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

856 lines
35 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 画布交互视图:承载条形 / 圆周两种节拍视图的绘制与全部手势操作。
//
// 架构位置:位于 UI 层核心,向下调用布局(BarLayout / CircularLayout)
// 与渲染器(BarPainter / CircularPainter),向上通过 AppController 修改
// 项目状态。本文件负责:
// · 屏幕坐标 → 逻辑坐标的变换(考虑平移与缩放);
// · 点选、双击新建、拖拽移动相位、拖拽端点改持续角、Shift 拖拽改层;
// · 空白区域拖拽平移、Ctrl + 滚轮缩放;
// · 右键上下文菜单。
import 'dart:io' show Platform;
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter/services.dart';
import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart';
import '../render/bar_painter.dart';
import '../render/circular_painter.dart';
import '../render/flow_painter.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
import 'dialogs.dart';
/// 当前拖拽行为类型:无操作 / 平移相位 / 拖右端改时长 / 拖左端改起始。
enum _DragMode { none, move, resize, resizeStart }
/// 画布视图组件:根据视图模式渲染图形并处理所有画布手势。
class CanvasView extends StatefulWidget {
/// 创建画布视图,[controller] 为全局应用控制器。
const CanvasView({super.key, required this.controller});
/// 全局应用控制器,提供项目数据与编辑动作。
final AppController controller;
/// 创建画布视图对应的状态对象。
@override
State<CanvasView> createState() => _CanvasViewState();
}
/// 画布视图状态:维护一次拖拽过程中的起始快照与拖拽模式。
class _CanvasViewState extends State<CanvasView> {
// ---- 拖拽会话状态:在一次手势内记录起始值,用于计算增量 ----
/// 当前拖拽模式(平移相位或调整持续角)。
_DragMode _mode = _DragMode.none;
/// 当前正在拖拽的动作;为空表示拖拽空白区域(执行画布平移)。
Action? _dragAction;
/// 手势按下时的逻辑坐标,作为位移计算的参考点。
Offset _startPointer = Offset.zero;
/// 动作在按下时的起始相位角。
double _startAngle = 0;
/// 动作在按下时的持续角。
double _startDuration = 0;
/// 圆周视图中按下时指针相对圆心的角度,用于计算旋转增量。
double _startAnglePointer = 0;
/// 正在拖拽的相位分区下标(-1 表示未在拖拽分区)。
int _zoneIndex = -1;
/// 拖拽的是分区的起始边界(true)还是结束边界(false)。
bool _zoneIsStart = false;
/// 拖拽分区边界或动作端点时的参考角(用于绘制虚线坐标参考);否则为 null。
double? _zoneGuideAngle;
/// 当前鼠标指针样式(靠近可拖拽端点时显示左右箭头)。
MouseCursor _cursor = SystemMouseCursors.basic;
/// 上下拖拽换泳道时的目标泳道号;非空时在画布上高亮。
int? _dropLane;
/// 目标泳道是否可放置(时间不重叠)。
bool _dropValid = true;
/// 是否处于双指捏合会话。
bool _pinching = false;
/// 捏合开始时的视图缩放。
double _pinchStartZoom = 1;
/// 捏合开始时的焦点(逻辑坐标),作为缩放锚点。
Offset _pinchFocalLogical = Offset.zero;
/// 触屏单指拖拽占用的原始指针 id(-1 表示空闲)。
///
/// 触屏平台(含手写笔)的单指拖拽走 [Listener] 原始指针事件:绕开手势竞技场
/// 与「精确指针」极小的滑移阈值,避免手写笔拖拽端点时被点按/双点按抢走判定。
int _rawPointer = -1;
/// 是否触屏平台(Android / iOS):端点拖拽容差加大、空白单指不平移。
bool get _touch => Platform.isAndroid || Platform.isIOS;
/// 命中容差:触屏用更大的目标,桌面保持精确。
double get _hitSlop => _touch ? 14 : 4;
/// 动作端点(两端把手)的抓取半径:触屏显著加大,避免误判为平移。
double get _grabRadius => _touch ? 28 : 8;
/// 控制器快捷访问器。
AppController get c => widget.controller;
/// 在条形图顶部的相位分区带上命中一条边界。
///
/// 返回命中的 `(分区下标, 是否起始边界)`;未命中返回 null。
/// 仅当指针落在分区带高度范围内、且距某条边界 8px 以内时命中。
(int, bool)? _hitZoneBoundary(Offset p, BarLayout layout) {
if (p.dy < BarPainter.phaseBandTop - 6 || p.dy > BarPainter.phaseBandTop + 40) return null;
final List<PhaseZone> zones = c.project.phaseZones;
int best = -1;
bool bestStart = false;
double bestDist = _touch ? 24 : 9;
for (int i = 0; i < zones.length; i++) {
final double xs = layout.xFor(zones[i].startAngle);
final double xe = layout.xFor(zones[i].endAngle);
final double ds = (p.dx - xs).abs();
final double de = (p.dx - xe).abs();
if (ds < bestDist) {
bestDist = ds;
best = i;
bestStart = true;
}
if (de < bestDist) {
bestDist = de;
best = i;
bestStart = false;
}
}
if (best < 0) return null;
return (best, bestStart);
}
/// 命中相位分区带内的某个分区(返回下标;未命中返回 -1)。
int _hitZoneAt(Offset p, BarLayout layout) {
if (p.dy < BarPainter.phaseBandTop - 6 || p.dy > BarPainter.phaseBandTop + 40) return -1;
final double angle = (p.dx - layout.plotLeft) / layout.span * 360;
for (int i = 0; i < c.project.phaseZones.length; i++) {
if (c.project.phaseZones[i].contains(angle)) return i;
}
return -1;
}
/// 命中动作两端的「把手」圆点:返回 `(动作, 是否起始端)`,未命中返回 null。
///
/// 把手绘制在动作端点(条形 = 条带左右两端、圆周 = 弧两端),可能略在动作本体
/// 之外;精确指针(手写笔)直接点在把手上时,仅靠动作命中测试会落空,因此这里
/// 单独做一次把手邻近命中,半径与 [_grabRadius] 一致。
(Action, bool)? _hitHandle(Offset p, Size size) {
// 流程图只读:无端点把手。
if (c.project.viewState.mode == ViewMode.flow) return null;
Action? best;
bool bestStart = false;
double bestDist = _grabRadius;
if (c.project.viewState.mode == ViewMode.bar) {
final BarLayout layout = BarLayout(c.project, size);
for (final Action a in c.project.actions) {
final Rect r = layout.rectFor(a);
final double ds = (p - Offset(r.left, r.center.dy)).distance;
final double de = (p - Offset(r.right, r.center.dy)).distance;
if (ds < bestDist) {
bestDist = ds;
best = a;
bestStart = true;
}
if (de < bestDist) {
bestDist = de;
best = a;
bestStart = false;
}
}
} else {
final CircularLayout layout = CircularLayout(c.project, size);
for (final Action a in c.project.actions) {
final double r = layout.radiusFor(a.layer);
final double ds = (p - polar(layout.center, r, a.startAngle)).distance;
final double de = (p - polar(layout.center, r, math.min(a.endAngle, 360))).distance;
if (ds < bestDist) {
bestDist = ds;
best = a;
bestStart = true;
}
if (de < bestDist) {
bestDist = de;
best = a;
bestStart = false;
}
}
}
return best == null ? null : (best, bestStart);
}
/// 更新鼠标指针样式:靠近分区边界或动作端点时显示左右拖拽箭头。
void _updateCursor(Offset local, Size size) {
final Offset p = _toLogical(local, size);
MouseCursor next = SystemMouseCursors.basic;
if (c.project.viewState.mode == ViewMode.bar) {
final BarLayout layout = BarLayout(c.project, size);
if (_hitZoneBoundary(p, layout) != null) {
next = SystemMouseCursors.resizeLeftRight;
} else {
final Action? hit = layout.hitTest(p);
if (hit != null) {
final Rect r = layout.rectFor(hit);
if ((p.dx - r.right).abs() <= 6 || (p.dx - r.left).abs() <= 6) {
next = SystemMouseCursors.resizeLeftRight;
}
}
}
}
if (next != _cursor) setState(() => _cursor = next);
}
/// 判断两个角度是否足够接近(用于圆周视图命中弧端点)。
bool _angleNear(double a, double b, double tolDeg) {
double d = (a - b) % 360;
if (d > 180) d -= 360;
if (d < -180) d += 360;
return d.abs() <= tolDeg;
}
/// 动作端点弱吸附:贴合到整 5°、分区边界或其它动作端点(容差 2.5°)。
double _snapActionAngle(double raw, String excludeId) {
const double tol = 2.5;
final List<double> cands = <double>[0, 360];
for (int d = 0; d <= 360; d += 5) {
cands.add(d.toDouble());
}
for (final Action a in c.project.actions) {
if (a.id == excludeId) continue;
cands.add(a.startAngle);
cands.add(a.endAngle);
}
for (final PhaseZone z in c.project.phaseZones) {
cands.add(z.startAngle);
cands.add(z.endAngle);
}
double best = raw;
double bestD = tol;
for (final double cand in cands) {
final double d = (cand - raw).abs();
if (d < bestD) {
bestD = d;
best = cand;
}
}
return best;
}
/// 弱吸附:把 [raw] 贴合到最近的整 5°、动作端点或其它分区边界(容差 2.5°)。
double _snapZoneAngle(double raw, int zoneIndex, bool isStart) {
const double tol = 2.5;
final List<double> cands = <double>[0, 360, 400];
for (int d = 0; d <= 400; d += 5) {
cands.add(d.toDouble());
}
for (final Action a in c.project.actions) {
cands.add(a.startAngle);
cands.add(a.endAngle);
}
for (int i = 0; i < c.project.phaseZones.length; i++) {
if (i == zoneIndex) continue;
cands.add(c.project.phaseZones[i].startAngle);
cands.add(c.project.phaseZones[i].endAngle);
}
double best = raw;
double bestD = tol;
for (final double cand in cands) {
final double d = (raw - cand).abs();
if (d < bestD) {
bestD = d;
best = cand;
}
}
return best.clamp(0, 400);
}
/// 双击分区带:弹出对话框重命名该分区。
Future<void> _renameZone(int index) async {
final PhaseZone z = c.project.phaseZones[index];
final TextEditingController ctrl = TextEditingController(text: z.name);
final String? name = await showDialog<String>(
context: context,
builder: (BuildContext ctx) => AlertDialog(
title: const Text('重命名相位分区'),
content: TextField(
controller: ctrl,
autofocus: true,
decoration: const InputDecoration(labelText: '分区名称'),
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
FilledButton(onPressed: () => Navigator.pop(ctx, ctrl.text.trim()), child: const Text('确定')),
],
),
);
ctrl.dispose();
if (name == null || name.isEmpty) return;
final List<PhaseZone> zones = List<PhaseZone>.of(c.project.phaseZones)..[index] = z.copyWith(name: name);
c.setPhaseZones(zones, status: '分区已重命名为「$name」');
}
// ===================== 坐标变换 =====================
/// 将画布局部坐标 [local] 转换为项目逻辑坐标:
/// 先减去平移量,再除以缩放系数。
Offset _toLogical(Offset local, Size size) {
final double z = c.project.viewState.zoom;
return Offset(
(local.dx - c.project.viewState.panX) / z,
(local.dy - c.project.viewState.panY) / z,
);
}
// ===================== 手势处理 =====================
/// 单击:命中最上层动作则选中,否则清空选中。
///
/// 流程图视图为只读:点击节点即选中对应动作(修改请回时序图)。
void _onTapDown(TapDownDetails d, Size 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);
hit = handle?.$1 ??
(mode == ViewMode.bar
? BarLayout(c.project, size).hitTest(p, slop: _hitSlop)
: CircularLayout(c.project, size).hitTest(p, slop: _hitSlop));
}
// Ctrl(或 Shift)点击:切换该动作的选中状态,实现多选。
final bool toggle = HardwareKeyboard.instance.isControlPressed ||
HardwareKeyboard.instance.isShiftPressed;
c.select(hit?.id, toggle: toggle && hit != null);
}
/// 双击空白处:按点击位置换算出的相位角新建动作;
/// 若双击在已有动作上则不处理。
void _onDoubleTapDown(TapDownDetails d, Size size) {
// 流程图只读:双击不新建动作、也不编辑。
if (c.project.viewState.mode == ViewMode.flow) return;
final Offset p = _toLogical(d.localPosition, size);
// 双击相位分区带:重命名该分区。
if (c.project.viewState.mode == ViewMode.bar) {
final int zi = _hitZoneAt(p, BarLayout(c.project, size));
if (zi >= 0) {
_renameZone(zi);
return;
}
}
final Action? hit = c.project.viewState.mode == ViewMode.bar
? BarLayout(c.project, size).hitTest(p, slop: _hitSlop)
: CircularLayout(c.project, size).hitTest(p, slop: _hitSlop);
// 双击动作色块 / 圆弧:进入该动作的编辑对话框。
if (hit != null) {
showDialog<void>(
context: context,
builder: (_) => ActionEditorDialog(controller: c, action: hit),
);
return;
}
double angle = 0;
if (c.project.viewState.mode == ViewMode.bar) {
angle = BarLayout(c.project, size).angleAt(p.dx);
} else {
final CircularLayout cl = CircularLayout(c.project, size);
angle = angleOf(cl.center, p);
}
c.addAction(startAngle: angle);
}
/// 拖拽开始:判断落点是否命中动作。
/// 条形视图下靠近动作端部([_grabRadius],触屏显著加大)视为“调整持续角 / 起始角”,
/// 否则为“平移相位”;圆周视图同理。未命中动作时:
/// - 桌面:进入画布平移模式;
/// - 触屏:不平移(单指只做选择 / 编辑,平移缩放交给双指)。
void _onPanStart(Offset p, Size size) {
// 流程图只读:不做时序编辑(空拖拽仍可按桌面习惯平移画布)。
if (c.project.viewState.mode == ViewMode.flow) {
_mode = _DragMode.none;
_dragAction = null;
return;
}
if (c.project.viewState.mode == ViewMode.bar) {
final BarLayout layout = BarLayout(c.project, size);
// 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。
final (int, bool)? zone = _hitZoneBoundary(p, layout);
if (zone != null) {
_zoneIndex = zone.$1;
_zoneIsStart = zone.$2;
_mode = _DragMode.none;
_dragAction = null;
_startPointer = p;
return;
}
// 端点把手优先:精确指针(手写笔)点在把手上时可能略在动作体之外,
// 先按把手邻近命中,直接进入「改时长 / 改起始角」模式。
final (Action, bool)? handle = _hitHandle(p, size);
if (handle != null) {
_mode = handle.$2 ? _DragMode.resizeStart : _DragMode.resize;
_dragAction = handle.$1;
_startPointer = p;
_startAngle = handle.$1.startAngle;
_startDuration = handle.$1.durationAngle;
c.select(handle.$1.id);
return;
}
final Action? hit = layout.hitTest(p, slop: _hitSlop);
if (hit != null) {
final Rect r = layout.rectFor(hit);
final double dr = (p.dx - r.right).abs();
final double dl = (p.dx - r.left).abs();
final bool nearRight = dr <= _grabRadius;
final bool nearLeft = dl <= _grabRadius;
if (nearRight && nearLeft) {
// 两端都够得着(短条):抓离手指更近的一端;几乎居中则整体移动。
_mode = dr < dl - 6
? _DragMode.resize
: (dl < dr - 6 ? _DragMode.resizeStart : _DragMode.move);
} else if (nearRight) {
_mode = _DragMode.resize;
} else if (nearLeft) {
_mode = _DragMode.resizeStart;
} else {
_mode = _DragMode.move;
}
_dragAction = hit;
_startPointer = p;
_startAngle = hit.startAngle;
_startDuration = hit.durationAngle;
c.select(hit.id);
return;
}
} else {
final CircularLayout layout = CircularLayout(c.project, size);
// 弧端点把手优先命中(同条形视图)。
final (Action, bool)? handle = _hitHandle(p, size);
if (handle != null) {
_mode = handle.$2 ? _DragMode.resizeStart : _DragMode.resize;
_dragAction = handle.$1;
_startPointer = p;
_startAngle = handle.$1.startAngle;
_startDuration = handle.$1.durationAngle;
_startAnglePointer = angleOf(layout.center, p);
c.select(handle.$1.id);
return;
}
final Action? hit = layout.hitTest(p, slop: _hitSlop);
if (hit != null) {
final double a = angleOf(layout.center, p);
final double rad = (p - layout.center).distance;
// 距端点 [grabRadius] 以内视为拖拽端点(改起止角),否则整体旋转。
final double tolDeg = math.atan2(_grabRadius, math.max(rad, 1)) * 180 / math.pi;
final bool nearStart = _angleNear(a, hit.startAngle, tolDeg);
final bool nearEnd = _angleNear(a, math.min(hit.endAngle, 360), tolDeg);
_mode = nearStart
? _DragMode.resizeStart
: (nearEnd ? _DragMode.resize : _DragMode.move);
_dragAction = hit;
_startPointer = p;
_startAngle = hit.startAngle;
_startDuration = hit.durationAngle;
_startAnglePointer = a;
c.select(hit.id);
return;
}
}
_mode = _DragMode.none;
_dragAction = null;
}
/// 拖拽更新:未命中动作时平移画布;命中动作时根据模式与修饰键
/// 计算增量并写回控制器(调整持续角 / 改层 / 平移相位)。
/// [p] 为指针逻辑坐标,[screenDelta] 为指针在屏幕(未变换)空间的位移。
void _onPanUpdate(Offset p, Offset screenDelta, Size size) {
// 拖拽相位分区边界:按横坐标换算角度(结束角允许超过 360° 表示跨圈),
// 并做「弱吸附」——靠近整 5°、动作端点或其它分区边界时自动贴合。
if (_zoneIndex >= 0) {
final BarLayout layout = BarLayout(c.project, size);
final double raw = ((p.dx - layout.plotLeft) / layout.span * 360).clamp(0, 400);
final double angle = _snapZoneAngle(raw, _zoneIndex, _zoneIsStart);
_zoneGuideAngle = angle;
c.movePhaseZoneBoundary(_zoneIndex, _zoneIsStart, angle);
return;
}
// 未命中动作:桌面端整幅画布跟随指针平移;触屏端不平移
// (单指只做选择 / 编辑,平移与缩放交给双指捏合)。
if (_dragAction == null) {
if (!_touch) c.panBy(screenDelta);
return;
}
final bool shift = HardwareKeyboard.instance.isShiftPressed;
if (c.project.viewState.mode == ViewMode.bar) {
// 条形视图:水平位移按时间轴跨度换算为相位角。
final BarLayout layout = BarLayout(c.project, size);
final double dx = p.dx - _startPointer.dx;
if (_mode == _DragMode.resize) {
// 拖右端:固定起始角,改结束角(弱吸附 + 虚线参考)。
final double rawEnd = _startAngle + _startDuration + dx / layout.span * 360;
final double end = _snapActionAngle(rawEnd, _dragAction!.id).clamp(_startAngle + 5, 360);
_zoneGuideAngle = end;
c.setActionDuration(_dragAction!.id, end - _startAngle);
} else if (_mode == _DragMode.resizeStart) {
// 拖左端:固定结束角,改起始角(弱吸附 + 虚线参考)。
final double rawStart = _startAngle + dx / layout.span * 360;
final double fixedEnd = _startAngle + _startDuration;
final double ns = _snapActionAngle(rawStart, _dragAction!.id).clamp(0, fixedEnd - 5);
_zoneGuideAngle = ns;
c.updateAction(
_dragAction!.id,
(Action x) => x.copyWith(startAngle: ns, durationAngle: fixedEnd - ns),
status: '调整起始角',
);
} else {
// 整体移动:水平改起始相位 + 垂直跟随泳道,两者可同时进行。
// (原先要求「垂直分量明显大于水平」才换道,斜向拖拽几乎换不了道,
// 表现为“有一股磁吸力、拖不到别的泳道”。)
c.setActionStart(_dragAction!.id, _startAngle + dx / layout.span * 360);
final int curLane =
c.project.actionById(_dragAction!.id)?.layer ?? _dragAction!.layer;
final int target = layout.laneAt(p.dy);
if (target != curLane) {
_dropLane = target;
_dropValid = c.canPlaceInLane(_dragAction!.id, target);
c.moveActionLane(_dragAction!.id, target);
}
}
} else {
// 圆周视图:用指针相对圆心的角度差作为旋转增量,并归一化到 ±180°。
final CircularLayout layout = CircularLayout(c.project, size);
final double a = angleOf(layout.center, p);
double delta = a - _startAnglePointer;
if (delta > 180) delta -= 360;
if (delta < -180) delta += 360;
if (_mode == _DragMode.resize) {
// 拖弧末端:固定起始角,改结束角(弱吸附 + 径向虚线参考)。
final double end = _snapActionAngle(_startAngle + _startDuration + delta, _dragAction!.id);
_zoneGuideAngle = end;
c.setActionDuration(_dragAction!.id, (end - _dragAction!.startAngle).clamp(5, 360));
} else if (_mode == _DragMode.resizeStart) {
// 拖弧起始端:固定结束角,改起始角。
final double fixedEnd = _startAngle + _startDuration;
final double ns = _snapActionAngle(_startAngle + delta, _dragAction!.id).clamp(0, fixedEnd - 5);
_zoneGuideAngle = ns;
c.updateAction(
_dragAction!.id,
(Action x) => x.copyWith(startAngle: ns, durationAngle: fixedEnd - ns),
status: '调整起始角',
);
} else if (shift) {
// Shift + 径向拖拽:换轨道(同轨道可放多个不重叠动作)。
final double rad = (p - layout.center).distance;
c.moveActionLane(_dragAction!.id, layout.laneAtRadius(rad));
} else {
c.setActionStart(_dragAction!.id, _startAngle + delta);
}
}
}
/// 拖拽结束:重置拖拽会话状态。
void _onPanEnd() {
_mode = _DragMode.none;
_dragAction = null;
_zoneIndex = -1;
_zoneGuideAngle = null;
_dropLane = null;
}
// ===================== 原始指针单指拖拽(触屏:手指 / 手写笔) =====================
/// 原始指针按下:触屏平台自按下瞬间接管单指拖拽。
///
/// 与手势体系解耦,手写笔(精确指针)与手指行为一致;若已有指针在拖拽时
/// 又落下第二根手指,则放弃单指拖拽,交回缩放手势做双指捏合。
void _onRawDown(PointerDownEvent e, Size size) {
if (!_touch) return;
if (_rawPointer == -1) {
_rawPointer = e.pointer;
_onPanStart(_toLogical(e.localPosition, size), size);
return;
}
if (e.pointer != _rawPointer) {
// 第二根手指落下:结束单指拖拽,改由 _onScaleStart 进入捏合。
_rawPointer = -1;
_onPanEnd();
}
}
/// 原始指针移动:单指拖拽(复用 [_onPanUpdate] 的编辑逻辑)。
void _onRawMove(PointerMoveEvent e, Size size) {
if (!_touch || e.pointer != _rawPointer) return;
_onPanUpdate(_toLogical(e.localPosition, size), e.localDelta, size);
}
/// 原始指针抬起 / 取消:结束单指拖拽。
void _onRawUp(PointerEvent e) {
if (!_touch || e.pointer != _rawPointer) return;
_rawPointer = -1;
_onPanEnd();
}
// ===================== 双指捏合缩放 / 平移 =====================
/// 进入捏合会话:记录起始缩放与逻辑焦点(作为缩放锚点)。
void _beginPinch(Offset logicalFocal) {
_pinching = true;
_pinchStartZoom = c.project.viewState.zoom;
_pinchFocalLogical = logicalFocal;
_mode = _DragMode.none;
_dragAction = null;
_zoneIndex = -1;
_zoneGuideAngle = null;
_dropLane = null;
}
/// 缩放手势开始:双指进入捏合;桌面的单指针仍由该手势分发
/// (触屏单指已被 [_onRawDown] 原始指针通道接管,避免竞技场抢判定)。
void _onScaleStart(ScaleStartDetails d, Size size) {
final Offset p = _toLogical(d.localFocalPoint, size);
if (d.pointerCount >= 2) {
_beginPinch(p);
} else if (!_touch) {
_onPanStart(p, size);
}
}
/// 缩放手势更新:
/// - 双指:以捏合焦点为锚点同时缩放与平移(焦点处内容跟随手指);
/// - 单指:仅桌面走此路径(平移相位 / 改时长 / 平移画布)。
void _onScaleUpdate(ScaleUpdateDetails d, Size size) {
final Offset p = _toLogical(d.localFocalPoint, size);
if (d.pointerCount >= 2) {
// 拖拽中途落下第二根手指:立即切换为捏合。
if (!_pinching) _beginPinch(p);
final double z = (_pinchStartZoom * d.scale).clamp(0.25, 4.0);
// 锚点公式:screen = logical × zoom + pan → pan = screenFocal − logicalFocal × z。
c.setViewTransform(
zoom: z,
panX: d.localFocalPoint.dx - _pinchFocalLogical.dx * z,
panY: d.localFocalPoint.dy - _pinchFocalLogical.dy * z,
);
} else if (!_pinching && !_touch) {
_onPanUpdate(p, d.focalPointDelta, size);
}
}
/// 缩放手势结束:重置捏合与拖拽会话状态。
void _onScaleEnd(ScaleEndDetails d) {
_pinching = false;
_onPanEnd();
}
/// 滚轮:按住 Ctrl 时以指针方向缩放,否则按滚轮增量平移画布。
void _onScroll(PointerScrollEvent e, Size size) {
if (HardwareKeyboard.instance.isControlPressed) {
// 以光标位置为锚点缩放,避免“越缩越偏”。
c.zoomAt(e.scrollDelta.dy > 0 ? 0.92 : 1.08, e.localPosition);
} else {
c.panBy(Offset(-e.scrollDelta.dx, -e.scrollDelta.dy));
}
}
// ===================== 右键上下文菜单 =====================
/// 在命中动作处弹出右键菜单,提供添加依赖、改层、复制、删除等操作;
/// 若右键落在相位分区带上,则弹出分区的增删改菜单。
Future<void> _contextMenu(Offset global, Size size) async {
final Offset local = _toLogical(global, size);
// 流程图只读:右键仅做选中联动。
if (c.project.viewState.mode == ViewMode.flow) {
c.select(FlowLayout(c.project).hitTest(local)?.id);
return;
}
if (c.project.viewState.mode == ViewMode.bar) {
final int zi = _hitZoneAt(local, BarLayout(c.project, size));
if (zi >= 0) {
await _zoneMenu(global, zi);
return;
}
}
final Action? hit = c.project.viewState.mode == ViewMode.bar
? BarLayout(c.project, size).hitTest(local)
: CircularLayout(c.project, size).hitTest(local);
if (hit == null) return;
c.select(hit.id);
final RenderBox box = context.findRenderObject()! as RenderBox;
final Offset pos = box.globalToLocal(global);
final String? result = await showMenu<String>(
context: context,
position: RelativeRect.fromLTRB(pos.dx, pos.dy, pos.dx, pos.dy),
items: const <PopupMenuEntry<String>>[
PopupMenuItem<String>(value: 'add-dep', child: Text('添加依赖…')),
PopupMenuItem<String>(value: 'layer-up', child: Text('上移一层')),
PopupMenuItem<String>(value: 'layer-down', child: Text('下移一层')),
PopupMenuItem<String>(value: 'duplicate', child: Text('复制动作')),
PopupMenuItem<String>(value: 'delete', child: Text('删除动作')),
],
);
if (result == null) return;
// 根据菜单选项分派到对应控制器动作。
switch (result) {
case 'layer-up':
c.changeLayer(hit.id, 1);
break;
case 'layer-down':
c.changeLayer(hit.id, -1);
break;
case 'duplicate':
c.duplicateSelected();
break;
case 'delete':
c.deleteAction(hit.id);
break;
case 'add-dep':
break;
}
}
/// 相位分区右键菜单:重命名 / 插入 / 删除,实现任意增减。
Future<void> _zoneMenu(Offset global, int index) async {
final RenderBox box = context.findRenderObject()! as RenderBox;
final Offset pos = box.globalToLocal(global);
final String? result = await showMenu<String>(
context: context,
position: RelativeRect.fromLTRB(pos.dx, pos.dy, pos.dx, pos.dy),
items: const <PopupMenuEntry<String>>[
PopupMenuItem<String>(value: 'rename', child: Text('重命名分区')),
PopupMenuItem<String>(value: 'insert', child: Text('在其后插入分区')),
PopupMenuItem<String>(value: 'delete', child: Text('删除此分区')),
PopupMenuItem<String>(value: 'edit-all', child: Text('编辑全部…')),
],
);
if (result == null) return;
if (result == 'rename') {
await _renameZone(index);
return;
}
if (result == 'edit-all') {
if (!mounted) return;
await showDialog<void>(context: context, builder: (_) => PhaseZoneDialog(controller: c));
return;
}
final List<PhaseZone> zones = List<PhaseZone>.of(c.project.phaseZones);
if (result == 'insert') {
final PhaseZone z = zones[index];
final double mid = ((z.startAngle + z.endAngle) / 2).clamp(0, 360);
zones.insert(index + 1, PhaseZone(name: '分区 ${zones.length + 1}', startAngle: mid, endAngle: (mid + 30).clamp(0, 400)));
c.setPhaseZones(zones, status: '已插入分区');
} else if (result == 'delete') {
zones.removeAt(index);
c.setPhaseZones(zones, status: '已删除分区');
}
}
// ===================== 构建与视图变换 =====================
/// 构建画布:用 [LayoutBuilder] 获取可用尺寸,[Listener] 处理滚轮,
/// [GestureDetector] 处理点选/拖拽/右键,[Transform] 应用平移与缩放,
/// 最后由对应的 Painter 完成绘制。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return LayoutBuilder(
builder: (BuildContext ctx, BoxConstraints constraints) {
final Size size = Size(constraints.maxWidth, constraints.maxHeight);
// 回填视口尺寸,供控制器计算「适应窗口」与居中缩放锚点。
c.setViewport(size);
// 鼠标指针样式:靠近分区边界或动作端点时变为左右拖拽箭头。
return MouseRegion(
cursor: _cursor,
onHover: (PointerHoverEvent e) {
// 仅鼠标需要光标提示;手写笔悬停会持续触发,跳过无谓重建。
if (e.kind == PointerDeviceKind.mouse) _updateCursor(e.localPosition, size);
},
onExit: (_) {
if (_cursor != SystemMouseCursors.basic) {
setState(() => _cursor = SystemMouseCursors.basic);
}
},
// 指针监听:滚轮(缩放 / 平移)+ 触屏单指拖拽
//(走原始指针事件,手指与手写笔行为一致,不受手势竞技场影响)。
child: Listener(
onPointerDown: (PointerDownEvent e) => _onRawDown(e, size),
onPointerMove: (PointerMoveEvent e) => _onRawMove(e, size),
onPointerUp: _onRawUp,
onPointerCancel: _onRawUp,
onPointerSignal: (PointerSignalEvent e) {
if (e is PointerScrollEvent) _onScroll(e, size);
},
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails d) => _onTapDown(d, size),
onDoubleTapDown: (TapDownDetails d) => _onDoubleTapDown(d, size),
// 单指拖拽编辑 / 双指捏合缩放平移:由缩放手势回调统一分发。
onScaleStart: (ScaleStartDetails d) => _onScaleStart(d, size),
onScaleUpdate: (ScaleUpdateDetails d) => _onScaleUpdate(d, size),
onScaleEnd: _onScaleEnd,
onSecondaryTapDown: (TapDownDetails d) => _contextMenu(d.globalPosition, size),
// 裁剪到画布范围内,避免缩放/平移后内容溢出。
child: ClipRect(
// 应用视图变换矩阵:先平移(panX/panY),再整体缩放(zoom)。
child: Transform(
transform: Matrix4.identity()
..setEntry(0, 3, c.project.viewState.panX)
..setEntry(1, 3, c.project.viewState.panY)
..setEntry(0, 0, c.project.viewState.zoom)
..setEntry(1, 1, c.project.viewState.zoom)
..setEntry(2, 2, c.project.viewState.zoom),
child: CustomPaint(
size: size,
painter: switch (c.project.viewState.mode) {
ViewMode.bar => BarPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
guideAngle: _zoneGuideAngle,
dropLane: _dropLane,
dropValid: _dropValid,
),
ViewMode.circular => CircularPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
guideAngle: _zoneGuideAngle,
),
ViewMode.flow => FlowchartPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
),
},
),
),
),
),
),
);
},
);
}
}