2 Commits

Author SHA1 Message Date
admin f4ef9b32a5 feat(flow): 新增流程图视图(时序图自动生成);导出合并为菜单并支持 drawio;发布 v1.3.0
- 流程图视图:泳道 = 轨道、FS/SS 依赖连线、关键路径高亮、相位阶段栏
  (每个动作行归属覆盖占比最大的分区,重叠分区台阶错位)
- 无前置依赖的动作从「开始」并列引出(并行分支),无后继动作汇入「结束」
- 流程图只读:AI 生成 / 撤销重做 / 动作增删 / 属性与依赖编辑等入口自动置灰,
  左栏视图模式只保留条形 / 圆周(流程图入口在顶部工具栏)
- 导出升级:导出按钮合并为下拉菜单,SVG / PNG 三种视图通用;
  流程图额外支持 drawio(diagrams.net 可继续编辑泳道 / 相位 / 依赖)
- 连线走线统一收敛到 FlowLayout.routes,画布 / SVG / drawio 共用同一几何
- 默认示例升级为完整「装配线节拍」(8 动作 / 3 工位 / 4 相位分区)
- 版本号 1.3.0+16,更新说明 release/RELEASE_NOTES_v1.3.0.md
2026-10-09 13:59:05 +08:00
admin fe2008b604 fix(ui): 修复「适应视图」条形视图缩小后偏到左上角;发布 v1.2.3
- fitView 条形分支:内容被缩小时按内容范围居中显示
  (此前固定 pan=0,动作较多触发缩小时画面会钉在左上角)
- 圆周视图行为不变(原本即按圆心居中计算)
- tool/check_update.dart 改用 package 导入并声明 ignore,flutter analyze 归零
- 版本号 1.2.3+15
2026-10-09 10:24:48 +08:00
25 changed files with 1827 additions and 259 deletions
+1 -1
View File
@@ -127,7 +127,7 @@ flutter pub get
flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-release.apk flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-release.apk
``` ```
- 发布包归档:`release\sequence_diagram_android_v1.2.2_release.apk`(**本地保留,不入库**;exe 的 `dist\` 同理)。 - 发布包归档:`release\sequence_diagram_android_v1.2.3_release.apk`(**本地保留,不入库**;exe 的 `dist\` 同理)。
- 上架应用商店时建议在 `android\app\build.gradle.kts` 配置正式签名后再构建 AAB: - 上架应用商店时建议在 `android\app\build.gradle.kts` 配置正式签名后再构建 AAB:
`flutter build appbundle --release`。 `flutter build appbundle --release`。
- 应用名「时序图设计」、包名 `cc.sincos.sequence_diagram`、launcher 图标由 - 应用名「时序图设计」、包名 `cc.sincos.sequence_diagram`、launcher 图标由
+3 -3
View File
@@ -9,7 +9,7 @@
- **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致 - **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致
- **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES - **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES
## 正式版 V1.2.2 ## 正式版 V1.2.3
**可运行的 Flutter Windows 桌面正式版**(源码在 `lib/`),设计人:呆头鹅。 **可运行的 Flutter Windows 桌面正式版**(源码在 `lib/`),设计人:呆头鹅。
@@ -97,7 +97,7 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模
- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装; - **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装;
- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像: - **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像:
```bash ```bash
flutter build apk --release # 产物 → release/sequence_diagram_android_v1.2.2_release.apk flutter build apk --release # 产物 → release/sequence_diagram_android_v1.2.3_release.apk
``` ```
- **自测**:`test/tablet_layout_test.dart` 覆盖 1280×800、2560×1600、960×600、800×480、竖屏 800×1280、600×960 等 7 种分辨率的无溢出回归; - **自测**:`test/tablet_layout_test.dart` 覆盖 1280×800、2560×1600、960×600、800×480、竖屏 800×1280、600×960 等 7 种分辨率的无溢出回归;
- **demo 图**:`demo/tablet-*.png`(由 `test/tablet_screenshots_test.dart` 生成)。 - **demo 图**:`demo/tablet-*.png`(由 `test/tablet_screenshots_test.dart` 生成)。
@@ -113,6 +113,6 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模
- **软件**:时序图设计 · Sequence Diagram Studio - **软件**:时序图设计 · Sequence Diagram Studio
- **设计人**:呆头鹅 - **设计人**:呆头鹅
- **版本**:V1.2.2 - **版本**:V1.2.3
- **版权**:Copyright © 2026 呆头鹅。保留所有权利。 - **版权**:Copyright © 2026 呆头鹅。保留所有权利。
- **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md) - **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md)
+225
View File
@@ -0,0 +1,225 @@
/// drawio 导出写入器:把流程图序列化为 diagrams.net(draw.io)可编辑的 `.drawio` 文件。
///
/// 架构位置:
/// - 仅流程图视图支持(条形 / 圆周视图只有 SVG / PNG 两种导出);
/// - 几何完全复用 [FlowLayout](与屏幕画布、SVG 导出同一套坐标与走线),
/// 保证三种载体(画布 / drawio / SVG)内容一致;
/// - 输出标准 `<mxfile>` 文档:节点保留动作颜色与「时长 · 工位」语义,
/// 连线保留 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 文档字符串。
///
/// 返回:以 `<mxfile>` 开头、`</mxfile>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;约定每次导出新建实例。
String build() {
final FlowLayout layout = FlowLayout(project);
if (layout.nodes.isEmpty) {
return '<mxfile host="app.diagrams.net"><diagram id="flow" name="流程图">'
'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root>'
'</mxGraphModel></diagram></mxfile>';
}
// 平移到页内:原点统一挪到 (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('<mxfile host="app.diagrams.net" agent="Sequence Diagram Studio" '
'version="24.7.8" type="device">');
_b.write('<diagram id="flow" name="${_esc(project.name.isEmpty ? '流程图' : project.name)}">');
_b.write('<mxGraphModel dx="1600" dy="900" grid="1" gridSize="10" guides="1" '
'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '
'pageWidth="$pageW" pageHeight="$pageH" math="0" shadow="0">');
_b.write('<root>');
_b.write('<mxCell id="0"/>');
_b.write('<mxCell id="1" parent="0"/>');
_lanes(layout, ox, oy);
_phases(layout, ox, oy);
_edges(layout);
_nodes(layout, ox, oy);
_b.write('</root></mxGraphModel></diagram></mxfile>');
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('<mxCell id="edge-$i-${_cellId(e.fromId)}-${_cellId(e.toId)}" '
'value="${_esc(label)}" '
'style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;jettySize=auto;'
'orthogonalLoop=1;endArrow=block;endFill=1;'
'strokeWidth=${e.critical ? 2.4 : 1.3};strokeColor=$col;'
'${e.type == DepType.ss ? 'dashed=1;dashPattern=6 4;' : ''}'
'fontSize=9;fontColor=$col;labelBackgroundColor=${_hex(tokens.bg)};" '
'edge="1" parent="1" source="${_cellId(e.fromId)}" target="${_cellId(e.toId)}">'
'<mxGeometry relative="1" as="geometry"/></mxCell>');
}
}
/// 写入一个顶点(矩形 / 胶囊 / 竖带)单元格。
void _rectCell(String id, String value, double x, double y, double w, double h,
String style) {
_b.write('<mxCell id="$id" value="${_esc(value)}" '
'style="$style" vertex="1" parent="1">'
'<mxGeometry x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" '
'width="${w.toStringAsFixed(1)}" height="${h.toStringAsFixed(1)}" as="geometry"/>'
'</mxCell>');
}
/// 节点 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 文本 / 属性中的特殊字符;换行转为 `&#10;`(drawio 多行标签约定)。
static String _esc(String s) => s
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll('\n', '&#10;');
/// 把 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')}';
}
}
+15 -3
View File
@@ -13,6 +13,7 @@ import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action; import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart'; import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart'; import '../model/models.dart';
import '../model/units.dart'; import '../model/units.dart';
import '../render/bar_painter.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 int n = l.lanes.length;
final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.yFor(n) + BarLayout.rowVisual + 8; 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); bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom);
} else { } else if (mode == ViewMode.circular) {
final CircularLayout l = CircularLayout(project, kExportSize); final CircularLayout l = CircularLayout(project, kExportSize);
final double rExt = l.tickR + 100; 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); 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) { if (bounds.width <= 1 || bounds.height <= 1) {
return const ExportFit(1, 0, 0); return const ExportFit(1, 0, 0);
@@ -69,14 +74,21 @@ ExportFit computeExportFit(Project project, ViewMode mode, Rect area) {
} }
/// 导出标题(与画布浮层一致)。 /// 导出标题(与画布浮层一致)。
String exportTitle(ViewMode mode) => String exportTitle(ViewMode mode) => switch (mode) {
mode == ViewMode.bar ? '条形时序视图' : '圆周时序视图'; ViewMode.bar => '条形时序视图',
ViewMode.circular => '圆周时序视图',
ViewMode.flow => '流程图视图',
};
/// 导出副标题(与画布浮层一致)。 /// 导出副标题(与画布浮层一致)。
String exportSubtitle(Project project, ViewMode mode) { String exportSubtitle(Project project, ViewMode mode) {
if (mode == ViewMode.bar) { if (mode == ViewMode.bar) {
return '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)'; return '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)';
} }
if (mode == ViewMode.flow) {
// 流程图不重复线型说明,导出仅保留标题(与画布浮层一致)。
return '';
}
return '同心圆环 = 动作层 · 1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%'; return '同心圆环 = 动作层 · 1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%';
} }
+9
View File
@@ -14,6 +14,7 @@ import 'package:flutter/material.dart' hide Action;
import '../model/models.dart'; import '../model/models.dart';
import '../render/bar_painter.dart'; import '../render/bar_painter.dart';
import '../render/circular_painter.dart'; import '../render/circular_painter.dart';
import '../render/flow_painter.dart';
import '../theme/tokens.dart'; import '../theme/tokens.dart';
import 'export_fit.dart'; import 'export_fit.dart';
@@ -64,6 +65,14 @@ Future<Uint8List> renderExportPng({
criticalDeps: criticalDeps, criticalDeps: criticalDeps,
selectedIds: const <String>{}, selectedIds: const <String>{},
).paint(canvas, kExportSize); ).paint(canvas, kExportSize);
} else if (mode == ViewMode.flow) {
FlowchartPainter(
project: project,
tokens: et,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
} else { } else {
CircularPainter( CircularPainter(
project: project, project: project,
+106 -3
View File
@@ -21,6 +21,7 @@ import 'dart:math' as math;
import 'dart:ui'; import 'dart:ui';
import '../layout/layout.dart'; import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart'; import '../model/models.dart';
import '../model/units.dart'; import '../model/units.dart';
import '../theme/tokens.dart'; import '../theme/tokens.dart';
@@ -85,8 +86,10 @@ class SvgWriter {
_b.write('<g id="content" transform="${fit.svgTransform}">'); _b.write('<g id="content" transform="${fit.svgTransform}">');
if (mode == ViewMode.bar) { if (mode == ViewMode.bar) {
_barView(const Size(w, h)); _barView(const Size(w, h));
} else { } else if (mode == ViewMode.circular) {
_circularView(const Size(w, h)); _circularView(const Size(w, h));
} else {
_flowView();
} }
_b.write('</g>'); _b.write('</g>');
// 图例:固定左下角。 // 图例:固定左下角。
@@ -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('<g id="lanes">');
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
final double top = layout.bounds.top + 20;
final double bottom = layout.bounds.bottom - 20;
for (int i = 0; i < layout.lanes.length; i++) {
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2;
_rect(cx - FlowLayout.nodeW / 2 - 26, top, FlowLayout.nodeW + 52, bottom - top,
fill: _hex(i.isEven ? tokens.ringA : tokens.ringB), rx: 14, opacity: 0.55);
_text(cx, top + 16, '轨道 L${i + 1}',
color: _hex(tokens.sub), size: 11, anchor: 'middle', weight: '700');
}
_b.write('</g>');
// 相位竖带:窄带 + 旋转 90° 分区名,纵向对齐流程行、重叠分区台阶错位。
_b.write('<g id="phases">');
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
for (final FlowPhaseSpan s in layout.spans) {
final double pTop = FlowLayout.marginY + s.rankTop * rowPitch - 6;
final double pBottom =
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6;
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep;
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: _hex(tokens.accent), rx: 9, opacity: 0.10);
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: 'none', rx: 9, stroke: _hex(tokens.accent), sw: 1, opacity: 0.45);
final double tx = left + FlowLayout.railW / 2;
final double ty = (pTop + pBottom) / 2;
_b.write('<text transform="translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) rotate(-90)" '
'font-family="$_font" font-size="10.5" fill="${_hex(tokens.sub)}" text-anchor="middle" '
'dominant-baseline="middle" font-weight="700">${_esc(s.zone.name)}</text>');
}
_b.write('</g>');
// 依赖折线:FS 实线 / SS 虚线,带箭头与 FS/SS 标签。
_b.write('<g id="edges">');
for (final FlowEdgeRoute r in layout.routes) {
final FlowEdge e = r.edge;
final bool fs = e.type == DepType.fs;
final String col = _hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
final String d = <String>[
for (int i = 0; i < r.points.length; i++)
'${i == 0 ? 'M' : 'L'} ${r.points[i].dx.toStringAsFixed(1)} ${r.points[i].dy.toStringAsFixed(1)}',
].join(' ');
final String marker = e.type == null ? '' : ' marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"';
final String dash = r.dashed ? ' stroke-dasharray="6 4"' : '';
_b.write('<path d="$d" fill="none" stroke="$col" stroke-width="${e.critical ? 2 : 1.3}"'
'$dash$marker/>');
if (e.type != null) {
final String text = switch (e.type!) {
DepType.fs => 'FS',
DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°',
DepType.ff => 'FF',
DepType.sf => 'SF',
};
_text(r.labelAt.dx, r.labelAt.dy, text,
color: col, size: 9, anchor: 'middle', weight: '600');
}
}
_b.write('</g>');
// 动作节点与开始 / 结束胶囊。
_b.write('<g id="actions">');
for (final FlowNode n in layout.nodes) {
final Rect r = n.rect;
if (n.isStart || n.isEnd) {
_rect(r.left, r.top, r.width, r.height,
fill: _hex(tokens.panel2), rx: r.height / 2, stroke: _hex(tokens.accent), sw: 1.2);
_text(r.center.dx, r.center.dy, n.title,
color: _hex(tokens.accent), size: 13, anchor: 'middle', weight: '700');
continue;
}
final Action a = n.action!;
final Color c = Color(a.color);
_b.write('<g id="${_esc(n.id)}" data-action="${_esc(n.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
_rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 10, opacity: 0.92);
_text(r.center.dx, r.top + 21, n.title,
color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
_text(r.center.dx, r.top + 41, n.subtitle,
color: _hex(tokens.arcText), size: 10, anchor: 'middle');
_b.write('</g>');
}
_b.write('</g>');
}
/// 生成一段圆弧的 SVG `d` 路径字符串。 /// 生成一段圆弧的 SVG `d` 路径字符串。
/// ///
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。 /// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
@@ -290,9 +391,11 @@ class SvgWriter {
/// ///
/// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。 /// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。
void _rect(double x, double y, double w, double h, 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('<rect x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" width="${w.toStringAsFixed(1)}" ' _b.write('<rect x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" width="${w.toStringAsFixed(1)}" '
'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"/>'); 'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"'
'${stroke == null ? '' : ' stroke="$stroke" stroke-width="$sw"'}'
'/>');
} }
/// 写入一个 `<circle>` 元素。 /// 写入一个 `<circle>` 元素。
+448
View File
@@ -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<Offset> 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 <String>{},
this.criticalDeps = const <String>{},
}) {
_build();
}
/// 数据源项目。
final Project project;
/// 关键路径上的动作 id。
final Set<String> criticalActions;
/// 关键路径上的依赖(`from->to`)。
final Set<String> 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<FlowNode> nodes = <FlowNode>[];
/// 全部连线。
final List<FlowEdge> edges = <FlowEdge>[];
/// 泳道列表(轨道号,升序)。
List<int> lanes = <int>[];
/// 相位分区跨度(左侧阶段栏,按项目分区顺序)。
final List<FlowPhaseSpan> spans = <FlowPhaseSpan>[];
/// 连线走线结果(画布 / SVG / drawio 导出共用)。
final List<FlowEdgeRoute> routes = <FlowEdgeRoute>[];
/// 内容范围(所有节点矩形并集再外扩,供适应视图使用)。
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 = (<int>{for (final Action a in project.actions) a.layer}.toList())..sort();
final Map<String, FlowNode> byId = <String, FlowNode>{};
// 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<Action> ordered = List<Action>.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<String> hasPred = <String>{for (final FlowEdge e in edges) e.toId};
final Set<String> hasSucc = <String>{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<String, int> rank = <String, int>{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<int, int> laneIndex = <int, int>{
for (int i = 0; i < lanes.length; i++) lanes[i]: i,
};
final Map<String, int> cellTotal = <String, int>{};
for (final FlowNode n in nodes) {
final String key = '${n.lane}:${n.rank}';
cellTotal[key] = (cellTotal[key] ?? 0) + 1;
}
final Map<String, int> cellSeen = <String, int>{};
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<String, int> fanIndex = <String, int>{};
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>[
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>[
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<PhaseZone> zones = project.phaseZones;
final Map<String, int> dominant = <String, int>{};
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<int> used = <int>{};
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 <double>[-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;
}
+102 -32
View File
@@ -17,6 +17,9 @@ enum ViewMode {
/// 圆周(环形)节拍视图。 /// 圆周(环形)节拍视图。
circular, circular,
/// 流程图视图(由时序图自动生成,只读)。
flow,
} }
/// 时间单位。 /// 时间单位。
@@ -666,7 +669,11 @@ class ViewState {
final List<dynamic> pan = (j['pan'] as List<dynamic>?) ?? <dynamic>[0, 0]; final List<dynamic> pan = (j['pan'] as List<dynamic>?) ?? <dynamic>[0, 0];
final List<dynamic> sel = (j['selectedIds'] as List<dynamic>?) ?? <dynamic>[]; final List<dynamic> sel = (j['selectedIds'] as List<dynamic>?) ?? <dynamic>[];
return ViewState( 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, zoom: (j['zoom'] as num?)?.toDouble() ?? 1,
panX: (pan.isNotEmpty ? (pan[0] as num?)?.toDouble() : 0) ?? 0, panX: (pan.isNotEmpty ? (pan[0] as num?)?.toDouble() : 0) ?? 0,
panY: (pan.length > 1 ? (pan[1] 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() { static Project demo() {
final List<Station> stations = <Station>[ return Project(
const Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0), name: '装配线节拍',
const Station(id: 'ST2', name: '工位 2', order: 1, color: 0xFFFFD166), cycle: const Cycle(durationMs: 2400),
]; stations: const <Station>[
final List<Action> actions = <Action>[ Station(id: 'ST1', name: '上料工位', order: 0, color: 0xFF4CC9F0),
Action( Station(id: 'ST2', name: '加工工位', order: 1, color: 0xFFFFD166),
Station(id: 'ST3', name: '检测工位', order: 2, color: 0xFF34D399),
],
actions: <Action>[
const Action(
id: 'A1', id: 'A1',
name: '动作 1', name: '上料',
stationId: 'ST1', stationId: 'ST1',
driver: '气缸 Y1', driver: '气缸 Y1',
startAngle: 0, startAngle: 0,
durationAngle: 70, durationAngle: 45,
layer: 0, layer: 0,
row: 0, color: 0xFF4CC9F0),
color: kActionPalette[0], const Action(
),
Action(
id: 'A2', id: 'A2',
name: '动作 2', name: '定位夹紧',
stationId: 'ST2', stationId: 'ST1',
driver: '气缸 Y2', driver: '气缸 Y2',
startAngle: 80, startAngle: 50,
durationAngle: 60, durationAngle: 55,
layer: 0,
color: 0xFF7BD88F,
deps: <Dependency>[Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)]),
const Action(
id: 'A3',
name: '伺服下压',
stationId: 'ST2',
driver: '伺服 M1',
startAngle: 90,
durationAngle: 70,
layer: 1, layer: 1,
row: 1, color: 0xFFFFD166,
color: kActionPalette[1], deps: <Dependency>[Dependency(fromId: 'A2', toId: 'A3', type: DepType.fs)]),
deps: const <Dependency>[ const Action(
Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs), id: 'A4',
name: '超声焊接',
stationId: 'ST2',
driver: '超声 U1',
startAngle: 100,
durationAngle: 50,
layer: 2,
color: 0xFFF472B6,
deps: <Dependency>[
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>[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>[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>[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>[
PhaseZone(name: '上料相位', startAngle: 0, endAngle: 70),
PhaseZone(name: '加工相位', startAngle: 70, endAngle: 200),
PhaseZone(name: '检测相位', startAngle: 200, endAngle: 300),
PhaseZone(name: '下料相位', startAngle: 300, endAngle: 360),
], ],
),
];
return Project(
name: '未命名节拍',
cycle: const Cycle(durationMs: 3600),
stations: stations,
actions: actions,
units: const UnitSettings(),
viewState: const ViewState(mode: ViewMode.bar, selectedIds: <String>['A1']),
); );
} }
} }
+279
View File
@@ -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<String> criticalActions;
/// 关键路径依赖(`from->to`)。
final Set<String> criticalDeps;
/// 选中动作 id。
final Set<String> 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;
}
+38 -8
View File
@@ -14,6 +14,7 @@ import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action; import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart'; import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart'; import '../model/models.dart';
import '../model/units.dart'; import '../model/units.dart';
import '../persistence/storage.dart'; import '../persistence/storage.dart';
@@ -304,11 +305,19 @@ class AppController extends ChangeNotifier {
/// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。 /// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。
static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last; static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last;
/// 切换视图模式并更新状态栏文本。 /// 切换视图模式(条形 / 圆周 / 流程图)并更新状态栏文本。
///
/// 三种视图共用同一套缩放 / 平移状态,切换后自动适配一次视图
/// (各视图坐标系与内容范围不同,避免出现「看不到内容」)。
void setViewMode(ViewMode mode) { void setViewMode(ViewMode mode) {
_project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode)); _project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode));
_status = mode == ViewMode.bar ? '条形节拍视图' : '圆周节拍视图'; _status = switch (mode) {
ViewMode.bar => '条形节拍视图',
ViewMode.circular => '圆周节拍视图',
ViewMode.flow => '流程图视图(只读)',
};
notifyListeners(); notifyListeners();
fitView(silent: true);
} }
/// 选中指定动作([id] 为 null 表示清空选中)并刷新。 /// 选中指定动作([id] 为 null 表示清空选中)并刷新。
@@ -432,8 +441,11 @@ class AppController extends ChangeNotifier {
/// ///
/// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放, /// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放,
/// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。 /// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。
/// - 条形视图:布局本身按视口高度自适应,直接回到 `zoom = 1`。 /// - 条形视图:布局本身按视口高度自适应,动作较多触发缩小时内容居中。
void fitView() { /// - 流程图:按节点内容范围适配并居中。
///
/// [silent] 为真时不改写状态栏文案(供视图切换时自动调用)。
void fitView({bool silent = false}) {
final Size vp = _viewport; final Size vp = _viewport;
if (vp.width <= 0 || vp.height <= 0) { if (vp.width <= 0 || vp.height <= 0) {
resetView(); resetView();
@@ -442,7 +454,22 @@ class AppController extends ChangeNotifier {
double z = 1; double z = 1;
double px = 0; double px = 0;
double py = 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); final CircularLayout l = CircularLayout(_project, vp);
// 半径需覆盖:刻度文字(tickR + ~50)、顺时针箭头(rMax + ~70)、 // 半径需覆盖:刻度文字(tickR + ~50)、顺时针箭头(rMax + ~70)、
// 12 点钟起点标记(tickR + ~70),再留 20px 余量,避免任何标注被裁掉。 // 12 点钟起点标记(tickR + ~70),再留 20px 余量,避免任何标注被裁掉。
@@ -456,16 +483,19 @@ class AppController extends ChangeNotifier {
py = vp.height / 2 - center.dy * z; py = vp.height / 2 - center.dy * z;
} else { } else {
final BarLayout l = BarLayout(_project, vp); final BarLayout l = BarLayout(_project, vp);
// 内容逻辑范围:(0,0) → 右缘 + 60、最后一行底部 + 40。
final double contentW = l.plotRight + 60; final double contentW = l.plotRight + 60;
final double contentH = l.yFor(l.ordered.length) + 40; final double contentH = l.yFor(l.ordered.length) + 40;
z = math.min(vp.width / contentW, vp.height / contentH).clamp(0.25, 1.0); z = math.min(vp.width / contentW, vp.height / contentH).clamp(0.25, 1.0);
px = 0; // 关键修复:内容被缩小时按内容范围居中显示;内容本来就能放下时保持默认位置。
py = 0; // (此前固定 pan = 0,缩小的画面会被钉在左上角。)
px = z < 1 ? (vp.width - contentW * z) / 2 : 0;
py = z < 1 ? (vp.height - contentH * z) / 2 : 0;
} }
_project = _project.copyWith( _project = _project.copyWith(
viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py), viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py),
); );
_status = '适应窗口'; if (!silent) _status = '适应窗口';
notifyListeners(); notifyListeners();
} }
+285 -90
View File
@@ -15,6 +15,7 @@ import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action; import 'package:flutter/material.dart' hide Action;
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import '../export/drawio_writer.dart';
import '../export/export_renderer.dart'; import '../export/export_renderer.dart';
import '../export/svg_writer.dart'; import '../export/svg_writer.dart';
import '../model/models.dart'; import '../model/models.dart';
@@ -250,6 +251,8 @@ class _AppShellState extends State<AppShell> {
} }
/// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。
///
/// 三种视图均支持(流程图由 [FlowLayout] 几何直接生成)。
Future<void> _exportSvg() async { Future<void> _exportSvg() async {
if (!c.licensed) { if (!c.licensed) {
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。');
@@ -300,6 +303,8 @@ class _AppShellState extends State<AppShell> {
} }
/// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。 /// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。
///
/// 三种视图均支持(流程图走 [FlowchartPainter] 离屏渲染)。
Future<void> _exportPng() async { Future<void> _exportPng() async {
if (!c.licensed) { if (!c.licensed) {
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
@@ -352,6 +357,55 @@ class _AppShellState extends State<AppShell> {
} }
} }
/// 导出 drawio:仅流程图视图提供,输出 diagrams.net 可直接打开并继续编辑的 XML。
///
/// 条形 / 圆周视图调用时给出明确提示(不做静默失败)。
Future<void> _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<String>(
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<AppShell> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Tokens t = context.tok; final Tokens t = context.tok;
// 流程图视图只读:撤销 / 重做 / 删除等编辑操作统一停用(与置灰按钮一致)。
final bool flow = c.project.viewState.mode == ViewMode.flow;
// 全局快捷键绑定:编辑、文件、帮助、主题等。 // 全局快捷键绑定:编辑、文件、帮助、主题等。
return CallbackShortcuts( return CallbackShortcuts(
bindings: <ShortcutActivator, VoidCallback>{ bindings: <ShortcutActivator, VoidCallback>{
const SingleActivator(LogicalKeyboardKey.keyZ, control: true): c.undo, const SingleActivator(LogicalKeyboardKey.keyZ, control: true): () {
const SingleActivator(LogicalKeyboardKey.keyY, control: true): c.redo, if (!flow) c.undo();
},
const SingleActivator(LogicalKeyboardKey.keyY, control: true): () {
if (!flow) c.redo();
},
const SingleActivator(LogicalKeyboardKey.keyS, control: true): _save, const SingleActivator(LogicalKeyboardKey.keyS, control: true): _save,
const SingleActivator(LogicalKeyboardKey.keyO, control: true): _open, const SingleActivator(LogicalKeyboardKey.keyO, control: true): _open,
const SingleActivator(LogicalKeyboardKey.keyN, control: true): _newProject, const SingleActivator(LogicalKeyboardKey.keyN, control: true): _newProject,
const SingleActivator(LogicalKeyboardKey.delete): () { 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): () => const SingleActivator(LogicalKeyboardKey.f1): () =>
showDialog<void>(context: context, builder: (_) => const HelpDialog()), showDialog<void>(context: context, builder: (_) => const HelpDialog()),
@@ -509,6 +569,7 @@ class _AppShellState extends State<AppShell> {
/// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。 /// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。
Widget _toolbar(Tokens t) { Widget _toolbar(Tokens t) {
final double s = _toolScale; final double s = _toolScale;
final bool flow = c.project.viewState.mode == ViewMode.flow;
return Container( return Container(
height: 54 * s, height: 54 * s,
padding: EdgeInsets.symmetric(horizontal: 6 * s), padding: EdgeInsets.symmetric(horizontal: 6 * s),
@@ -570,18 +631,19 @@ class _AppShellState extends State<AppShell> {
_iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'),
_iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'),
SizedBox(width: 6 * 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), SizedBox(width: 6 * s),
_aiBtn(t), _aiBtn(t),
SizedBox(width: 12 * s), SizedBox(width: 12 * s),
_segmented(t), _segmented(t),
]; ];
right = <Widget>[ right = <Widget>[
// 未授权时导出按钮置灰(授权有效才允许导出)。 // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。
_primaryBtn(t, '导出 SVG', c.licensed ? _exportSvg : null), _exportMenu(t),
SizedBox(width: 6 * s),
_ghost(t, '导出 PNG', c.licensed ? _exportPng : null),
SizedBox(width: 6 * s), SizedBox(width: 6 * s),
_zoomBox(t), _zoomBox(t),
SizedBox(width: 6 * s), SizedBox(width: 6 * s),
@@ -593,6 +655,8 @@ class _AppShellState extends State<AppShell> {
sideToggleRight, sideToggleRight,
_iconBtn(t, Icons.help_outline, () => _iconBtn(t, Icons.help_outline, () =>
showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'),
_iconBtn(t, Icons.account_tree_outlined, () => c.setViewMode(ViewMode.flow),
tooltip: '流程图(由时序图生成)'),
_updateBtn(t), _updateBtn(t),
_themeToggle(t), _themeToggle(t),
]; ];
@@ -612,8 +676,11 @@ class _AppShellState extends State<AppShell> {
_iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'),
_iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'),
SizedBox(width: 4 * 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), SizedBox(width: 4 * s),
// AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。
_aiBtn(t), _aiBtn(t),
@@ -621,10 +688,8 @@ class _AppShellState extends State<AppShell> {
_segmented(t, compact: true), _segmented(t, compact: true),
]; ];
right = <Widget>[ right = <Widget>[
// 导出保持两个独立按钮;未授权时置灰。 // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。
_ghost(t, '导出 SVG', c.licensed ? _exportSvg : null), _exportMenu(t),
SizedBox(width: 4 * s),
_ghost(t, '导出 PNG', c.licensed ? _exportPng : null),
SizedBox(width: 4 * s), SizedBox(width: 4 * s),
_zoomBox(t), _zoomBox(t),
_iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'),
@@ -633,6 +698,8 @@ class _AppShellState extends State<AppShell> {
sideToggleRight, sideToggleRight,
_iconBtn(t, Icons.help_outline, () => _iconBtn(t, Icons.help_outline, () =>
showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), showDialog<void>(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'),
_iconBtn(t, Icons.account_tree_outlined, () => c.setViewMode(ViewMode.flow),
tooltip: '流程图(由时序图生成)'),
_updateBtn(t), _updateBtn(t),
_themeToggle(t), _themeToggle(t),
]; ];
@@ -654,17 +721,17 @@ class _AppShellState extends State<AppShell> {
); );
} }
/// 视图模式分段控件:条形节拍 / 圆周节拍一键切换。 /// 视图模式分段控件:条形节拍 / 圆周节拍 / 流程图 一键切换。
/// ///
/// [compact] 为真时使用更窄的宽度,适配 1920×1080 等较小窗口。 /// [compact] 为真时使用更窄的宽度,适配 1920×1080 等较小窗口。
Widget _segmented(Tokens t, {bool compact = false}) { 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) { Widget seg(String label, bool active, VoidCallback onTap) {
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Container( child: Container(
width: (compact ? 96 : 140) * _toolScale, width: (compact ? 84 : 118) * _toolScale,
height: 34 * _toolScale, height: 34 * _toolScale,
alignment: Alignment.center, alignment: Alignment.center,
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -691,8 +758,9 @@ class _AppShellState extends State<AppShell> {
), ),
child: Row( child: Row(
children: <Widget>[ children: <Widget>[
seg('条形节拍', bar, () => c.setViewMode(ViewMode.bar)), seg('条形节拍', mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar)),
seg('圆周节拍', !bar, () => c.setViewMode(ViewMode.circular)), seg('圆周节拍', mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular)),
seg('流程图', mode == ViewMode.flow, () => c.setViewMode(ViewMode.flow)),
], ],
), ),
); );
@@ -807,67 +875,121 @@ class _AppShellState extends State<AppShell> {
); );
} }
/// 次要(幽灵)样式按钮;[onTap] 为 null 时呈禁用态;尺寸随 [_toolScale] 缩放。 /// 导出下拉菜单:合并原「导出 SVG / 导出 PNG」两个按钮。
Widget _ghost(Tokens t, String label, VoidCallback? onTap, {IconData? icon}) { ///
/// 选项规则(1.3 产品约定):
/// - 「导出 SVG」「导出 PNG」三种视图(条形 / 圆周 / 流程图)均可用;
/// - 「导出 drawio」仅在流程图视图出现(条形 / 圆周视图不提供);
/// - 未授权时各项置灰(桌面无 license 不允许导出)。
Widget _exportMenu(Tokens t) {
final double s = _toolScale; 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( return Padding(
padding: EdgeInsets.symmetric(horizontal: 3 * s), padding: EdgeInsets.symmetric(horizontal: 3 * s),
child: TextButton.icon( child: PopupMenuButton<String>(
onPressed: onTap, tooltip: '导出(SVG / PNG${flow ? ' / drawio' : ''})',
icon: icon == null ? null : Icon(icon, size: 16 * s, color: onTap == null ? t.dim : t.text), color: t.panel2,
label: Text(label, style: TextStyle(fontSize: _toolFont(11), color: onTap == null ? t.dim : t.text)), position: PopupMenuPosition.under,
style: TextButton.styleFrom( onSelected: (String v) {
backgroundColor: t.panel, if (v == 'svg') _exportSvg();
side: BorderSide(color: t.line2), if (v == 'png') _exportPng();
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), if (v == 'drawio') _exportDrawio();
padding: EdgeInsets.symmetric(horizontal: 12 * s, vertical: 10 * s), },
minimumSize: Size(0, 34 * s), itemBuilder: (BuildContext ctx) => <PopupMenuEntry<String>>[
tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null, _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: <Widget>[
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 时禁用(置灰); /// 导出菜单单项:图标 + 名称 + 一句说明;[enabled] 为 false 时整体置灰。
/// 尺寸随 [_toolScale] 缩放。 ///
Widget _primaryBtn(Tokens t, String label, VoidCallback? onTap) { /// 菜单宽度有限(PopupMenu 默认上限约 256px),文本统一单行省略,
final bool enabled = onTap != null; /// 避免窄窗口 / 紧凑布局下溢出。
final double s = _toolScale; PopupMenuItem<String> _exportItem(
return FilledButton( Tokens t, String value, IconData icon, String label, String hint, bool enabled) {
onPressed: onTap, final Color main = enabled ? t.text : t.dim;
style: FilledButton.styleFrom( return PopupMenuItem<String>(
backgroundColor: enabled ? t.accent2 : t.panel2, value: value,
foregroundColor: enabled ? Colors.white : t.dim, enabled: enabled,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), height: 46,
padding: EdgeInsets.symmetric(horizontal: 16 * s, vertical: 10 * s), child: Row(
minimumSize: Size(0, 34 * s), children: <Widget>[
tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null, Icon(icon, size: 17, color: enabled ? t.accent : t.dim),
const SizedBox(width: 10),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
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 生成按钮:打开「自然语言 → 时序图」对话框;尺寸随 [_toolScale] 缩放。
///
/// AI 只服务时序图(生成条形 / 圆周视图的底层数据),流程图页置灰禁用。
Widget _aiBtn(Tokens t) { Widget _aiBtn(Tokens t) {
final double s = _toolScale; final double s = _toolScale;
return Padding( final bool enabled = c.project.viewState.mode != ViewMode.flow;
padding: EdgeInsets.symmetric(horizontal: 3 * s), final Widget btn = FilledButton.icon(
child: FilledButton.icon( onPressed: enabled
onPressed: () => showDialog<void>( ? () => showDialog<void>(
context: context, context: context,
builder: (_) => AiGenerateDialog(controller: c), builder: (_) => AiGenerateDialog(controller: c),
), )
: null,
icon: Icon(Icons.auto_awesome, size: 16 * s), icon: Icon(Icons.auto_awesome, size: 16 * s),
label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)),
style: FilledButton.styleFrom( style: FilledButton.styleFrom(
backgroundColor: t.accent2, backgroundColor: enabled ? t.accent2 : t.panel2,
foregroundColor: Colors.white, foregroundColor: enabled ? Colors.white : t.dim,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s),
minimumSize: Size(0, 34 * s), minimumSize: Size(0, 34 * s),
tapTargetSize: MaterialTapTargetSize.shrinkWrap, tapTargetSize: MaterialTapTargetSize.shrinkWrap,
), ),
), );
return Padding(
padding: EdgeInsets.symmetric(horizontal: 3 * s),
child: enabled ? btn : Tooltip(message: 'AI 生成仅针对时序图(条形 / 圆周视图)', child: btn),
); );
} }
@@ -1038,6 +1160,7 @@ class _AppShellState extends State<AppShell> {
/// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。
Widget _leftPanel(Tokens t, {bool floating = false}) { Widget _leftPanel(Tokens t, {bool floating = false}) {
final bool bar = c.project.viewState.mode == ViewMode.bar; final bool bar = c.project.viewState.mode == ViewMode.bar;
final bool flow = c.project.viewState.mode == ViewMode.flow;
return Container( return Container(
width: _leftPanelWidth, width: _leftPanelWidth,
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -1064,6 +1187,7 @@ class _AppShellState extends State<AppShell> {
t, t,
icon: Icons.edit_note, icon: Icons.edit_note,
label: '编辑时序与节拍参数', label: '编辑时序与节拍参数',
enabled: !flow,
onTap: () => showDialog<void>( onTap: () => showDialog<void>(
context: context, context: context,
builder: (_) => SettingsDialog(controller: c), builder: (_) => SettingsDialog(controller: c),
@@ -1077,16 +1201,17 @@ class _AppShellState extends State<AppShell> {
children: <Widget>[ children: <Widget>[
// 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。 // 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。
Expanded(child: _sectionLabel(t, '动作和执行编辑')), 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), const SizedBox(width: 6),
// 至少保留一个动作 / 泳道:只剩一个时禁用删除。 // 至少保留一个动作 / 泳道:只剩一个时禁用删除;流程图只读时禁用。
_headerAction( _headerAction(
t, t,
Icons.delete_outline, Icons.delete_outline,
'删除', '删除',
t.danger, t.danger,
Colors.white, Colors.white,
(c.selectedId == null || c.project.actions.length <= 1) (flow || c.selectedId == null || c.project.actions.length <= 1)
? null ? null
: () => c.deleteAction(c.selectedId!), : () => c.deleteAction(c.selectedId!),
), ),
@@ -1103,18 +1228,20 @@ class _AppShellState extends State<AppShell> {
icon: Icons.precision_manufacturing_outlined, icon: Icons.precision_manufacturing_outlined,
label: '编辑工位', label: '编辑工位',
badge: c.project.stations.length, badge: c.project.stations.length,
enabled: !flow,
onTap: () => showDialog<void>( onTap: () => showDialog<void>(
context: context, context: context,
builder: (_) => StationDialog(controller: c), builder: (_) => StationDialog(controller: c),
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
// 相位分区:可任意增删、改名、改起止角。 // 相位分区:可任意增删、改名、改起止角;流程图只读时置灰。
_editEntry( _editEntry(
t, t,
icon: Icons.tune, icon: Icons.tune,
label: '编辑相位分区', label: '编辑相位分区',
badge: c.project.phaseZones.length, badge: c.project.phaseZones.length,
enabled: !flow,
onTap: () => showDialog<void>( onTap: () => showDialog<void>(
context: context, context: context,
builder: (_) => PhaseZoneDialog(controller: c), builder: (_) => PhaseZoneDialog(controller: c),
@@ -1123,11 +1250,13 @@ class _AppShellState extends State<AppShell> {
const SizedBox(height: 12), const SizedBox(height: 12),
_sectionLabel(t, '视图模式'), _sectionLabel(t, '视图模式'),
const SizedBox(height: 8), const SizedBox(height: 8),
// 该栏永久只保留条形 / 圆周两个时序视图的切换;
// 流程图由时序图生成、属独立载体,入口在顶部工具栏(不在本栏混排)。
Row( Row(
children: <Widget>[ children: <Widget>[
Expanded(child: _modeButton(t, '条形节拍(甘特)', bar, () => c.setViewMode(ViewMode.bar))), Expanded(child: _modeButton(t, '条形节拍(甘特)', c.project.viewState.mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar))),
const SizedBox(width: 10), const SizedBox(width: 8),
Expanded(child: _modeButton(t, '圆周节拍(同心)', !bar, () => c.setViewMode(ViewMode.circular))), Expanded(child: _modeButton(t, '圆周节拍(同心)', c.project.viewState.mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular))),
], ],
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -1151,10 +1280,17 @@ class _AppShellState extends State<AppShell> {
children: <Widget>[ children: <Widget>[
Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)),
const SizedBox(height: 6), const SizedBox(height: 6),
// 提示随视图模式切换:流程图是只读预览,给出交互方式说明。
if (flow) ...<Widget>[
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 ...<Widget>[
Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.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('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)),
Text('双击空白新建动作 · F1 打开帮助', 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<AppShell> {
/// 侧栏中的“单行编辑入口”卡片:图标 + 文案 + 可选计数徽标 + 右箭头。 /// 侧栏中的“单行编辑入口”卡片:图标 + 文案 + 可选计数徽标 + 右箭头。
/// ///
/// 用于把复杂的设置模块收敛为一个点击即可进入的入口。 /// 用于把复杂的设置模块收敛为一个点击即可进入的入口。
/// [enabled] 为 false 时整体置灰(流程图只读视图下禁用编辑入口)。
Widget _editEntry( Widget _editEntry(
Tokens t, { Tokens t, {
required IconData icon, required IconData icon,
required String label, required String label,
required VoidCallback onTap, required VoidCallback onTap,
int? badge, int? badge,
bool enabled = true,
}) { }) {
return InkWell( final Widget card = InkWell(
onTap: onTap, onTap: enabled ? onTap : null,
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),
@@ -1193,18 +1331,19 @@ class _AppShellState extends State<AppShell> {
), ),
child: Row( child: Row(
children: <Widget>[ children: <Widget>[
Icon(icon, size: 16, color: t.accent), Icon(icon, size: 16, color: enabled ? t.accent : t.dim),
const SizedBox(width: 8), 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) ...<Widget>[ if (badge != null) ...<Widget>[
Container( Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration( 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), borderRadius: BorderRadius.circular(6),
), ),
child: Text('$badge', 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), const SizedBox(width: 4),
], ],
@@ -1213,6 +1352,8 @@ class _AppShellState extends State<AppShell> {
), ),
), ),
); );
if (enabled) return card;
return Tooltip(message: '流程图只读:修改请切回条形 / 圆周视图', child: card);
} }
/// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。 /// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。
@@ -1259,6 +1400,7 @@ class _AppShellState extends State<AppShell> {
/// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。 /// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。
Widget _laneRow(Tokens t, int lane, int li, List<Action> acts, bool bar) { Widget _laneRow(Tokens t, int lane, int li, List<Action> acts, bool bar) {
if (acts.isEmpty) return const SizedBox.shrink(); if (acts.isEmpty) return const SizedBox.shrink();
final bool flow = c.project.viewState.mode == ViewMode.flow;
final Action primary = final Action primary =
acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first); acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first);
final bool sel = c.isSelected(primary.id); final bool sel = c.isSelected(primary.id);
@@ -1278,8 +1420,10 @@ class _AppShellState extends State<AppShell> {
toggle: HardwareKeyboard.instance.isControlPressed || toggle: HardwareKeyboard.instance.isControlPressed ||
HardwareKeyboard.instance.isShiftPressed, HardwareKeyboard.instance.isShiftPressed,
), ),
// 双击泳道行直接编辑该泳道的主动作。 // 双击泳道行直接编辑该泳道的主动作(流程图只读时禁用)。
onDoubleTap: () => showDialog<void>( onDoubleTap: flow
? null
: () => showDialog<void>(
context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)),
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Container( child: Container(
@@ -1347,7 +1491,9 @@ class _AppShellState extends State<AppShell> {
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
InkWell( InkWell(
onTap: () => showDialog<void>( onTap: flow
? null
: () => showDialog<void>(
context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)),
borderRadius: BorderRadius.circular(7), borderRadius: BorderRadius.circular(7),
child: Container( child: Container(
@@ -1358,7 +1504,7 @@ class _AppShellState extends State<AppShell> {
borderRadius: BorderRadius.circular(7), borderRadius: BorderRadius.circular(7),
border: Border.all(color: t.line2), 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<AppShell> {
/// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。
Widget _actionRow(Tokens t, Action a, int i, bool bar) { 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 bool sel = c.isSelected(a.id);
final Station? st = c.project.stationById(a.stationId); final Station? st = c.project.stationById(a.stationId);
return Padding( return Padding(
@@ -1381,8 +1528,10 @@ class _AppShellState extends State<AppShell> {
toggle: HardwareKeyboard.instance.isControlPressed || toggle: HardwareKeyboard.instance.isControlPressed ||
HardwareKeyboard.instance.isShiftPressed, HardwareKeyboard.instance.isShiftPressed,
), ),
// 双击动作行直接进入编辑。 // 双击动作行直接进入编辑(流程图只读时禁用)。
onDoubleTap: () => showDialog<void>( onDoubleTap: flow
? null
: () => showDialog<void>(
context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)),
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Container( child: Container(
@@ -1439,7 +1588,9 @@ class _AppShellState extends State<AppShell> {
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
InkWell( InkWell(
onTap: () => showDialog<void>( onTap: flow
? null
: () => showDialog<void>(
context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)),
borderRadius: BorderRadius.circular(7), borderRadius: BorderRadius.circular(7),
child: Container( child: Container(
@@ -1450,11 +1601,11 @@ class _AppShellState extends State<AppShell> {
borderRadius: BorderRadius.circular(7), borderRadius: BorderRadius.circular(7),
border: Border.all(color: t.line2), 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) ...<Widget>[ if (sel && !flow && c.project.actions.length > 1) ...<Widget>[
const SizedBox(width: 4), const SizedBox(width: 4),
InkWell( InkWell(
onTap: () => c.deleteAction(a.id), onTap: () => c.deleteAction(a.id),
@@ -1598,6 +1749,7 @@ class _AppShellState extends State<AppShell> {
Widget _rightPanel(Tokens t, {bool floating = false}) { Widget _rightPanel(Tokens t, {bool floating = false}) {
final Action? a = c.selected; final Action? a = c.selected;
final bool bar = c.project.viewState.mode == ViewMode.bar; final bool bar = c.project.viewState.mode == ViewMode.bar;
final bool flow = c.project.viewState.mode == ViewMode.flow;
return Container( return Container(
width: _rightPanelWidth, width: _rightPanelWidth,
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -1632,15 +1784,49 @@ class _AppShellState extends State<AppShell> {
children: <Widget>[ children: <Widget>[
_selectedHeader(t, a, bar), _selectedHeader(t, a, bar),
const SizedBox(height: 14), const SizedBox(height: 14),
// 流程图只读提示:节点与连线自动生成,编辑请回时序视图。
if (flow) ...<Widget>[
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: <Widget>[
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), ..._propertyFields(t, a, bar),
const SizedBox(height: 10), const SizedBox(height: 10),
if (!bar) ...<Widget>[ if (!bar) ...<Widget>[
_sectionLabel(t, '角度编辑'), _sectionLabel(t, '角度编辑'),
const SizedBox(height: 8), const SizedBox(height: 8),
// 流程图只读:滑块仅展示数值,不可拖动。
Opacity(
opacity: flow ? 0.45 : 1,
child: IgnorePointer(
ignoring: flow,
child: Column(
children: <Widget>[
_slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units),
(double v) => c.setActionStart(a.id, v * 360)), (double v) => c.setActionStart(a.id, v * 360)),
_slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units),
(double v) => c.setActionDuration(a.id, v * 180)), (double v) => c.setActionDuration(a.id, v * 180)),
],
),
),
),
const SizedBox(height: 8), const SizedBox(height: 8),
], ],
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -1650,10 +1836,12 @@ class _AppShellState extends State<AppShell> {
if (a.deps.isEmpty) if (a.deps.isEmpty)
Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11)) Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11))
else 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), const SizedBox(height: 6),
OutlinedButton.icon( OutlinedButton.icon(
onPressed: () => showDialog<void>( onPressed: flow
? null
: () => showDialog<void>(
context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)),
icon: const Icon(Icons.add_link, size: 15), icon: const Icon(Icons.add_link, size: 15),
label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)), label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)),
@@ -1673,7 +1861,7 @@ class _AppShellState extends State<AppShell> {
Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11)) Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11))
else else
for (final (Action target, Dependency d) in _outgoingDeps(a)) 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), const SizedBox(height: 12),
_helpCard(t), _helpCard(t),
], ],
@@ -1866,7 +2054,9 @@ class _AppShellState extends State<AppShell> {
} }
/// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。 /// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。
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; final Color col = d.type == DepType.fs ? t.fs : t.ss;
return Container( return Container(
margin: const EdgeInsets.only(bottom: 5), margin: const EdgeInsets.only(bottom: 5),
@@ -1887,8 +2077,8 @@ class _AppShellState extends State<AppShell> {
), ),
), ),
InkWell( InkWell(
onTap: () => c.removeDependency(d.fromId, a.id), onTap: enabled ? () => c.removeDependency(d.fromId, a.id) : null,
child: Icon(Icons.close, size: 14, color: t.dim), child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2),
), ),
], ],
), ),
@@ -1896,7 +2086,9 @@ class _AppShellState extends State<AppShell> {
} }
/// 输出依赖展示行:本动作 [a] 作为前置指向 [target],可删除。 /// 输出依赖展示行:本动作 [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; final Color col = d.type == DepType.fs ? t.fs : t.ss;
return Container( return Container(
margin: const EdgeInsets.only(bottom: 5), margin: const EdgeInsets.only(bottom: 5),
@@ -1917,8 +2109,8 @@ class _AppShellState extends State<AppShell> {
), ),
), ),
InkWell( InkWell(
onTap: () => c.removeDependency(a.id, target.id), onTap: enabled ? () => c.removeDependency(a.id, target.id) : null,
child: Icon(Icons.close, size: 14, color: t.dim), child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2),
), ),
], ],
), ),
@@ -1959,14 +2151,17 @@ class _AppShellState extends State<AppShell> {
/// 当前状态消息,右侧提示未保存状态与常用快捷键。 /// 当前状态消息,右侧提示未保存状态与常用快捷键。
Widget _statusBar(Tokens t) { Widget _statusBar(Tokens t) {
final UnitSettings u = c.project.units; 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<String> items = <String>[ final List<String> items = <String>[
'循环周期 ${tfmt(c.project.cycle.durationMs, u)}', '循环周期 ${tfmt(c.project.cycle.durationMs, u)}',
'相位 360° = 100%', '相位 360° = 100%',
'动作 ${c.project.actions.length}', '动作 ${c.project.actions.length}',
'依赖 ${_depCount()}', '依赖 ${_depCount()}',
circular ? '轨道 L1–L${c.project.laneCount}' : '工位 ${c.project.stations.length}', 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)}', '单位 ${timeUnitLabel(u.timeUnit)} / ${phaseUnitLabel(u.phaseUnit)}',
'1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}', '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}',
c.status, c.status,
+25 -13
View File
@@ -56,7 +56,9 @@ class CanvasOverlays extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Tokens t = context.tok; 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( return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) { builder: (BuildContext context, BoxConstraints constraints) {
final double w = constraints.maxWidth; final double w = constraints.maxWidth;
@@ -82,7 +84,7 @@ class CanvasOverlays extends StatelessWidget {
left: left, left: left,
top: 12, top: 12,
right: right, 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) if (showPanels && showLeftColumn)
@@ -105,7 +107,8 @@ class CanvasOverlays extends StatelessWidget {
), ),
), ),
// 条形视图左下角:节拍统计 + 编辑工具。 // 条形视图左下角:节拍统计 + 编辑工具。
if (showPanels && !circular && (showStats || showTools)) // (流程图只读,不显示编辑工具。)
if (showPanels && !circular && !flow && (showStats || showTools))
Positioned( Positioned(
left: left, left: left,
bottom: 12, bottom: 12,
@@ -122,7 +125,8 @@ class CanvasOverlays extends StatelessWidget {
), ),
), ),
// 右下角预览:圆周视图显示条形缩略,反之亦然;点击可切换视图。 // 右下角预览:圆周视图显示条形缩略,反之亦然;点击可切换视图。
if (showPanels && showPreview) // 流程图是独立的载体,不显示时序视图的缩略预览。
if (showPanels && showPreview && !flow)
Positioned( Positioned(
right: right, right: right,
bottom: 12, bottom: 12,
@@ -174,30 +178,38 @@ class _Card extends StatelessWidget {
/// 顶部标题浮层:显示当前视图名称与双刻度/图例说明。 /// 顶部标题浮层:显示当前视图名称与双刻度/图例说明。
class _Title 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 Tokens t;
/// 是否处于圆周视图。 /// 当前视图模式。
final bool circular; final ViewMode mode;
/// 当前项目,用于展示循环时长等文案。 /// 当前项目,用于展示循环时长等文案。
final Project project; final Project project;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final String title = circular final String title = switch (mode) {
? '圆周时序视图' ViewMode.bar => '条形时序视图',
: '条形时序视图'; ViewMode.circular => '圆周时序视图',
final String sub = circular ViewMode.flow => '流程图视图',
? '同心圆环 = 动作层;箭头 = 执行顺序(绿色实线 FS 严格顺序,琥珀虚线 SS 并行重叠);1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%' };
: '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)'; 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( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[
Text(title, style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)), Text(title, style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)),
if (sub.isNotEmpty) ...<Widget>[
const SizedBox(height: 4), const SizedBox(height: 4),
Text(sub, style: TextStyle(color: t.dim, fontSize: 11)), Text(sub, style: TextStyle(color: t.dim, fontSize: 11)),
], ],
],
); );
} }
} }
+39 -6
View File
@@ -15,9 +15,11 @@ import 'package:flutter/material.dart' hide Action;
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import '../layout/layout.dart'; import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart'; import '../model/models.dart';
import '../render/bar_painter.dart'; import '../render/bar_painter.dart';
import '../render/circular_painter.dart'; import '../render/circular_painter.dart';
import '../render/flow_painter.dart';
import '../state/app_controller.dart'; import '../state/app_controller.dart';
import '../theme/tokens.dart'; import '../theme/tokens.dart';
import 'dialogs.dart'; import 'dialogs.dart';
@@ -150,6 +152,8 @@ class _CanvasViewState extends State<CanvasView> {
/// 之外;精确指针(手写笔)直接点在把手上时,仅靠动作命中测试会落空,因此这里 /// 之外;精确指针(手写笔)直接点在把手上时,仅靠动作命中测试会落空,因此这里
/// 单独做一次把手邻近命中,半径与 [_grabRadius] 一致。 /// 单独做一次把手邻近命中,半径与 [_grabRadius] 一致。
(Action, bool)? _hitHandle(Offset p, Size size) { (Action, bool)? _hitHandle(Offset p, Size size) {
// 流程图只读:无端点把手。
if (c.project.viewState.mode == ViewMode.flow) return null;
Action? best; Action? best;
bool bestStart = false; bool bestStart = false;
double bestDist = _grabRadius; double bestDist = _grabRadius;
@@ -316,14 +320,22 @@ class _CanvasViewState extends State<CanvasView> {
// ===================== 手势处理 ===================== // ===================== 手势处理 =====================
/// 单击:命中最上层动作则选中,否则清空选中。 /// 单击:命中最上层动作则选中,否则清空选中。
///
/// 流程图视图为只读:点击节点即选中对应动作(修改请回时序图)。
void _onTapDown(TapDownDetails d, Size size) { void _onTapDown(TapDownDetails d, Size size) {
final Offset p = _toLogical(d.localPosition, size); final Offset p = _toLogical(d.localPosition, size);
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); final (Action, bool)? handle = _hitHandle(p, size);
final Action? hit = handle?.$1 ?? hit = handle?.$1 ??
(c.project.viewState.mode == ViewMode.bar (mode == ViewMode.bar
? BarLayout(c.project, size).hitTest(p, slop: _hitSlop) ? BarLayout(c.project, size).hitTest(p, slop: _hitSlop)
: CircularLayout(c.project, size).hitTest(p, slop: _hitSlop)); : CircularLayout(c.project, size).hitTest(p, slop: _hitSlop));
}
// Ctrl(或 Shift)点击:切换该动作的选中状态,实现多选。 // Ctrl(或 Shift)点击:切换该动作的选中状态,实现多选。
final bool toggle = HardwareKeyboard.instance.isControlPressed || final bool toggle = HardwareKeyboard.instance.isControlPressed ||
HardwareKeyboard.instance.isShiftPressed; HardwareKeyboard.instance.isShiftPressed;
@@ -333,6 +345,8 @@ class _CanvasViewState extends State<CanvasView> {
/// 双击空白处:按点击位置换算出的相位角新建动作; /// 双击空白处:按点击位置换算出的相位角新建动作;
/// 若双击在已有动作上则不处理。 /// 若双击在已有动作上则不处理。
void _onDoubleTapDown(TapDownDetails d, Size size) { void _onDoubleTapDown(TapDownDetails d, Size size) {
// 流程图只读:双击不新建动作、也不编辑。
if (c.project.viewState.mode == ViewMode.flow) return;
final Offset p = _toLogical(d.localPosition, size); final Offset p = _toLogical(d.localPosition, size);
// 双击相位分区带:重命名该分区。 // 双击相位分区带:重命名该分区。
if (c.project.viewState.mode == ViewMode.bar) { if (c.project.viewState.mode == ViewMode.bar) {
@@ -369,6 +383,12 @@ class _CanvasViewState extends State<CanvasView> {
/// - 桌面:进入画布平移模式; /// - 桌面:进入画布平移模式;
/// - 触屏:不平移(单指只做选择 / 编辑,平移缩放交给双指)。 /// - 触屏:不平移(单指只做选择 / 编辑,平移缩放交给双指)。
void _onPanStart(Offset p, Size size) { 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) { if (c.project.viewState.mode == ViewMode.bar) {
final BarLayout layout = BarLayout(c.project, size); final BarLayout layout = BarLayout(c.project, size);
// 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。 // 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。
@@ -654,6 +674,11 @@ class _CanvasViewState extends State<CanvasView> {
/// 若右键落在相位分区带上,则弹出分区的增删改菜单。 /// 若右键落在相位分区带上,则弹出分区的增删改菜单。
Future<void> _contextMenu(Offset global, Size size) async { Future<void> _contextMenu(Offset global, Size size) async {
final Offset local = _toLogical(global, size); 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) { if (c.project.viewState.mode == ViewMode.bar) {
final int zi = _hitZoneAt(local, BarLayout(c.project, size)); final int zi = _hitZoneAt(local, BarLayout(c.project, size));
if (zi >= 0) { if (zi >= 0) {
@@ -791,8 +816,8 @@ class _CanvasViewState extends State<CanvasView> {
..setEntry(2, 2, c.project.viewState.zoom), ..setEntry(2, 2, c.project.viewState.zoom),
child: CustomPaint( child: CustomPaint(
size: size, size: size,
painter: c.project.viewState.mode == ViewMode.bar painter: switch (c.project.viewState.mode) {
? BarPainter( ViewMode.bar => BarPainter(
project: c.project, project: c.project,
tokens: t, tokens: t,
criticalActions: c.criticalActions, criticalActions: c.criticalActions,
@@ -801,8 +826,8 @@ class _CanvasViewState extends State<CanvasView> {
guideAngle: _zoneGuideAngle, guideAngle: _zoneGuideAngle,
dropLane: _dropLane, dropLane: _dropLane,
dropValid: _dropValid, dropValid: _dropValid,
) ),
: CircularPainter( ViewMode.circular => CircularPainter(
project: c.project, project: c.project,
tokens: t, tokens: t,
criticalActions: c.criticalActions, criticalActions: c.criticalActions,
@@ -810,6 +835,14 @@ class _CanvasViewState extends State<CanvasView> {
selectedIds: c.selectedIds.toSet(), selectedIds: c.selectedIds.toSet(),
guideAngle: _zoneGuideAngle, guideAngle: _zoneGuideAngle,
), ),
ViewMode.flow => FlowchartPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
),
},
), ),
), ),
), ),
+1 -1
View File
@@ -2124,7 +2124,7 @@ class HelpDialog extends StatelessWidget {
Text('时序图设计 · Sequence Diagram Studio', Text('时序图设计 · Sequence Diagram Studio',
style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)),
const SizedBox(height: 4), const SizedBox(height: 4),
Text('V1.2.2(${android ? '安卓版' : 'Windows 版'})', Text('V1.3.0(${android ? '安卓版' : 'Windows 版'})',
style: TextStyle(color: t.dim, fontSize: 12)), style: TextStyle(color: t.dim, fontSize: 12)),
], ],
), ),
+1 -1
View File
@@ -2,4 +2,4 @@
/// ///
/// 应用内更新检查用它判断服务器发布的版本是否更新; /// 应用内更新检查用它判断服务器发布的版本是否更新;
/// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。 /// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。
const String kAppVersion = '1.2.2'; const String kAppVersion = '1.3.0';
+1 -1
View File
@@ -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 # 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 # 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. # of the product and file versions while build-number is used as the build suffix.
version: 1.2.2+14 version: 1.3.0+16
environment: environment:
sdk: ^3.13.3 sdk: ^3.13.3
+5
View File
@@ -0,0 +1,5 @@
# V1.2.3 更新内容
- 修复「适应视图」在条形视图动作较多时的显示问题:画面被缩小后现在会**居中显示**,
不再偏移到左上角(此前固定 pan=0 导致缩小的内容钉在左上角)
- 圆周视图的适应视图行为保持不变(本来就是居中计算)
+19
View File
@@ -0,0 +1,19 @@
# V1.3.0 更新内容
## 全新:流程图视图(第三个视图模式)
- 由时序图**自动生成**:泳道 = 轨道;动作节点显示「序号. 名称 + 时长 · 工位」
- 依赖连线:绿色实线 FS 顺序 / 琥珀虚线 SS 并行(含偏移角标注)
- 关键路径加粗光晕;无前置依赖的动作自动从「开始」并列引出,形成并行分支
- 左侧相位阶段栏:相位分区按动作归属竖排显示(每个动作行归属覆盖占比最大的分区)
- 只读预览:点击节点可选中联动动作,修改请回条形 / 圆周视图
(流程图页的 AI 生成、撤销 / 重做、动作增删、属性编辑等入口会自动置灰)
## 导出升级
- 导出按钮合并为下拉菜单:**SVG / PNG 三种视图通用**
- 流程图额外支持导出 **drawio**:可在 diagrams.net(draw.io)中继续编辑,
泳道、相位分区、依赖关系都保留,方便二次加工
## 其他
- 首次启动的默认示例升级为完整「装配线节拍」(8 个动作 / 3 个工位 / 4 个相位分区)
- 左侧栏「视图模式」只保留条形 / 圆周节拍切换(流程图入口在顶部工具栏)
- 修复若干界面细节与截图工具问题
+73
View File
@@ -4,8 +4,10 @@ import 'dart:typed_data';
import 'dart:ui' as ui; import 'dart:ui' as ui;
import 'package:flutter_test/flutter_test.dart'; 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/export_renderer.dart';
import 'package:sequence_diagram/export/svg_writer.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/model/models.dart';
import 'package:sequence_diagram/theme/tokens.dart'; import 'package:sequence_diagram/theme/tokens.dart';
@@ -50,4 +52,75 @@ void main() {
expect(first & 0xFFFFFF, 0xFFFFFF); expect(first & 0xFFFFFF, 0xFFFFFF);
File('build/export_preview.png').writeAsBytesSync(bytes); 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('<g id="lanes">'));
expect(svg, contains('轨道 L1'));
expect(svg, contains('<g id="phases">'));
expect(svg, contains('上料相位'));
expect(svg, contains('rotate(-90)'));
expect(svg, contains('<g id="edges">'));
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°</text>'));
expect(svg, contains('<g id="actions">'));
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 <String>{'A1', 'A2', 'A3'},
criticalDeps: const <String>{'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('<mxfile'));
expect(xml, endsWith('</mxfile>'));
expect(xml, contains('<mxGraphModel'));
expect(xml, contains('<mxCell id="0"/>'));
expect(xml, contains('<mxCell id="1" parent="0"/>'));
expect(xml, contains('value="轨道 L1"'));
expect(xml, contains('value="上料相位"'));
expect(xml, contains('horizontal=0'));
// 动作节点:两行文本(&#10; 换行)+ 依赖以 source / target 引用。
expect(xml, contains('&#10;'));
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__')));
});
} }
+15 -34
View File
@@ -5,40 +5,9 @@ import 'package:flutter/services.dart';
import 'package:sequence_diagram/model/models.dart'; import 'package:sequence_diagram/model/models.dart';
/// 构造一个动作较多、含依赖与相位分区的演示工程。 /// 构造一个动作较多、含依赖与相位分区的演示工程。
Project demoTiming() { /// 演示工程:与内置默认工程完全一致(`Project.demo()`),
return Project( /// 保证「本地构建启动即所见」与演示截图的数据永远同步。
name: '装配线节拍', Project demoTiming() => Project.demo();
cycle: const Cycle(durationMs: 2400),
stations: const <Station>[
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: <Action>[
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>[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>[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>[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>[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>[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>[Dependency(fromId: 'A6', toId: 'A7', type: DepType.fs)]),
],
units: const UnitSettings(timeUnit: TimeUnit.s),
viewState: const ViewState(mode: ViewMode.bar),
phaseZones: const <PhaseZone>[
PhaseZone(name: '上料相位', startAngle: 0, endAngle: 70),
PhaseZone(name: '加工相位', startAngle: 70, endAngle: 200),
PhaseZone(name: '检测相位', startAngle: 200, endAngle: 300),
PhaseZone(name: '下料相位', startAngle: 300, endAngle: 360),
],
);
}
/// 从系统字体加载中文字体,使测试截图中的中文正常渲染。 /// 从系统字体加载中文字体,使测试截图中的中文正常渲染。
Future<void> loadZhFonts() async { Future<void> loadZhFonts() async {
@@ -57,3 +26,15 @@ Future<void> loadZhFonts() async {
return; return;
} }
} }
/// 从 Flutter SDK 加载 Material 图标字体,使测试截图中的图标正常渲染
/// (否则所有 Icon 会显示为空心方框)。
Future<void> 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<ByteData>.value(bytes));
await loader.load();
}
+3 -2
View File
@@ -52,8 +52,9 @@ void main() {
expect(decoded.actions.length, p.actions.length); expect(decoded.actions.length, p.actions.length);
expect(decoded.stations.length, p.stations.length); expect(decoded.stations.length, p.stations.length);
expect(decoded.phaseZones.length, p.phaseZones.length); expect(decoded.phaseZones.length, p.phaseZones.length);
expect(decoded.actions.last.deps.first.type, DepType.fs); final Action withDeps = decoded.actions.firstWhere((Action a) => a.deps.isNotEmpty);
expect(decoded.cycle.durationMs, 3600); expect(withDeps.deps.first.type, DepType.fs);
expect(decoded.cycle.durationMs, 2400);
expect(decoded.actions.last.color, p.actions.last.color); expect(decoded.actions.last.color, p.actions.last.color);
}); });
}); });
+6 -4
View File
@@ -6,7 +6,8 @@ void main() {
group('station management', () { group('station management', () {
test('setStations reassigns actions of a removed station', () { test('setStations reassigns actions of a removed station', () {
final AppController c = AppController(project: Project.demo()); 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; final String removed = c.project.stations[1].id;
expect(c.project.actions.any((Action a) => a.stationId == removed), isTrue); expect(c.project.actions.any((Action a) => a.stationId == removed), isTrue);
@@ -26,13 +27,14 @@ void main() {
test('setStations can add and rename stations', () { test('setStations can add and rename stations', () {
final AppController c = AppController(project: Project.demo()); final AppController c = AppController(project: Project.demo());
final int before = c.project.stations.length;
final List<Station> next = <Station>[ final List<Station> next = <Station>[
...c.project.stations, ...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); c.setStations(next);
expect(c.project.stations.length, 3); expect(c.project.stations.length, before + 1);
expect(c.project.stationById('ST3')?.name, '工位 3'); expect(c.project.stationById('ST9')?.name, '工位 9');
}); });
}); });
} }
+28 -3
View File
@@ -13,6 +13,7 @@ import 'helpers.dart';
void main() { void main() {
testWidgets('generate tablet demo screenshots', (WidgetTester tester) async { testWidgets('generate tablet demo screenshots', (WidgetTester tester) async {
await tester.runAsync(() => loadZhFonts()); await tester.runAsync(() => loadZhFonts());
await tester.runAsync(() => loadMaterialIcons());
tester.view.physicalSize = const Size(1280, 800); tester.view.physicalSize = const Size(1280, 800);
tester.view.devicePixelRatio = 1.0; tester.view.devicePixelRatio = 1.0;
@@ -25,6 +26,7 @@ void main() {
key: const ValueKey<String>('shot'), key: const ValueKey<String>('shot'),
child: MaterialApp( child: MaterialApp(
theme: buildTheme(t), theme: buildTheme(t),
debugShowCheckedModeBanner: false,
home: AppShell(controller: c), home: AppShell(controller: c),
), ),
); );
@@ -38,13 +40,15 @@ void main() {
await shot('../demo/tablet-bar-light.png'); 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(); await tester.pump();
if (tester.any(find.byIcon(Icons.push_pin_outlined))) { if (tester.any(find.byIcon(Icons.push_pin_outlined))) {
await tester.tap(find.byIcon(Icons.push_pin_outlined).first); await tester.tap(find.byIcon(Icons.push_pin_outlined).first);
await tester.pump(); await tester.pump();
} }
await tester.tap(find.byIcon(Icons.chevron_left).first); await tester.tapAt(const Offset(1270, 300));
await tester.pump(); await tester.pump();
if (tester.any(find.byIcon(Icons.push_pin_outlined))) { if (tester.any(find.byIcon(Icons.push_pin_outlined))) {
await tester.tap(find.byIcon(Icons.push_pin_outlined).first); await tester.tap(find.byIcon(Icons.push_pin_outlined).first);
@@ -56,12 +60,33 @@ void main() {
c.setViewMode(ViewMode.circular); c.setViewMode(ViewMode.circular);
await shot('../demo/tablet-circular-light.png'); 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(); c.toggleTheme();
await tester.pumpWidget(shell(Tokens.dark)); await tester.pumpWidget(shell(Tokens.dark));
await tester.pump(const Duration(milliseconds: 400));
c.setViewMode(ViewMode.bar); c.setViewMode(ViewMode.bar);
await shot('../demo/tablet-bar-dark.png'); await shot('../demo/tablet-bar-dark.png');
c.setViewMode(ViewMode.circular); c.setViewMode(ViewMode.circular);
await shot('../demo/tablet-circular-dark.png'); await shot('../demo/tablet-circular-dark.png');
c.setViewMode(ViewMode.flow);
await shot('../demo/tablet-flow-dark.png');
}); });
} }
+43 -1
View File
@@ -25,9 +25,10 @@ void main() {
await tester.pump(); await tester.pump();
expect(controller.project.viewState.mode, ViewMode.circular); expect(controller.project.viewState.mode, ViewMode.circular);
final int before = controller.project.actions.length;
controller.addAction(startAngle: 30); controller.addAction(startAngle: 30);
await tester.pump(); await tester.pump();
expect(controller.project.actions.length, 3); expect(controller.project.actions.length, before + 1);
controller.setViewMode(ViewMode.bar); controller.setViewMode(ViewMode.bar);
await tester.pump(); await tester.pump();
@@ -56,4 +57,45 @@ void main() {
await tester.pump(); await tester.pump();
expect(controller.brightness, Brightness.dark); 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<FilledButton>(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<FilledButton>(find.widgetWithText(FilledButton, 'AI 生成')).onPressed, isNull);
expect(
tester.widget<IconButton>(find.widgetWithIcon(IconButton, Icons.undo)).onPressed,
isNull,
);
expect(
tester.widget<IconButton>(find.widgetWithIcon(IconButton, Icons.redo)).onPressed,
isNull,
);
await tester.tap(find.text('导出'));
await tester.pumpAndSettle();
expect(find.text('导出 drawio'), findsOneWidget);
});
} }
+8 -4
View File
@@ -2,11 +2,15 @@
// //
// 用途:验证更新链路(网络可达 / 接口解析 / 版本判定 / 附件匹配)。 // 用途:验证更新链路(网络可达 / 接口解析 / 版本判定 / 附件匹配)。
// 运行: // 运行:
// dart run tool\check_update.dart // dart run tool\check_update.dart # 用当前版本检查
// dart run tool\check_update.dart 1.2.1 # 模拟旧版本,验证「发现更新」路径
// //
// 说明:使用的是与客户端完全相同的 lib/update/update_service.dart。 // 说明:使用的是与客户端完全相同的 lib/update/update_service.dart;
import '../lib/update/update_service.dart'; // 本文件是命令行工具,直接向控制台打印结果属预期用法。
import '../lib/version.dart'; //
// ignore_for_file: avoid_print
import 'package:sequence_diagram/update/update_service.dart';
import 'package:sequence_diagram/version.dart';
Future<void> main(List<String> args) async { Future<void> main(List<String> args) async {
// 可传入一个版本号模拟旧安装(如 `dart run tool\check_update.dart 1.2.1`)。 // 可传入一个版本号模拟旧安装(如 `dart run tool\check_update.dart 1.2.1`)。