v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复

- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json
- 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档
- 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸
- 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名
- 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
This commit is contained in:
2026-11-22 10:02:48 +08:00
parent afc4dc6dd7
commit 0a3f2c5cc6
105 changed files with 6309 additions and 3577 deletions
+565
View File
@@ -0,0 +1,565 @@
/// 依赖连线的共享走线计算。
///
/// 条形视图 / 圆周视图的**画布绘制、标签放置与命中测试**(点选连线、
/// 沿法线拖拽调整走线)都使用这里的同一份几何,避免绘制与命中不一致:
/// - 自动错开:同一走线分组内的多条依赖依次错开,先解决“完全重叠”;
/// - 手动偏移:[Dependency.routeOffset] 叠加在自动错开之上(拖拽连线的结果)。
library;
import 'dart:math' as math;
import 'dart:ui';
import 'package:sequence_diagram/model/models.dart';
import 'layout.dart';
// ===================== 通用工具 =====================
/// 点 [p] 到线段 [a]–[b] 的最短距离。
double distanceToSegment(Offset p, Offset a, Offset b) {
final Offset ab = b - a;
final double len2 = ab.dx * ab.dx + ab.dy * ab.dy;
if (len2 <= 0) return (p - a).distance;
final double t = (((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2).clamp(0.0, 1.0);
return (p - (a + ab * t)).distance;
}
/// 点 [p] 到折线 [pts] 的最短距离。
double distanceToPolyline(List<Offset> pts, Offset p) {
double best = double.infinity;
for (int i = 0; i + 1 < pts.length; i++) {
final double d = distanceToSegment(p, pts[i], pts[i + 1]);
if (d < best) best = d;
}
return best;
}
/// 点 [p] 到路径 [path] 的近似最短距离(按弧长采样,步长 [step])。
double distanceToPath(Path path, Offset p, {double step = 4}) {
double best = double.infinity;
for (final PathMetric m in path.computeMetrics()) {
for (double d = 0; d < m.length; d += step) {
final Tangent? t = m.getTangentForOffset(d);
if (t == null) continue;
final double dist = (t.position - p).distance;
if (dist < best) best = dist;
}
}
return best;
}
/// 第 [k] 档自动错开量(px):0、−6、+6、−12、+12 …
///
/// 同一走线分组内第二条起依次错开,避免多条依赖完全重叠。
double staggerOffset(int k) {
if (k <= 0) return 0;
return (k.isOdd ? -1 : 1) * ((k + 1) ~/ 2) * 6.0;
}
/// 拖拽调整走线时的移动轴(走线的“法线”方向)。
///
/// - [vertical]:上下拖动——平移水平走线段(条形 / 流程图的常见形态);
/// - [horizontal]:左右拖动——平移纵向走线走廊(跨行绕行走廊 / 同层绕行)。
enum RouteAxis { vertical, horizontal }
/// 拖拽走线时可用的最大手动偏移(px,双向)。
const double kMaxRouteOffset = 200;
// ===================== 条形视图 =====================
/// 条形视图的一条依赖走线。
class BarDepRoute {
/// 构造。
BarDepRoute(this.dep, this.points, this.arrowTip, this.arrowDir, this.chipCenter, this.axis,
{this.chipRun = double.infinity,
this.chipRunMargin = 0,
this.chipAltAnchor = Offset.zero,
this.junctionOnly = false});
/// 对应依赖。
final Dependency dep;
/// 折线顶点(含起点与箭头端点)。
final List<Offset> points;
/// 箭头端点。
final Offset arrowTip;
/// 箭头方向(分量式)。
final Offset arrowDir;
/// 标签中心(默认位置,避让前)。
final Offset chipCenter;
/// 拖拽方向:vertical = 上下拖动平移横线;horizontal = 左右拖动平移纵向走廊。
final RouteAxis axis;
/// 标签挂钩的水平行程长度(跑长时用于判断是否需要把标签移到箭头外侧)。
///
/// 默认 [double.infinity] 表示不做外移判断(跨行走廊等)。
final double chipRun;
/// 外移判断余量:行程 `< 标签宽 + 余量` 时把标签移到 [chipAltAnchor]。
final double chipRunMargin;
/// 外移时标签的锚点(绘制端会再加半个标签宽)。
final Offset chipAltAnchor;
/// 动作紧贴时只显示连接点标签,隐藏连线与箭头(由绘制层处理)。
final bool junctionOnly;
/// 依赖键 `from->to`。
String get key => '${dep.fromId}->${dep.toId}';
}
/// 条形依赖在动作条一端的锚点。
///
/// [point] 为线条端点(目标端为箭头尖端);[dir] 为箭头进入方向(源端为
/// 离开方向);[corner] 表示端点已退到条块的上/下角;[vSide] 为角点所在
/// 一侧(-1 上、+1 下)。
class _BarEnd {
const _BarEnd(this.point, this.dir, this.corner, this.vSide);
final Offset point;
final Offset dir;
final bool corner;
final int vSide;
}
/// 判断端点前的水平通道是否被其它动作条遮挡(宽 8px,条高中间 ±3px)。
///
/// 遮挡时把端点退到端部的上/下角,保证线条从角上引出而不是贴着邻条走。
bool _barEndBlocked(double edge, double outward, double centerY, Iterable<Rect> obstacles) {
const double clearance = 9;
final Rect probe = Rect.fromLTRB(
math.min(edge, edge + outward * clearance),
centerY - 3,
math.max(edge, edge + outward * clearance),
centerY + 3,
);
for (final Rect r in obstacles) {
if (r.overlaps(probe)) return true;
}
return false;
}
/// 源端锚点:默认取条块左/右端点中心;端部有遮挡时取朝向目标一侧的上下角。
_BarEnd _startEnd(Rect bar, int side, int cornerSide, Iterable<Rect> obstacles,
{bool forceCorner = false}) {
final double edge = side > 0 ? bar.right : bar.left;
final double outward = side > 0 ? 1 : -1;
final double cy = bar.center.dy;
if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) {
return _BarEnd(Offset(edge + outward * 2, cy), Offset(outward, 0), false, 0);
}
final int vs = cornerSide == 0 ? 1 : cornerSide;
final double y = vs > 0 ? bar.bottom - 2 : bar.top + 2;
return _BarEnd(Offset(edge + outward * 1.5, y), Offset(0, vs.toDouble()), true, vs);
}
/// 目标端锚点:默认取条块左/右端点中心(箭头停在端点外 2px);端部有遮挡
/// 时取朝向源条一侧的上下角,箭头从角外垂直指向条块。
_BarEnd _targetEnd(Rect bar, int side, int cornerSide, Iterable<Rect> obstacles,
{bool forceCorner = false}) {
final double edge = side > 0 ? bar.right : bar.left;
final double outward = side > 0 ? 1 : -1;
final double cy = bar.center.dy;
if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) {
return _BarEnd(Offset(edge + outward * 2, cy), Offset(-outward, 0), false, 0);
}
final int vs = cornerSide == 0 ? 1 : cornerSide;
final double y = vs > 0 ? bar.bottom + 2 : bar.top - 2;
return _BarEnd(
Offset(edge + outward * 1.5, y), Offset(0, -vs.toDouble()), true, vs);
}
/// 计算条形视图的全部依赖走线(含自动错开与手动偏移)。
///
/// 端点规则(FS / SS / FF / SF 均按语义取条块前端或后端):
/// 1. 默认从条块的左/右端点中心引出;FS/FF 从后端(右端)出发,
/// SS/SF 从前端(左端)出发;目标端按 FS/SS 取前端、FF/SF 取后端;
/// 2. 当端点临近被其它动作条遮挡(或同泳道走线会穿过条块)时,退到该端部
/// 的上/下角引出,再从角外绕行。
///
/// 走线分三种情形:同泳道(水平线或上下绕行)、相邻泳道(Z 形)、跨多行
/// (外侧纵向走廊);同组自动错开 + [Dependency.routeOffset] 手动偏移。
List<BarDepRoute> buildBarDepRoutes(Project project, BarLayout layout) {
final Map<String, Rect> rectById = <String, Rect>{
for (final Action a in project.actions) a.id: layout.rectFor(a),
};
final Map<String, int> laneIndex = <String, int>{
for (final Action a in project.actions) a.id: layout.laneIndexOf(a.layer),
};
final Map<String, int> seen = <String, int>{};
final List<BarDepRoute> out = <BarDepRoute>[];
for (final Action to in layout.ordered) {
for (final Dependency d in to.deps) {
final Action? from = project.actionById(d.fromId);
if (from == null) continue;
final Rect? ra = rectById[from.id];
final Rect? rb = rectById[to.id];
if (ra == null || rb == null) continue;
// 端点遮挡检查要包含“对方条块”:动作前后贴紧时,源端被目标条块
// 挡住、目标端被源条块挡住,此时应退到上下角并从条块外侧绕行。
final List<Rect> obstaclesForStart = <Rect>[
for (final MapEntry<String, Rect> e in rectById.entries)
if (e.key != from.id) e.value,
];
final List<Rect> obstaclesForEnd = <Rect>[
for (final MapEntry<String, Rect> e in rectById.entries)
if (e.key != to.id) e.value,
];
final int ia = laneIndex[from.id] ?? 0;
final int ib = laneIndex[to.id] ?? 0;
const double barHalf = BarLayout.barH / 2;
final double sy = ra.center.dy;
final double ty = rb.center.dy;
final int dirY = ty > sy ? 1 : (ty < sy ? -1 : 0);
final bool sameRow = dirY == 0;
final bool adjacentLane = (ib - ia).abs() <= 1;
// 端点语义:FS/FF 从后端出发,SS/SF 从前端出发;目标端 FS/SS 为前端,
// FF/SF 为后端。
final int fromSide =
(d.type == DepType.fs || d.type == DepType.ff) ? 1 : -1;
final int toSide =
(d.type == DepType.fs || d.type == DepType.ss) ? -1 : 1;
final String groupKey =
sameRow ? 'S$ia' : (adjacentLane ? 'A$ia→$ib' : 'M$ia→$ib');
final int k = seen.putIfAbsent(groupKey, () => 0);
seen[groupKey] = k + 1;
final double stagger = staggerOffset(k);
// 同泳道无上下方向时,按走线偏移/错开量决定绕上还是绕下。
final int cornerSide = dirY != 0
? dirY
: (stagger + d.routeOffset >= 0 ? 1 : -1);
if (sameRow) {
// 前后动作紧贴(首尾相接)时,连线/箭头会挤在接缝处且不可读:
// 隐藏走线,只在接缝处显示依赖标签。
final bool tight =
(rb.left - ra.right).abs() <= 4 || (ra.left - rb.right).abs() <= 4;
if (tight) {
final bool toRight = rb.center.dx >= ra.center.dx;
final double junctionX =
toRight ? (ra.right + rb.left) / 2 : (ra.left + rb.right) / 2;
out.add(BarDepRoute(
d,
const <Offset>[],
Offset.zero,
const Offset(1, 0),
Offset(junctionX, ra.top - 10),
RouteAxis.vertical,
junctionOnly: true,
));
continue;
}
// 同泳道:默认一条水平线;端点被遮挡或语义端点背向对方时,从
// 端部上/下角绕行(避免线穿过两个条块)。
final bool sourceFaces =
(rb.center.dx - ra.center.dx) * fromSide >= 0;
final bool targetFaces =
(ra.center.dx - rb.center.dx) * toSide >= 0;
_BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart);
_BarEnd t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd);
final bool straight = !s.corner && !t.corner && sourceFaces && targetFaces;
if (straight) {
final double y = sy + stagger + d.routeOffset;
final Offset sp = Offset(s.point.dx, y);
final Offset tp = Offset(t.point.dx, y);
out.add(BarDepRoute(
d,
<Offset>[sp, tp],
tp,
t.dir,
Offset((sp.dx + tp.dx) / 2, y - (barHalf + 9)),
RouteAxis.vertical,
chipRun: (tp.dx - sp.dx).abs(),
chipRunMargin: 8,
chipAltAnchor: Offset(tp.dx + 6, y - (barHalf + 9)),
));
} else {
// 只对背向对方 / 被遮挡的那一端退角,另一端仍从端点中心进出。
if (!sourceFaces || s.corner) {
s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart, forceCorner: true);
}
if (!targetFaces || t.corner) {
t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd, forceCorner: true);
}
final int side = s.corner
? s.vSide
: (t.corner ? t.vSide : cornerSide);
double runY = sy + side * (barHalf + 10) + stagger + d.routeOffset;
runY = side > 0
? math.max(runY, ra.bottom + 6)
: math.min(runY, ra.top - 6);
final double tx =
t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10;
final List<Offset> pts = <Offset>[s.point, Offset(s.point.dx, runY), Offset(tx, runY)];
if (t.corner) {
pts.add(t.point);
} else {
pts.add(Offset(tx, t.point.dy));
pts.add(t.point);
}
out.add(BarDepRoute(
d,
pts,
t.point,
t.dir,
// 绕行线在条块外侧,标签也放到线外侧,避免压住动作条。
Offset((ra.center.dx + rb.center.dx) / 2, runY + side * (barHalf + 9)),
RouteAxis.vertical,
chipRun: (tx - s.point.dx).abs(),
chipRunMargin: 8,
chipAltAnchor: Offset(
t.point.dx + 6,
t.corner ? t.point.dy + side * 10 : t.point.dy - 12,
),
));
}
continue;
}
final _BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart);
final _BarEnd t = _targetEnd(rb, toSide, -cornerSide, obstaclesForEnd);
if (adjacentLane) {
// 相邻泳道:端部引出后在两泳道之间的中线走水平段;同组错开 + 手动偏移。
final double mid = (sy + ty) / 2 + stagger + d.routeOffset;
final List<Offset> pts = <Offset>[s.point];
if (!s.corner) {
final double sx2 = s.point.dx + s.dir.dx * 10;
pts.add(Offset(sx2, s.point.dy));
pts.add(Offset(sx2, mid));
} else {
pts.add(Offset(s.point.dx, mid));
}
final double tx2 = t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10;
pts.add(Offset(tx2, mid));
if (t.corner) {
pts.add(t.point);
} else {
pts.add(Offset(tx2, t.point.dy));
pts.add(t.point);
}
out.add(BarDepRoute(
d,
pts,
t.point,
t.dir,
Offset((ra.center.dx + rb.center.dx) / 2, mid),
RouteAxis.vertical,
chipRun: (tx2 - s.point.dx).abs(),
chipRunMargin: 10,
chipAltAnchor: Offset(
t.point.dx + 6,
t.point.dy + (t.corner ? t.dir.dy * 10 : -12),
),
));
} else {
// 跨多行:扫描区间内所有条块边界,在外侧选一条纵向走廊;同组按
// ±12px 错开走廊,手动偏移作用于走廊横向位置。
final double sx = s.point.dx;
final double tx = t.point.dx;
double maxRight = 0;
double minLeft = double.infinity;
final List<int> lanes = layout.lanes;
for (int r = math.min(ia, ib) + 1; r < math.max(ia, ib); r++) {
if (r < 0 || r >= lanes.length) continue;
for (final Action aa in layout.actionsInLane(lanes[r])) {
final Rect rr = layout.rectFor(aa);
maxRight = math.max(maxRight, rr.right);
minLeft = math.min(minLeft, rr.left);
}
}
final double shift = stagger * 2 + d.routeOffset;
double lane = math.max(math.max(sx, tx), maxRight) + 28 + shift;
if (lane > layout.plotRight - 16) {
lane = math.min(math.min(sx, tx), minLeft) - 28 - shift;
}
final double srcGapY = sy + dirY * (barHalf + 14);
final double gapY = ty - dirY * (barHalf + 6);
final List<Offset> pts = <Offset>[s.point];
if (!s.corner) {
final double sx2 = s.point.dx + s.dir.dx * 10;
pts.add(Offset(sx2, s.point.dy));
pts.add(Offset(sx2, srcGapY));
} else {
pts.add(Offset(s.point.dx, srcGapY));
}
pts.add(Offset(lane, srcGapY));
pts.add(Offset(lane, gapY));
if (t.corner) {
pts.add(Offset(t.point.dx, gapY));
pts.add(t.point);
} else {
final double tx2 = t.point.dx - t.dir.dx * 10;
pts.add(Offset(tx2, gapY));
pts.add(Offset(tx2, t.point.dy));
pts.add(t.point);
}
out.add(BarDepRoute(
d,
pts,
t.point,
t.dir,
Offset((lane + tx) / 2, gapY - (barHalf + 1)),
RouteAxis.horizontal,
));
}
}
}
return out;
}
/// 命中条形依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。
BarDepRoute? hitBarDep(List<BarDepRoute> routes, Offset p, double maxDist) {
BarDepRoute? best;
double bestD = maxDist;
for (final BarDepRoute r in routes) {
final double d = distanceToPolyline(r.points, p);
if (d < bestD) {
bestD = d;
best = r;
}
}
return best;
}
// ===================== 圆周视图 =====================
/// 圆周视图的一条依赖走线(径向 → 圆弧 → 径向)。
class ArcDepRoute {
/// 构造。
ArcDepRoute(this.dep, this.center, this.rA, this.rB, this.rC, this.rTip, this.aEnd, this.aStart,
this.degenerate, this.cw, this.large, this.chipR, this.chipDeg,
{this.junctionOnly = false});
/// 对应依赖。
final Dependency dep;
/// 圆心。
final Offset center;
/// 源环半径。
final double rA;
/// 目标环半径。
final double rB;
/// 绕行半径(自动错开 + 手动偏移作用于此)。
final double rC;
/// 箭头落点半径。
final double rTip;
/// 源弧末端角(度)。
final double aEnd;
/// 目标弧起点角(度)。
final double aStart;
/// 起止角几乎重合(退化)时改画短箭头。
final bool degenerate;
/// 圆弧是否顺时针。
final bool cw;
/// 是否大弧。
final int large;
/// 标签极径。
final double chipR;
/// 标签极角。
final double chipDeg;
/// 动作紧贴时只显示连接点标签,隐藏圆弧与箭头。
final bool junctionOnly;
/// 依赖键 `from->to`。
String get key => '${dep.fromId}->${dep.toId}';
/// 起点(源环上)。
Offset get p0 => polar(center, rA, aEnd);
/// 绕行起点(半径 rC 上)。
Offset get p1 => polar(center, rC, aEnd);
/// 绕行终点(半径 rC 上)。
Offset get p2 => polar(center, rC, aStart);
/// 箭头端点。
Offset get p3 => polar(center, rTip, aStart);
/// 退化短箭头的起点。
Offset get q0 => polar(center, rTip - (rTip > rB ? 28 : -28), aStart);
/// 生成绘制路径(绘制与命中测试同源)。
Path buildPath() {
final Path p = Path();
if (degenerate) {
p.moveTo(q0.dx, q0.dy);
p.lineTo(p3.dx, p3.dy);
return p;
}
final Offset a0 = p0;
final Offset a1 = p1;
final Offset a2 = p2;
final Offset a3 = p3;
p.moveTo(a0.dx, a0.dy);
p.lineTo(a1.dx, a1.dy);
p.arcToPoint(a2, radius: Radius.circular(rC), largeArc: large == 1, clockwise: cw);
p.lineTo(a3.dx, a3.dy);
return p;
}
/// 箭头方向(分量式)。
Offset get tipDir => degenerate ? (p3 - q0) : (p3 - p2);
}
/// 计算圆周视图的全部依赖走线(含自动错开与手动偏移)。
List<ArcDepRoute> buildArcDepRoutes(Project project, CircularLayout layout) {
final Map<String, int> seen = <String, int>{};
final List<ArcDepRoute> out = <ArcDepRoute>[];
for (final Action to in project.actions) {
for (final Dependency d in to.deps) {
final Action? a = project.actionById(d.fromId);
final Action? b = project.actionById(d.toId);
if (a == null || b == null) continue;
final double rA = layout.radiusFor(a.layer, layout.slotOf(a));
final double rB = layout.radiusFor(b.layer, layout.slotOf(b));
final double aEnd = math.min(a.endAngle, 360);
final double aStart = b.startAngle;
// 层差大于 1 时从最外圈绕行,避免穿过中间层弧线。
final bool skip = (a.layer - b.layer).abs() > 1;
final String groupKey = '${skip ? 'K' : 'N'}${a.layer}→${b.layer}';
final int k = seen.putIfAbsent(groupKey, () => 0);
seen[groupKey] = k + 1;
// 同一环 / 相邻环的依赖如果画在环半径上会压住动作弧:把绕行半径
// 放到环间空隙(同一环时即为外侧空隙),标签也跟随到空隙里。
final double ringGap = math.max(layout.pitch - layout.th, 8);
final bool sameRing = (rA - rB).abs() < layout.pitch * 0.35;
final double baseC = skip
? layout.rMax + 24
: (sameRing ? rA + ringGap * 0.55 : (rA + rB) / 2);
// 自动错开(步长 9px)+ 手动径向偏移(圆周视图的“法线”即半径方向)。
double rC = baseC + staggerOffset(k) * 1.5 + d.routeOffset;
rC = rC.clamp(18.0, layout.rMax + 170);
final double rTip = rC < rB ? rB - layout.th / 2 - 4 : rB + layout.th / 2 + 4;
final bool cw = aStart >= aEnd;
final int large = (aStart - aEnd).abs() > 180 ? 1 : 0;
final bool degenerate = (aStart - aEnd).abs() < 0.5;
final bool junctionOnly = (aStart - aEnd).abs() <= 2.0;
final double chipDeg = degenerate ? aStart : (aEnd + aStart) / 2;
final double chipR = rC;
out.add(ArcDepRoute(
d,
layout.center,
rA,
rB,
rC,
rTip,
aEnd,
aStart,
degenerate,
cw,
large,
chipR,
chipDeg,
junctionOnly: junctionOnly));
}
}
return out;
}
/// 命中圆周依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。
ArcDepRoute? hitArcDep(List<ArcDepRoute> routes, Offset p, double maxDist) {
ArcDepRoute? best;
double bestD = maxDist;
for (final ArcDepRoute r in routes) {
final double d = distanceToPath(r.buildPath(), p);
if (d < bestD) {
bestD = d;
best = r;
}
}
return best;
}
@@ -0,0 +1,603 @@
/// 流程图布局:把时序图中的动作与依赖转换为纵向流程图(泳道 = 轨道)。
///
/// 产品规则(1.3 大版本,经需求确认):
/// - 每个动作 = 一个工序节点,节点内显示「序号. 名称」与时长(含工位);
/// - 泳道 = 动作的轨道(layer),横向并列,一眼看出哪些步骤在并行;
/// - 依赖:FS 实线、SS 虚线(带偏移角标注);关键路径加粗高亮;
/// - 自动补「开始 / 结束」节点:开始 → 时间最早的动作(动作1),
/// 其余无前置的动作作为并行起点同样从开始引出;无后继的动作 → 结束;
/// - 只读视图:交互仅支持点选联动与平移缩放,内容修改请回时序图。
library;
import 'dart:math' as math;
import 'dart:ui';
import 'package:sequence_diagram/model/models.dart';
import 'package:sequence_diagram/model/units.dart';
import 'dep_routes.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, this.axis);
/// 对应的连线。
final FlowEdge edge;
/// 折线顶点序列(含起点与箭头端点)。
final List<Offset> points;
/// 箭头端点。
final Offset tip;
/// 箭头方向(分量式单位方向)。
final Offset dir;
/// FS / SS 标签位置。
final Offset labelAt;
/// 拖拽调整走线的方向:向下流为竖直(上下拖动),同层绕行为水平(左右拖动)。
final RouteAxis axis;
/// 依赖键 `from->to`。
String get key => '${edge.fromId}->${edge.toId}';
/// 是否虚线(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;
/// 泳道内两个槽位之间的横向间距(留出依赖连线的走线空间)。
static const double slotGap = 26;
/// 各泳道左边缘 x(放置完成后按内容自适应填充)。
final List<double> laneStarts = <double>[];
/// 各泳道宽度(基础 = 槽位数,放置后按内容自动加宽)。
final List<double> laneWidths = <double>[];
/// 第 [li] 条泳道的宽度(优先取内容自适应结果;未计算时按槽位数)。
double laneWidth(int li) {
if (li >= 0 && li < laneWidths.length) return laneWidths[li];
if (li < 0 || li >= lanes.length) return nodeW;
final int s = project.slotsOf(lanes[li]);
return s * nodeW + (s - 1) * slotGap;
}
/// 第 [li] 条泳道左边缘 x(优先取内容自适应结果,其次按槽位宽度累加)。
double laneStartX(int li) {
if (li >= 0 && li < laneStarts.length) return laneStarts[li];
double x = marginX;
for (int i = 0; i < li && i < lanes.length; i++) {
x += laneWidth(i) + laneGap;
}
return x;
}
/// 第 [li] 条泳道第 [slot] 列的节点中心 x(槽位钳制到有效范围)。
double slotCenterX(int li, int slot) {
final int s = (li >= 0 && li < lanes.length) ? project.slotsOf(lanes[li]) : 1;
final int k = slot < 0 ? 0 : (slot >= s ? s - 1 : slot);
return laneStartX(li) + k * (nodeW + slotGap) + nodeW / 2;
}
/// 按 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 = project.renderLanes;
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>{};
// 泳道基础几何:宽度按槽位数,左边缘按前一泳道宽度累加。
laneStarts.clear();
laneWidths.clear();
{
double x = marginX;
for (int i = 0; i < lanes.length; i++) {
final int s = project.slotsOf(lanes[i]);
laneStarts.add(x);
laneWidths.add(s * nodeW + (s - 1) * slotGap);
x += laneWidths.last + 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;
if (n.isStart || n.isEnd) {
centerX = laneStartX(li) + laneWidth(li) / 2;
} else {
final int slot = effectiveSlot(project, n.action!);
centerX = slotCenterX(li, slot) + (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);
}
// 同层智能排开:同一 rank 行内若有水平重叠(同格多节点 / 跨列挤出),
// 从左到右依次推开,保证节点之间至少留 10px,避免“堆叠到一起看不清”。
final Map<int, List<FlowNode>> byRank = <int, List<FlowNode>>{};
for (final FlowNode n in nodes) {
byRank.putIfAbsent(n.rank, () => <FlowNode>[]).add(n);
}
for (final List<FlowNode> row in byRank.values) {
row.sort((FlowNode a, FlowNode b) => a.rect.left.compareTo(b.rect.left));
for (int i = 1; i < row.length; i++) {
final FlowNode prev = row[i - 1];
final FlowNode cur = row[i];
final double minLeft = prev.rect.right + 10;
if (cur.rect.left < minLeft) {
cur.rect = cur.rect.shift(Offset(minLeft - cur.rect.left, 0));
}
}
}
// 泳道带按内容**智能加宽**:若某泳道的节点被推到基础宽度之外,
// 先按内容算出需要的加宽量,再把该泳道及其后所有泳道整体右移,
// 保证底部泳道带完整覆盖自己的动作节点(与条形 / 圆周视图的观感一致)。
final List<double> extra = List<double>.filled(lanes.length, 0);
for (int i = 0; i < lanes.length; i++) {
double contentRight = double.negativeInfinity;
for (final FlowNode n in nodes) {
if ((laneIndex[n.lane] ?? 0) == i) {
contentRight = math.max(contentRight, n.rect.right);
}
}
if (contentRight.isFinite) {
final double need = contentRight + 26 - (laneStarts[i] + laneWidths[i]);
if (need > 0) extra[i] = need;
}
}
if (extra.any((double e) => e > 0)) {
double delta = 0;
for (int i = 0; i < lanes.length; i++) {
if (delta != 0) {
for (final FlowNode n in nodes) {
if ((laneIndex[n.lane] ?? 0) == i) {
n.rect = n.rect.shift(Offset(delta, 0));
}
}
laneStarts[i] += delta;
}
laneWidths[i] += extra[i];
// 泳道加宽后,开始 / 结束胶囊重新居中于泳道带。
if (extra[i] > 0) {
for (final FlowNode n in nodes) {
if ((n.isStart || n.isEnd) && (laneIndex[n.lane] ?? 0) == i) {
final double cx = laneStarts[i] + laneWidths[i] / 2;
n.rect = Rect.fromLTWH(
cx - n.rect.width / 2, n.rect.top, n.rect.width, n.rect.height);
}
}
}
delta += extra[i];
}
}
// 6) 连线走线:画布绘制 / SVG / drawio 导出共用(同源同层分支扇形错位)。
// 依赖上保存的手动走线偏移(routeOffset)在此叠加:
// 向下流为竖直偏移(拖动横线),同层绕行为水平偏移(拖动纵向走廊)。
// 同源同层的多条分支预先分组,横线在可用空隙内**均匀铺开**,
// 分支多时不再全部挤在同一条线上(流程图“智能排开”)。
final Map<String, List<FlowEdge>> fanGroups = <String, List<FlowEdge>>{};
for (final FlowEdge e in edges) {
final FlowNode? a = byId[e.fromId];
final FlowNode? b = byId[e.toId];
if (a == null || b == null || b.rank <= a.rank) continue;
fanGroups.putIfAbsent('${e.fromId}:${b.rank}', () => <FlowEdge>[]).add(e);
}
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;
double routeOffset = 0;
if (e.type != null) {
final Action? to = project.actionById(e.toId);
for (final Dependency d in to?.deps ?? const <Dependency>[]) {
if (d.fromId == e.fromId) {
routeOffset = d.routeOffset;
break;
}
}
}
if (b.rank > a.rank) {
final String key = '${e.fromId}:${b.rank}';
final List<FlowEdge> group = fanGroups[key] ?? <FlowEdge>[e];
final int idx = fanIndex[key] ?? 0;
fanIndex[key] = idx + 1;
// 横线高度:单条分支沿用“空隙中线”;多条分支在
// [源底 + 10, 目标顶 - 8] 内均匀铺开(第 idx+1 / n+1 份),再叠加手动偏移。
final double gapLow = a.rect.bottom + 10;
double gapHigh = double.infinity;
for (final FlowEdge ge in group) {
final FlowNode? gb = byId[ge.toId];
if (gb != null && gb.rect.top - 8 < gapHigh) gapHigh = gb.rect.top - 8;
}
double lane;
if (group.length <= 1) {
lane = math.min((a.rect.bottom + b.rect.top) / 2 + routeOffset, b.rect.top - 8);
} else {
final double span = math.max(gapHigh - gapLow, 8);
lane = gapLow + span * (idx + 1) / (group.length + 1) + routeOffset;
}
if (lane < gapLow) lane = gapLow;
if (lane > gapHigh) lane = gapHigh;
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),
RouteAxis.vertical,
));
} else {
// 同层 / 回连:右侧绕行;手动偏移作用于绕行走廊的横向位置。
final double x = math.max(a.rect.right, b.rect.right) + 22 + routeOffset;
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),
RouteAxis.horizontal,
));
}
}
// 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;
}
+442
View File
@@ -0,0 +1,442 @@
/// 几何布局层:把领域模型 [Project] 映射为屏幕坐标,供绘制与命中测试使用。
///
/// 本层不持有任何可变状态、不修改模型,属于纯计算:
/// - 顶层的极坐标/角度/圆弧工具函数服务于圆周视图;
/// - [BarLayout] 负责条形(甘特)视图的行与列定位;
/// - [CircularLayout] 负责圆周视图的同心环定位与命中测试。
/// 视图层根据这些坐标进行绘制与交互命中判断。
library;
import 'dart:math' as math;
import 'dart:ui';
import 'package:sequence_diagram/model/models.dart';
/// 极坐标转直角坐标:以 [c] 为圆心、[r] 为半径、[deg] 为角度(0° 指向正上方)。
Offset polar(Offset c, double r, double deg) {
final double t = (deg - 90) * math.pi / 180;
return Offset(c.dx + r * math.cos(t), c.dy + r * math.sin(t));
}
/// 已知圆心 [c] 与点 [p],求该点相对圆心的角度(度,0° 为正上方,范围 [0,360))。
double angleOf(Offset c, Offset p) {
final double a = math.atan2(p.dy - c.dy, p.dx - c.dx) * 180 / math.pi + 90;
return a < 0 ? a + 360 : a;
}
/// 构造从角度 [a0] 到 [a1] 的圆弧路径。
///
/// 参数 [c]:圆心;[r]:半径;[a0]/[a1]:起止角(度)。
/// 返回:以起点 moveTo、经 arcToPoint 连接终点的 [Path];根据扫过角度决定
/// 是否使用 largeArc,并根据扫角正负决定顺时针方向。
Path arcPath(Offset c, double r, double a0, double a1) {
final Path p = Path();
final Offset s = polar(c, r, a0);
final Offset e = polar(c, r, a1);
p.moveTo(s.dx, s.dy);
final double sweep = a1 - a0;
final int large = sweep.abs() > 180 ? 1 : 0;
p.arcToPoint(
e,
radius: Radius.circular(r),
largeArc: large == 1,
clockwise: sweep >= 0,
);
return p;
}
/// 将跨越 360° 的区间拆分为两段,便于分别绘制。
///
/// 若 [a1] <= 360 直接返回 `[[a0, a1]]`;否则返回 `[[a0, 360], [0, a1-360]]`。
List<List<double>> splitArcs(double a0, double a1) {
if (a1 <= 360) return <List<double>>[<double>[a0, a1]];
return <List<double>>[
<double>[a0, 360],
<double>[0, a1 - 360],
];
}
/// 计算动作在条形视图中的行顺序。
///
/// **泳道模型**:`Action.layer` 同时作为「泳道 / 圆周轨道」编号,
/// 对应一个物理执行器;同一泳道可容纳**多个互不重叠**的动作。
/// 排序规则:先按泳道号,再按起始角,最后按 id。
List<Action> orderActions(Project project) {
final List<Action> list = List<Action>.of(project.actions);
list.sort((Action a, Action b) {
if (a.layer != b.layer) return a.layer.compareTo(b.layer);
final int c = a.startAngle.compareTo(b.startAngle);
if (c != 0) return c;
return a.id.compareTo(b.id);
});
return list;
}
/// 判断两条角度区间是否重叠(用于同一泳道内“动作不可重叠”的约束)。
///
/// 参数均为角度区间 `[start, end]`;跨圈(end > 360)按模 360 归一后判断。
bool angleRangesOverlap(double s1, double e1, double s2, double e2) {
// 归一到 [0,360),并把跨圈区间拆成两段后逐一比较。
List<List<double>> seg(double s, double e) {
double a = s % 360;
if (a < 0) a += 360;
double b = e % 360;
if (b < 0) b += 360;
if (e - s >= 360) return <List<double>>[<double>[0, 360]];
if (b >= a) return <List<double>>[<double>[a, b]];
return <List<double>>[<double>[a, 360], <double>[0, b]];
}
for (final List<double> x in seg(s1, e1)) {
for (final List<double> y in seg(s2, e2)) {
if (x[0] < y[1] - 0.001 && y[0] < x[1] - 0.001) return true;
}
}
return false;
}
/// 动作 [a] 在 [project] 中其泳道内的有效槽位(与泳道槽位数钳制一致)。
///
/// 1 槽泳道恒为 0;旧数据中的历史行序(超出范围 / -1)会被钳制到有效槽位。
int effectiveSlot(Project project, Action a) {
final int slots = project.slotsOf(a.layer);
if (slots <= 1) return 0;
final int r = a.row;
return r < 0 ? 0 : (r >= slots ? slots - 1 : r);
}
/// 条形(甘特)视图布局。
///
/// 横轴为相位角(0°–360°),纵轴为动作行。行顺序由 [ordered] 决定,
/// 行高 [pitch] 会根据可用高度自适应(限制在 46–66 之间)。
class BarLayout {
/// 构造条形布局并计算行高。
///
/// 参数 [project]:项目数据;[size]:可用画布尺寸。
/// 副作用:初始化 [pitch]。
BarLayout(this.project, this.size) {
// 可用高度 = 总高 - 顶部留白 - 底部预留;按**总子行数**(各泳道槽位数之和)
// 均分并夹取到 [44, 58];单槽泳道时与旧版行为完全一致。
// 多槽位工程采用「组内紧凑 + 泳道间拉开」:子行更紧、泳道之间额外留白,
// 一眼能看出哪些子行属于同一条泳道。
final int n = subRowCount;
final int laneN = lanes.length;
final double extraTotal = _grouped && laneN > 1 ? (laneN - 1) * laneExtraGap : 0;
final double usable = size.height - topPad - bottomReserve;
pitch = n == 0 ? 58 : ((usable - extraTotal) / n).clamp(_grouped ? 36 : 44, 58);
}
/// 是否启用「组内紧凑 + 泳道间拉开」的间隔分组(仅多槽位工程)。
bool get _grouped => project.hasMultiSlotLanes;
/// 泳道之间的额外纵向留白(仅多槽位分组时生效,像素)。
static const double laneExtraGap = 16;
/// 布局所依据的项目数据。
final Project project;
/// 可用画布尺寸。
final Size size;
/// 左侧标签栏宽度(像素):紧贴图表,避免动作名离图太远。
static const double leftGutter = 210;
/// 顶部留白(为标题/刻度等预留)。
static const double topPad = 210;
/// 单个动作条的高度(像素):单行文字即可,条块更苗条(留出更多泳道间隙放依赖标签)。
static const double barH = 18;
/// 行的视觉参考高度(像素)。
static const double rowVisual = 36;
/// 底部预留空间(像素)。
static const double bottomReserve = 350;
/// 相邻动作行之间的垂直距离(像素)。
late final double pitch;
/// 绘图区左边界。
double get plotLeft => leftGutter;
/// 绘图区右边界(右侧留 56px)。
double get plotRight => size.width - 56;
/// 绘图区横向跨度(像素)。
double get span => plotRight - plotLeft;
/// 决定行先后的动作列表;见顶层函数 [orderActions]。
List<Action> get ordered => orderActions(project);
/// 泳道编号(= 物理执行器轨道):来自 [Project.renderLanes]。
///
/// 开启「保留空泳道」时包含动作已全部移走的空泳道(序号不变)。
List<int> get lanes => project.renderLanes;
/// 泳道号在 [lanes] 中的序号。
int laneIndexOf(int lane) => lanes.indexOf(lane);
/// 泳道内包含的动作(按起始角排序)。
List<Action> actionsInLane(int lane) =>
ordered.where((Action a) => a.layer == lane).toList();
/// 泳道 [lane] 的槽位数(1–5)。
int slotsOf(int lane) => project.slotsOf(lane);
/// 动作 [a] 的实际槽位(钳制到所属泳道的有效范围;1 槽泳道恒为 0)。
int slotOf(Action a) => effectiveSlot(project, a);
/// 全部泳道的子行总数(Σ 槽位)。
int get subRowCount {
int n = 0;
for (final int lane in lanes) {
n += slotsOf(lane);
}
return n;
}
/// 泳道 [lane] 之前(不含)的纵向高度(子行 + 分组留白)。
double _laneOffsetBefore(int lane) {
double h = 0;
for (final int l in lanes) {
if (l == lane) break;
h += slotsOf(l) * pitch + (_grouped ? laneExtraGap : 0);
}
return h;
}
/// 泳道号转纵坐标(该泳道顶部 y)。
double yForLane(int lane) => topPad + _laneOffsetBefore(lane);
/// 泳道内槽位转纵坐标(该槽位所在子行的顶部 y)。
double yForSlot(int lane, int slot) => yForLane(lane) + slot * pitch;
/// 内容底部 y(最后一个子行之后)。
double get plotBottom {
double h = subRowCount * pitch;
if (_grouped && lanes.length > 1) h += (lanes.length - 1) * laneExtraGap;
return topPad + h;
}
/// 由纵坐标反查最近的泳道号(用于拖拽换道)。
int laneAt(double y) => laneSlotAt(y).$1;
/// 由纵坐标反查(泳道号, 槽位)——拖拽换道 / 换槽位时使用。
(int, int) laneSlotAt(double y) {
if (lanes.isEmpty) return (0, 0);
double top = topPad;
for (int li = 0; li < lanes.length; li++) {
final int lane = lanes[li];
final int s = slotsOf(lane);
final double h = s * pitch;
// 泳道之间的额外留白按半份归属本道,保证指针落在空隙中也能命中相邻泳道。
final double boundary =
top + h + (_grouped && li < lanes.length - 1 ? laneExtraGap * 0.5 : 0);
if (y < boundary || li == lanes.length - 1) {
final int slot = ((y - top) / pitch).round().clamp(0, s - 1);
return (lane, slot);
}
top += h + (_grouped ? laneExtraGap : 0);
}
return (lanes.last, slotsOf(lanes.last) - 1);
}
/// 相位角(度)转横坐标;角度先钳制到 `[0, 360]`。
double xFor(double deg) => plotLeft + (deg.clamp(0, 360) / 360) * span;
/// 计算动作 [a] 的条形矩形(按所属泳道的 y)。
///
/// 宽度至少为 3px,避免极短动作不可见;跨圈部分会被截断到 360°。
Rect rectFor(Action a) {
final double y = yForSlot(a.layer, slotOf(a));
final double x0 = xFor(a.startAngle);
final double x1 = xFor(math.min(a.endAngle, 360));
return Rect.fromLTWH(x0, y, math.max(x1 - x0, 3), barH);
}
/// 命中测试:返回坐标 [p] 处最上层的动作,未命中返回 null。
///
/// 从后往前遍历(后绘制的在上层),并按 [slop] 向外膨胀矩形提升可点性
/// (触屏平台可传入更大的容差)。
Action? hitTest(Offset p, {double slop = 4}) {
for (int i = ordered.length - 1; i >= 0; i--) {
final Action a = ordered[i];
final Rect r = rectFor(a).inflate(slop);
if (r.contains(p)) return a;
}
return null;
}
/// 横坐标反算相位角(度),结果钳制在 `[0, 360]`。
double angleAt(double x) => ((x - plotLeft) / span * 360).clamp(0, 360);
}
/// 圆周(环形)视图布局。
///
/// 每个动作的层 [Action.layer] 决定其所在同心环的半径,角度区间决定环上的弧段。
class CircularLayout {
/// 构造圆周布局并计算圆心、环间距与环宽。
///
/// 参数 [project]:项目数据;[size]:可用画布尺寸。
/// 副作用:初始化 [center]、[pitch]、[ringWidth]。
CircularLayout(this.project, this.size) {
// 圆心略微下移 18px 以平衡顶部刻度标签的视觉重心。
center = Offset(size.width / 2, size.height / 2 + 18);
// 子环总数 = Σ 各轨道槽位数(泳道加宽后同一轨道可有多条并行子环);
// 单槽时与旧版(按轨道数)完全一致。
final int rings = subRingCount;
final int laneN = lanes.length;
// 多槽位工程采用「组内紧凑 + 轨道间拉开」:同一轨道的子环更紧、
// 轨道之间额外留白,一眼能看出哪些子环属于同一轨道。
final double extraTotal = _grouped && laneN > 1 ? (laneN - 1) * ringExtraGap : 0;
// 最大半径受较短边约束,减去 74px 留给刻度与边距。
final double maxR = math.min(size.width, size.height) / 2 - 74;
// 在 r0 与 maxR 之间均分各子环,环间距夹取(多槽位时允许更紧)。
pitch = rings <= 1
? 46
: ((maxR - r0 - extraTotal) / (rings - 1)).clamp(_grouped ? 24 : 32, 56);
// 动作环带宽度:只求容纳文字;多槽位分组时子环更窄,轨道间靠留白区分。
ringWidth = (pitch * 0.42).clamp(_grouped ? 10 : 14, 17);
}
/// 是否启用「组内紧凑 + 轨道间拉开」的间隔分组(仅多槽位工程)。
bool get _grouped => project.hasMultiSlotLanes;
/// 轨道之间的额外径向留白(仅多槽位分组时生效,像素)。
static const double ringExtraGap = 18;
/// 布局所依据的项目数据。
final Project project;
/// 可用画布尺寸。
final Size size;
/// 最内层(第 0 层)半径(像素)。
static const double r0 = 58;
/// 圆心坐标。
late final Offset center;
/// 相邻层之间的半径差(像素)。
late final double pitch;
/// 环的视觉宽度(像素)。
late final double ringWidth;
/// 轨道编号(= 泳道):来自 [Project.renderLanes](含保留的空轨道)。
List<int> get lanes => project.renderLanes;
/// 轨道号在 [lanes] 中的序号。
int laneIndexOf(int lane) => lanes.indexOf(lane);
/// 轨道 [lane] 的槽位数(1–5)。
int slotsOf(int lane) => project.slotsOf(lane);
/// 动作 [a] 的实际槽位(钳制;1 槽轨道恒为 0)。
int slotOf(Action a) => effectiveSlot(project, a);
/// 全部轨道的子环总数(Σ 槽位)。
int get subRingCount {
int n = 0;
for (final int lane in lanes) {
n += slotsOf(lane);
}
return n;
}
/// 轨道 [lane] 之前(不含)的子环数。
int subRingIndexOfLane(int lane) {
int n = 0;
for (final int l in lanes) {
if (l == lane) break;
n += slotsOf(l);
}
return n;
}
/// 由半径反查最近的轨道号(用于拖拽换轨)。
int laneAtRadius(double r) => laneSlotAtRadius(r).$1;
/// 由半径反查(轨道号, 槽位)——拖拽换轨 / 换子环时使用。
(int, int) laneSlotAtRadius(double r) {
if (lanes.isEmpty) return (0, 0);
double base = r0;
for (int li = 0; li < lanes.length; li++) {
final int lane = lanes[li];
final int s = slotsOf(lane);
final double h = s * pitch;
// 轨道之间的额外留白按半份归属本道,落在空隙中也能命中相邻轨道。
final double boundary =
base + h + (_grouped && li < lanes.length - 1 ? ringExtraGap * 0.5 : 0);
if (r < boundary || li == lanes.length - 1) {
final int slot = ((r - base) / pitch).round().clamp(0, s - 1);
return (lane, slot);
}
base += h + (_grouped ? ringExtraGap : 0);
}
return (lanes.last, slotsOf(lanes.last) - 1);
}
/// 轨道 [lane] 第 [slot] 条子环的半径(未知轨道回退到最内圈)。
double radiusFor(int lane, [int slot = 0]) {
final int i = laneIndexOf(lane);
if (i < 0) return r0;
final int s = slotsOf(lane);
final int k = slot < 0 ? 0 : (slot >= s ? s - 1 : slot);
return r0 +
(subRingIndexOfLane(lane) + k) * pitch +
(_grouped ? i * ringExtraGap : 0);
}
/// 最外层半径。
double get rMax {
if (lanes.isEmpty) return r0;
final double extra = _grouped && lanes.length > 1 ? (lanes.length - 1) * ringExtraGap : 0;
return r0 + (subRingCount - 1) * pitch + extra;
}
/// 刻度标签所在的半径(最外层再向外偏移)。
/// 刻度环半径:在外层动作环之外留出足够间距,
/// 供相位分区带独立占位(不与动作环挤在一起)。
double get tickR => rMax + ringWidth / 2 + 38;
/// 环宽别名,供绘制代码使用。
double get th => ringWidth;
/// 命中测试:返回坐标 [p] 命中的动作,未命中返回 null。
///
/// 算法:计算点相对圆心的距离 [d] 与角度 [a];遍历所有动作,先按径向
/// 距离过滤(与所在环的偏差不超过半个环宽 + [slop]),再判断角度是否落在
/// 该动作弧段内;在候选中取径向偏差最小者(触屏平台可传入更大的容差)。
Action? hitTest(Offset p, {double slop = 3}) {
final double d = (p - center).distance;
final double a = angleOf(center, p);
Action? best;
double bestDelta = double.infinity;
for (final Action a2 in project.actions) {
final double r = radiusFor(a2.layer, slotOf(a2));
if ((d - r).abs() > ringWidth / 2 + slop) continue;
if (_inArc(a2, a)) {
final double delta = (d - r).abs();
if (delta < bestDelta) {
bestDelta = delta;
best = a2;
}
}
}
return best;
}
/// 判断角度 [deg] 是否落在动作 [a] 的弧段内(含 0.5° 容差)。
///
/// 当动作不跨圈(endAngle <= 360)时为普通区间判断;跨圈时区间回绕,
/// 条件变为 `n >= start-0.5 或 n <= (end-360)+0.5`。
bool _inArc(Action a, double deg) {
final double e = a.endAngle;
final double n = deg % 360;
if (e <= 360) {
return n >= a.startAngle - 0.5 && n <= e + 0.5;
}
return n >= a.startAngle - 0.5 || n <= (e - 360) + 0.5;
}
}
+61
View File
@@ -0,0 +1,61 @@
/// 动作条拖拽吸附:把整体拖动的水平位移吸附到最近的动作条端点、整 5°、
/// 0/360 或相位分区边界。
///
/// 架构位置:布局层纯函数,不依赖 UI 状态;`CanvasView` 在整体拖动时调用,
/// 单元测试可直接验证吸附结果。
library;
import 'package:sequence_diagram/model/models.dart';
/// 计算整体拖动后的动作起始角。
///
/// - [project]:当前工程;
/// - [excludeId]:正在拖动的动作 id(不参与吸附,避免自吸附);
/// - [rawStart]:未吸附的起始角;
/// - [duration]:动作持续角(整体拖动不改变长度);
/// - [toleranceDeg]:吸附容差(度)。
///
/// 返回 `(吸附后的起始角, 参考角度)`;参考角度用于绘制竖向虚线,
/// 未吸附时为 null。
(double, double?) snapActionStart({
required Project project,
required String excludeId,
required double rawStart,
required double duration,
required double toleranceDeg,
}) {
final double tol = toleranceDeg <= 0 ? 0 : toleranceDeg;
final List<double> candidates = <double>[0, 360];
for (int d = 0; d <= 360; d += 5) {
candidates.add(d.toDouble());
}
for (final Action a in project.actions) {
if (a.id == excludeId) continue;
candidates.add(a.startAngle);
candidates.add(a.endAngle);
}
for (final PhaseZone z in project.phaseZones) {
candidates.add(z.startAngle);
candidates.add(z.endAngle);
}
final double end = rawStart + duration;
double best = rawStart;
double bestD = tol;
double? guide;
// 起点与终点同时参与匹配:取绝对调整量最小的一条候选。
for (final double cand in candidates) {
final double ds = (cand - rawStart).abs();
if (ds < bestD) {
bestD = ds;
best = cand;
guide = cand;
}
final double de = (cand - end).abs();
if (de < bestD) {
bestD = de;
best = cand - duration;
guide = cand;
}
}
return (best.clamp(0, 360 - duration), guide);
}