Files
EasyDesignCollection/lib/ui/canvas_view.dart
T

614 lines
25 KiB
Dart
Raw Normal View History

2026-09-18 16:50:12 +08:00
// 画布交互视图:承载条形 / 圆周两种节拍视图的绘制与全部手势操作。
//
// 架构位置:位于 UI 层核心,向下调用布局(BarLayout / CircularLayout)
// 与渲染器(BarPainter / CircularPainter),向上通过 AppController 修改
// 项目状态。本文件负责:
// · 屏幕坐标 → 逻辑坐标的变换(考虑平移与缩放);
// · 点选、双击新建、拖拽移动相位、拖拽端点改持续角、Shift 拖拽改层;
// · 空白区域拖拽平移、Ctrl + 滚轮缩放;
// · 右键上下文菜单。
import 'dart:math' as math;
2026-09-18 16:50:12 +08:00
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter/services.dart';
import '../layout/layout.dart';
import '../model/models.dart';
import '../render/bar_painter.dart';
import '../render/circular_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;
2026-09-18 16:50:12 +08:00
/// 控制器快捷访问器。
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 = 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;
}
/// 更新鼠标指针样式:靠近分区边界或动作端点时显示左右拖拽箭头。
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;
}
2026-09-18 16:50:12 +08:00
/// 动作端点弱吸附:贴合到整 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 Action? hit = c.project.viewState.mode == ViewMode.bar
? BarLayout(c.project, size).hitTest(p)
: CircularLayout(c.project, size).hitTest(p);
// 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) {
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)
: CircularLayout(c.project, size).hitTest(p);
// 双击动作色块 / 圆弧:进入该动作的编辑对话框。
if (hit != null) {
showDialog<void>(
context: context,
builder: (_) => ActionEditorDialog(controller: c, action: hit),
);
return;
}
2026-09-18 16:50:12 +08:00
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);
}
/// 拖拽开始:判断落点是否命中动作。
/// 条形视图下靠近动作右端 8px 视为“调整持续角”,否则为“平移相位”;
/// 圆周视图下统一为“平移相位”。未命中则进入画布平移模式。
void _onPanStart(DragStartDetails d, Size size) {
final Offset p = _toLogical(d.localPosition, size);
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? hit = layout.hitTest(p);
if (hit != null) {
final Rect r = layout.rectFor(hit);
final bool nearRight = (p.dx - r.right).abs() <= 8;
final bool nearLeft = (p.dx - r.left).abs() <= 8;
_mode = nearRight
? _DragMode.resize
: (nearLeft ? _DragMode.resizeStart : _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? hit = layout.hitTest(p);
if (hit != null) {
final double a = angleOf(layout.center, p);
final double rad = (p - layout.center).distance;
// 距端点约 9px 以内视为拖拽端点(改起止角),否则整体旋转。
final double tolDeg = math.atan2(9, 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);
2026-09-18 16:50:12 +08:00
_dragAction = hit;
_startPointer = p;
_startAngle = hit.startAngle;
_startDuration = hit.durationAngle;
_startAnglePointer = a;
c.select(hit.id);
return;
}
}
_mode = _DragMode.none;
_dragAction = null;
}
/// 拖拽更新:未命中动作时平移画布;命中动作时根据模式与修饰键
/// 计算增量并写回控制器(调整持续角 / 改层 / 平移相位)。
void _onPanUpdate(DragUpdateDetails d, Size size) {
final Offset p = _toLogical(d.localPosition, 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) {
c.panBy(d.delta);
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;
final double dy = p.dy - _startPointer.dy;
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 if (dy.abs() > dx.abs() + 6 && dy.abs() > 12) {
// 以垂直为主:上下拖拽换泳道(同泳道可放多个不重叠动作)。
final int target = layout.laneAt(p.dy);
_dropLane = target;
_dropValid = c.canPlaceInLane(_dragAction!.id, target);
c.moveActionLane(_dragAction!.id, target);
2026-09-18 16:50:12 +08:00
} else {
c.setActionStart(_dragAction!.id, _startAngle + dx / layout.span * 360);
}
} 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: '调整起始角',
);
2026-09-18 16:50:12 +08:00
} else if (shift) {
// Shift + 径向拖拽:换轨道(同轨道可放多个不重叠动作)。
final double rad = (p - layout.center).distance;
c.moveActionLane(_dragAction!.id, layout.laneAtRadius(rad));
2026-09-18 16:50:12 +08:00
} else {
c.setActionStart(_dragAction!.id, _startAngle + delta);
}
}
}
/// 拖拽结束:重置拖拽会话状态。
void _onPanEnd(DragEndDetails d) {
_mode = _DragMode.none;
_dragAction = null;
_zoneIndex = -1;
_zoneGuideAngle = null;
_dropLane = null;
2026-09-18 16:50:12 +08:00
}
/// 滚轮:按住 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.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) => _updateCursor(e.localPosition, size),
onExit: (_) {
if (_cursor != SystemMouseCursors.basic) {
setState(() => _cursor = SystemMouseCursors.basic);
}
},
// 指针信号监听:仅处理滚轮事件(缩放 / 平移)。
child: Listener(
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),
onPanStart: (DragStartDetails d) => _onPanStart(d, size),
onPanUpdate: (DragUpdateDetails d) => _onPanUpdate(d, size),
onPanEnd: _onPanEnd,
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: 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,
2026-09-18 16:50:12 +08:00
)
: CircularPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
guideAngle: _zoneGuideAngle,
2026-09-18 16:50:12 +08:00
),
),
),
),
),
),
);
},
);
}
}