feat: V1.0.0 发布(呆头鹅)

- 默认浅色白底主题;字体整数化 + Microsoft YaHei UI 提升清晰度
- 相位分区:圆周/条形显示、沿弧排列、拖拽边界(虚线参考+弱吸附)、增删改(对话框/右键/双击)
- 动作:Ctrl 多选批量对齐;上下拖拽自由换行;左右端拖拽改起止(虚线+弱吸附+左右箭头光标)
- 动作编辑支持角度与时间双向换算
- 圆周顺时针箭头移至刻度环外;条形左侧标题列收窄
- 侧栏可隐藏/钉住;适应视图按内容自适应;节拍统计改为按钮弹窗
- AI 生成时序图(DeepSeek,Flash/Pro,推理强度),基于 dart:io 无插件
- 窗口标题显示文件名/未命名文件;关于信息(设计人/版本/版权)
- 全量中文注释、docs/ARCHITECTURE.md、docs/HELP.md(按任务组织)
- 构建脚本输出到 dist/,并附带 dist 生成物
This commit is contained in:
呆头鹅
2026-09-18 16:50:12 +08:00
parent e7ffa35959
commit 6cfa79507c
51 changed files with 12340 additions and 0 deletions
+280
View File
@@ -0,0 +1,280 @@
/// AI 生成时序图对话框。
///
/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)与推理强度
/// (高 / 最高)→ 在较大的自然语言输入框中描述工艺流程 → 点击「生成」,
/// 由 [AiClient] 调用大模型并解析为 [Project],成功后载入工作台。
///
/// 安全:API Key 仅保存在内存(静态字段,便于本次会话内复用),
/// 不写入工程文件,也不会被日志输出。
library;
import 'package:flutter/material.dart';
import '../ai/ai_client.dart';
import '../model/models.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
class AiGenerateDialog extends StatefulWidget {
const AiGenerateDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
@override
State<AiGenerateDialog> createState() => _AiGenerateDialogState();
}
class _AiGenerateDialogState extends State<AiGenerateDialog> {
/// 会话内复用的 API Key(不持久化)。
static String _sessionKey = '';
late final TextEditingController _key;
late final TextEditingController _prompt;
String _model = kAiModels.first.id;
String _effort = 'high';
bool _obscure = true;
bool _busy = false;
String? _error;
@override
void initState() {
super.initState();
_key = TextEditingController(text: _sessionKey);
_prompt = TextEditingController();
}
@override
void dispose() {
_key.dispose();
_prompt.dispose();
super.dispose();
}
Future<void> _generate() async {
setState(() {
_busy = true;
_error = null;
});
try {
_sessionKey = _key.text.trim();
final Project p = await AiClient.generate(
prompt: _prompt.text,
settings: AiSettings(apiKey: _sessionKey, model: _model, effort: _effort),
);
widget.controller.loadProject(p, dirty: true);
widget.controller.setStatus('AI 已生成时序图(${p.actions.length} 个动作)');
if (mounted) Navigator.pop(context);
} catch (e) {
if (mounted) setState(() => _error = '$e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: SizedBox(
width: 880,
height: 620,
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// 标题
Row(
children: <Widget>[
Icon(Icons.auto_awesome, size: 20, color: t.accent2),
const SizedBox(width: 8),
Text('AI 生成时序图', style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w700)),
const Spacer(),
Text('自然语言 → 时序图', style: TextStyle(color: t.dim, fontSize: 10)),
],
),
const Divider(height: 22),
// API Key
Text('DeepSeek API Key', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
TextField(
controller: _key,
obscureText: _obscure,
style: TextStyle(color: t.text, fontSize: 11),
decoration: InputDecoration(
isDense: true,
hintText: 'sk-...',
hintStyle: TextStyle(color: t.dim, fontSize: 11),
filled: true,
fillColor: t.panel2,
prefixIcon: Icon(Icons.key, size: 16, color: t.dim),
suffixIcon: IconButton(
onPressed: () => setState(() => _obscure = !_obscure),
icon: Icon(_obscure ? Icons.visibility_off : Icons.visibility, size: 16, color: t.dim),
tooltip: _obscure ? '显示' : '隐藏',
),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
const SizedBox(height: 14),
// 模型 + 推理强度
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('模型', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
Container(
height: 38,
padding: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line2),
),
child: DropdownButton<String>(
value: _model,
isExpanded: true,
underline: const SizedBox.shrink(),
dropdownColor: t.dialog,
style: TextStyle(color: t.text, fontSize: 11),
icon: Icon(Icons.keyboard_arrow_down, size: 18, color: t.sub),
items: kAiModels
.map((AiModelOption m) =>
DropdownMenuItem<String>(value: m.id, child: Text(m.label)))
.toList(),
onChanged: (String? v) {
if (v != null) setState(() => _model = v);
},
),
),
],
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('推理强度', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
Row(
children: <Widget>[
Expanded(child: _effortChip(t, '高', 'high')),
const SizedBox(width: 8),
Expanded(child: _effortChip(t, '最高', 'max')),
],
),
],
),
),
],
),
const SizedBox(height: 14),
// 自然语言输入(大输入框)
Text('用自然语言描述工艺流程', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
Expanded(
child: Container(
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: t.line2),
),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: TextField(
controller: _prompt,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: TextStyle(color: t.text, fontSize: 11, height: 1.5),
decoration: InputDecoration.collapsed(
hintText: '例如:一条装配线,循环 2.4 秒。上料后定位夹紧,夹紧完成再伺服下压 0.6 秒;'
'下压完成后并行进行超声波焊接与视觉检测;检测完成分选下料,最后清洁吹气。'
'共 3 个工位,请给出动作、相位与依赖关系。',
hintStyle: TextStyle(color: t.dim, fontSize: 11, height: 1.5),
),
),
),
),
if (_error != null) ...<Widget>[
const SizedBox(height: 10),
Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: t.danger.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.danger.withValues(alpha: 0.5)),
),
child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11, height: 1.4)),
),
],
const SizedBox(height: 14),
// 操作按钮
Row(
children: <Widget>[
Expanded(
child: Text(
'API Key 仅保存在本机内存,不写入工程文件。',
style: TextStyle(color: t.dim, fontSize: 10),
),
),
TextButton(onPressed: _busy ? null : () => Navigator.pop(context), child: const Text('取消')),
const SizedBox(width: 8),
FilledButton.icon(
onPressed: _busy ? null : _generate,
icon: _busy
? const SizedBox(
width: 15,
height: 15,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.auto_awesome, size: 16),
label: Text(_busy ? '生成中…' : '生成'),
style: FilledButton.styleFrom(
backgroundColor: t.accent2,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
),
),
],
),
],
),
),
),
);
}
/// 推理强度分段按钮。
Widget _effortChip(Tokens t, String label, String value) {
final bool active = _effort == value;
return InkWell(
onTap: () => setState(() => _effort = value),
borderRadius: BorderRadius.circular(8),
child: Container(
height: 38,
alignment: Alignment.center,
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.18) : t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: active ? t.accent : t.line2),
),
child: Text(label, style: TextStyle(color: active ? t.accent : t.sub, fontSize: 11)),
),
);
}
}
+88
View File
@@ -0,0 +1,88 @@
// 应用图标组件:绘制一个与应用程序图标一致的紧凑“时钟 / 周期表盘”标记。
//
// 架构位置:属于纯 UI 装饰组件,仅依赖主题令牌(Tokens)取色,
// 不持有任何业务状态;在工具栏与启动画面等处复用。
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../theme/tokens.dart';
/// 应用图标:一个简洁的时钟 / 周期表盘标记,呼应产品“节拍”主题。
class AppLogo extends StatelessWidget {
/// 创建应用图标;[size] 为正方形边长,默认 30。
const AppLogo({super.key, this.size = 30});
/// 图标边长(逻辑像素)。
final double size;
/// 使用 [_LogoPainter] 在方形画布上绘制图标。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return CustomPaint(
size: Size.square(size),
painter: _LogoPainter(t),
);
}
}
/// 图标绘制器:按主题令牌绘制圆角底板、双色圆弧表盘与指针。
class _LogoPainter extends CustomPainter {
/// 创建绘制器,[t] 为当前主题令牌。
_LogoPainter(this.t);
/// 当前主题令牌,提供配色。
final Tokens t;
/// 依次绘制:圆角底板 → 双色圆环弧 → 时针分针 → 中心圆点。
@override
void paint(Canvas canvas, Size size) {
// 以最短边为基准计算尺寸,保证图标始终为正方形。
final double s = size.shortestSide;
final Offset c = Offset(size.width / 2, size.height / 2);
// 圆角方形底板:半透明填充 + 主题色描边。
final RRect badge = RRect.fromRectAndRadius(
Rect.fromLTWH(0, 0, s, s),
Radius.circular(s * 0.28),
);
canvas.drawRRect(badge, Paint()..color = t.accent.withValues(alpha: 0.16));
canvas.drawRRect(
badge,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2
..color = t.accent,
);
// 表盘圆环:用两段不同颜色的圆弧表示进度/周期。
final double r = s * 0.30;
final Paint ring = Paint()
..style = PaintingStyle.stroke
..strokeWidth = s * 0.075
..strokeCap = StrokeCap.round;
ring.color = t.accent;
canvas.drawArc(Rect.fromCircle(center: c, radius: r), -math.pi / 2,
math.pi * 0.55, false, ring);
ring.color = t.accent2;
canvas.drawArc(Rect.fromCircle(center: c, radius: r), -math.pi / 2 + math.pi * 0.62,
math.pi * 0.5, false, ring);
// 指针:一根主色长针 + 一根强调色短针,从中心向外绘制。
final Paint hand = Paint()
..strokeCap = StrokeCap.round
..strokeWidth = s * 0.085;
hand.color = t.text;
canvas.drawLine(c, c.translate(0, -r * 0.62), hand);
hand.color = t.accent;
canvas.drawLine(c, c.translate(r * 0.5, r * 0.16), hand);
// 中心轴点:外圈文字色、内圈背景色,形成中空圆点。
canvas.drawCircle(c, s * 0.055, Paint()..color = t.text);
canvas.drawCircle(c, s * 0.022, Paint()..color = t.bg);
}
/// 仅当主题令牌变化时重绘。
@override
bool shouldRepaint(covariant _LogoPainter old) => old.t != t;
}
File diff suppressed because it is too large Load Diff
+899
View File
@@ -0,0 +1,899 @@
// 画布浮层:绘制在交互画布之上的固定信息面板,对应设计稿中的
// 标题、图例、统计、实时预览与编辑工具等元素。
//
// 架构位置:属于纯展示层,叠加在 CanvasView 之上,通过 AppController
// 读取项目数据;所有浮层均使用 IgnorePointer 或自身交互包裹,避免
// 遮挡画布手势。本文件通过 LayoutBuilder 依据窗口尺寸做响应式断点,
// 决定各面板是否显示。
import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
import 'dialogs.dart';
/// 画布浮层容器:按响应式断点组合并定位各信息面板。
class CanvasOverlays extends StatelessWidget {
/// 创建浮层容器,[controller] 为全局应用控制器。
const CanvasOverlays({super.key, required this.controller});
/// 全局应用控制器,提供项目数据与编辑动作。
final AppController controller;
/// 控制器快捷访问器。
AppController get c => controller;
/// 使用 [LayoutBuilder] 获取可用尺寸,计算响应式断点后,
/// 通过 [Stack] + [Positioned] 摆放各浮层面板。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
final bool circular = c.project.viewState.mode == ViewMode.circular;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final double w = constraints.maxWidth;
final double h = constraints.maxHeight;
// ---- 响应式断点:不同尺寸下显示不同的浮层组合 ----
// 圆周视图左侧图例列:需要较宽较高的窗口。
final bool showLeftColumn = circular && w >= 1500 && h >= 820;
// 条形视图统计卡片:中等尺寸以上显示。
final bool showStats = !circular && w >= 900 && h >= 760;
// 编辑工具条:门槛最低,几乎始终显示。
final bool showTools = w >= 760;
// 实时预览卡片:需要大屏才显示。
final bool showPreview = w >= 1400 && h >= 760;
// 浮层整体使用 Stack 叠加,各面板按断点条件选择性插入。
return Stack(
children: <Widget>[
// 顶部标题与副标题,横跨整个画布宽度,不拦截手势。
Positioned(
left: 18,
top: 12,
right: 18,
child: IgnorePointer(child: _Title(t: t, circular: circular, project: c.project)),
),
// 圆周视图左侧信息列:图例 + 选中卡片 + 依赖图例。
if (showLeftColumn)
Positioned(
left: 18,
top: 70,
bottom: 12,
width: 268,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
IgnorePointer(child: _CircularLegend(t: t, project: c.project)),
const SizedBox(height: 12),
IgnorePointer(child: _SelectedCard(t: t, c: c, circular: true)),
const SizedBox(height: 12),
IgnorePointer(child: _DepTypeLegend(t: t)),
],
),
),
),
// 条形视图左下角:节拍统计 + 编辑工具。
if (!circular && (showStats || showTools))
Positioned(
left: 18,
bottom: 12,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (showStats) ...<Widget>[
_StatsButton(t: t, c: c),
const SizedBox(height: 8),
],
_EditTools(t: t, c: c),
],
),
),
// 右下角实时预览:圆周视图显示条形缩略,反之亦然。
if (showPreview)
Positioned(
right: 18,
bottom: 12,
child: IgnorePointer(
child: circular
? _BarPreviewCard(t: t, project: c.project)
: _CircularPreviewCard(t: t, project: c.project),
),
),
// 圆周视图右侧浮动工具栏(添加/编辑/复制/删除/改层/对齐/帮助)。
if (circular)
Positioned(
right: 16,
top: 120,
child: _FloatingToolbar(t: t, c: c),
),
],
);
},
);
}
}
/// 通用卡片容器:统一浮层的背景、圆角与边框样式。
class _Card extends StatelessWidget {
const _Card({required this.t, required this.child, this.width, this.borderColor});
/// 主题令牌。
final Tokens t;
/// 卡片内容。
final Widget child;
/// 可选固定宽度。
final double? width;
/// 可选边框颜色,默认使用主题分隔线色。
final Color? borderColor;
@override
Widget build(BuildContext context) {
return Container(
width: width,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: t.panel2.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: borderColor ?? t.line),
),
child: child,
);
}
}
/// 顶部标题浮层:显示当前视图名称与双刻度/图例说明。
class _Title extends StatelessWidget {
const _Title({required this.t, required this.circular, required this.project});
/// 主题令牌。
final Tokens t;
/// 是否处于圆周视图。
final bool circular;
/// 当前项目,用于展示循环时长等文案。
final Project project;
@override
Widget build(BuildContext context) {
final String title = circular
? '圆周节拍视图(同心圆 · 12 点钟起始 · 顺时针)'
: '条形节拍视图(甘特 / 流程图 · 依赖箭头)';
final String sub = circular
? '同心圆环 = 动作层;箭头 = 执行顺序(绿色实线 FS 严格顺序,琥珀虚线 SS 并行重叠);1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%'
: '时间轴与相位角双刻度联动;箭头表示动作间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠);跨循环动作自动拆分并标注';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(title, style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
Text(sub, style: TextStyle(color: t.dim, fontSize: 11)),
],
);
}
}
/// 圆周视图左侧图例:逐条列出动作的层号、相位区间与时长。
class _CircularLegend extends StatelessWidget {
const _CircularLegend({required this.t, required this.project});
/// 主题令牌。
final Tokens t;
/// 当前项目,用于枚举动作。
final Project project;
@override
Widget build(BuildContext context) {
return _Card(
t: t,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('图层 / 相位图例', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
for (int i = 0; i < project.actions.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 15,
height: 15,
margin: const EdgeInsets.only(top: 2),
decoration: BoxDecoration(
color: Color(project.actions[i].color),
borderRadius: BorderRadius.circular(5),
),
),
const SizedBox(width: 9),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('${i + 1}. ${project.actions[i].id} ${project.actions[i].name}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.text2, fontSize: 11)),
Text(
'L${project.actions[i].layer + 1} · ${project.actions[i].startAngle.toStringAsFixed(0)}°–${math.min(project.actions[i].endAngle, 360).toStringAsFixed(0)}° · ${tfmt(project.actions[i].durationAngle / 360 * project.cycle.durationMs, project.units)}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.dim, fontSize: 10),
),
],
),
),
],
),
),
],
),
);
}
}
/// 选中动作信息卡:展示选中动作的起止/持续相位与所在层。
class _SelectedCard extends StatelessWidget {
const _SelectedCard({required this.t, required this.c, required this.circular});
/// 主题令牌。
final Tokens t;
/// 全局应用控制器。
final AppController c;
/// 是否处于圆周视图(用于文案微调)。
final bool circular;
@override
Widget build(BuildContext context) {
final Action? a = c.selected;
if (a == null) {
return _Card(
t: t,
borderColor: t.accent,
child: Text('未选中动作\n点击画布或左侧列表选择', style: TextStyle(color: t.dim, fontSize: 11, height: 1.6)),
);
}
final UnitSettings u = c.project.units;
final double cycle = c.project.cycle.durationMs;
final Station? st = c.project.stationById(a.stationId);
final String delta = tfmt(a.durationAngle / 360 * cycle, u);
return _Card(
t: t,
borderColor: t.accent,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('选中动作', style: TextStyle(color: t.accent, fontSize: 10, fontWeight: FontWeight.w700, letterSpacing: 1)),
const SizedBox(height: 6),
Text('${a.id} ${a.name}', style: TextStyle(color: t.text, fontSize: 13, fontWeight: FontWeight.w700)),
const SizedBox(height: 8),
_kv(t, '起始相位', pfmt(a.startAngle, u)),
_kv(t, '结束相位', pfmt(a.endAngle, u)),
_kv(t, '持续相位', pfmt(a.durationAngle, u)),
const SizedBox(height: 4),
Text('Δ = $delta · 层 L${a.layer + 1} · ${st?.id ?? a.stationId}',
style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)),
],
),
);
}
/// 渲染一行“标签 — 值”信息。
Widget _kv(Tokens t, String k, String v) => Padding(
padding: const EdgeInsets.only(bottom: 3),
child: Row(
children: <Widget>[
Text(k, style: TextStyle(color: t.sub, fontSize: 11)),
const Spacer(),
Flexible(
child: Text(v,
textAlign: TextAlign.right,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.text, fontSize: 11, fontWeight: FontWeight.w600)),
),
],
),
);
}
/// 依赖类型图例:说明 FS/SS 及关键路径的线条样式含义。
class _DepTypeLegend extends StatelessWidget {
const _DepTypeLegend({required this.t});
/// 主题令牌。
final Tokens t;
@override
Widget build(BuildContext context) {
Widget row(Widget sample, String label) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
children: <Widget>[
SizedBox(width: 48, child: sample),
const SizedBox(width: 8),
Expanded(child: Text(label, style: TextStyle(color: t.sub, fontSize: 10))),
],
),
);
return _Card(
t: t,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('执行顺序 / 依赖类型', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
const SizedBox(height: 10),
row(_SampleLine(color: t.fs, dash: false, arrow: true), 'FS 严格顺序(完成后启动)'),
row(_SampleLine(color: t.ss, dash: true, arrow: true), 'SS 并行重叠(可提前启动)'),
row(_SampleLine(color: t.fs, dash: false, arrow: false, star: true), '关键路径(累计最长链)'),
],
),
);
}
}
/// 图例中的示例线段:可组合实线/虚线、箭头与关键路径星标。
class _SampleLine extends StatelessWidget {
const _SampleLine({required this.color, required this.dash, required this.arrow, this.star = false});
/// 线条颜色。
final Color color;
/// 是否绘制为虚线。
final bool dash;
/// 是否绘制箭头。
final bool arrow;
/// 是否绘制关键路径星标。
final bool star;
/// 用 [_SamplePainter] 绘制示例线段。
@override
Widget build(BuildContext context) {
return SizedBox(
height: 16,
child: CustomPaint(painter: _SamplePainter(color, dash, arrow, star)),
);
}
}
/// 示例线段绘制器:按参数绘制实/虚线、箭头与星标。
class _SamplePainter extends CustomPainter {
_SamplePainter(this.color, this.dash, this.arrow, this.star);
/// 线条颜色。
final Color color;
/// 是否绘制为虚线。
final bool dash;
/// 是否绘制箭头。
final bool arrow;
/// 是否绘制关键路径星标。
final bool star;
/// 绘制示例线段本体、箭头及可选星标。
@override
void paint(Canvas canvas, Size size) {
final Paint p = Paint()
..color = color
..strokeWidth = 2.4
..strokeCap = StrokeCap.round;
final double y = size.height / 2;
if (dash) {
for (double x = 0; x < size.width - 10; x += 8) {
canvas.drawLine(Offset(x, y), Offset(math.min(x + 4, size.width - 10), y), p);
}
} else {
canvas.drawLine(Offset(0, y), Offset(size.width - 10, y), p);
}
if (arrow) {
final Path a = Path()
..moveTo(size.width - 1, y)
..lineTo(size.width - 11, y - 4.5)
..lineTo(size.width - 11, y + 4.5)
..close();
canvas.drawPath(a, Paint()..color = color);
}
if (star) {
canvas.drawCircle(Offset(size.width - 8, y), 7.5, Paint()..color = const Color(0xFF4CC9F0));
final TextPainter tp = TextPainter(
text: const TextSpan(text: '★', style: TextStyle(color: Colors.black, fontSize: 10, fontWeight: FontWeight.w700)),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(size.width - 8 - tp.width / 2, y - tp.height / 2));
}
}
/// 示例线段始终重绘(开销极小)。
@override
bool shouldRepaint(covariant _SamplePainter old) => true;
}
/// 条形视图左下角的「节拍统计」按钮。
///
/// 统计内容改为**弹出窗口**展示(见 [_CycleStatsDialog]),
/// 避免固定面板长期遮挡画布。
class _StatsButton extends StatelessWidget {
const _StatsButton({required this.t, required this.c});
/// 主题令牌。
final Tokens t;
/// 全局应用控制器。
final AppController c;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => showDialog<void>(
context: context,
builder: (BuildContext ctx) => _CycleStatsDialog(t: t, c: c),
),
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
decoration: BoxDecoration(
color: t.panel2.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: t.line2),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(Icons.insights, size: 15, color: t.accent),
const SizedBox(width: 6),
Text('节拍统计', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
],
),
),
);
}
}
/// 节拍统计弹窗:汇总循环周期、动作数、关键路径、并行度、
/// 相位覆盖率、瓶颈工位与预估产能。
class _CycleStatsDialog extends StatelessWidget {
const _CycleStatsDialog({required this.t, required this.c});
/// 主题令牌。
final Tokens t;
/// 全局应用控制器。
final AppController c;
@override
Widget build(BuildContext context) {
final Project p = c.project;
final UnitSettings u = p.units;
final List<Action> acts = p.actions;
final int stations = p.stations.length;
final double perHour = p.cycle.durationMs > 0 ? 3600 / (p.cycle.durationMs / 1000) : 0;
final List<List<String>> stats = <List<String>>[
<String>['循环周期', '${tfmt(p.cycle.durationMs, u)} / 360° / 100%'],
<String>['动作数量', '${acts.length}($stations 工位)'],
<String>['关键路径', _criticalChain()],
<String>['最大并行度', _maxParallel(acts)],
<String>['相位覆盖率', _coverage(acts)],
<String>['瓶颈工位', _bottleneck(p)],
<String>['预估产能', '${perHour.toStringAsFixed(0)} 件/小时(节拍 ${tfmt(p.cycle.durationMs, u)})'],
];
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: SizedBox(
width: 460,
child: Padding(
padding: const EdgeInsets.fromLTRB(18, 16, 12, 14),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.insights, size: 18, color: t.accent),
const SizedBox(width: 8),
Text('节拍统计', style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w700)),
const Spacer(),
IconButton(
onPressed: () => Navigator.pop(context),
icon: Icon(Icons.close, size: 18, color: t.sub),
splashRadius: 16,
),
],
),
Divider(height: 14, color: t.line),
for (int i = 0; i < stats.length; i++) ...<Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: <Widget>[
Text(stats[i][0], style: TextStyle(color: t.dim, fontSize: 11)),
const Spacer(),
Flexible(
child: Text(stats[i][1],
textAlign: TextAlign.right,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.text2, fontSize: 11, fontWeight: FontWeight.w600)),
),
],
),
),
if (i < stats.length - 1) Divider(height: 1, color: t.line.withValues(alpha: 0.6)),
],
],
),
),
),
);
}
/// 拼接关键路径上的动作 id 链。
String _criticalChain() {
final List<String> ids = <String>[];
for (final Action a in c.project.actions) {
if (c.criticalActions.contains(a.id)) ids.add(a.id);
}
if (ids.isEmpty) return '—';
return ids.join(' → ');
}
/// 扫描 0–360°,找出同时执行的动作数量峰值。
String _maxParallel(List<Action> acts) {
int best = 0;
double bestAt = 0;
for (int d = 0; d <= 360; d += 5) {
int n = 0;
for (final Action a in acts) {
if (d >= a.startAngle && d <= math.min(a.endAngle, 360)) n++;
}
if (n > best) {
best = n;
bestAt = d.toDouble();
}
}
return '$best 个动作同时执行(${bestAt.toStringAsFixed(0)}° 附近)';
}
/// 统计 0–360° 被动作覆盖的相位比例。
String _coverage(List<Action> acts) {
final List<bool> cover = List<bool>.filled(360, false);
for (final Action a in acts) {
for (int d = a.startAngle.floor(); d < math.min(a.endAngle, 360).ceil(); d++) {
if (d >= 0 && d < 360) cover[d] = true;
}
}
final int filled = cover.where((bool e) => e).length;
return '${(filled / 360 * 100).toStringAsFixed(0)}%(0°–360°)';
}
/// 找出累计相位占用最大的工位作为瓶颈。
String _bottleneck(Project p) {
final Map<String, double> load = <String, double>{};
for (final Action a in p.actions) {
load[a.stationId] = (load[a.stationId] ?? 0) + a.durationAngle;
}
String best = '—';
double bestV = -1;
for (final MapEntry<String, double> e in load.entries) {
if (e.value > bestV) {
bestV = e.value;
best = '${e.key} ${e.value.toStringAsFixed(0)}°';
}
}
return best;
}
}
/// 条形视图编辑工具条:添加 / 编辑 / 复制 / 删除 / 对齐 / 帮助。
class _EditTools extends StatelessWidget {
const _EditTools({required this.t, required this.c});
/// 主题令牌。
final Tokens t;
/// 全局应用控制器。
final AppController c;
/// 渲染一组横向排列的编辑工具按钮。
@override
Widget build(BuildContext context) {
return _Card(
t: t,
width: 470,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('编辑工具', style: TextStyle(color: t.sub, fontSize: 12, fontWeight: FontWeight.w600)),
const SizedBox(height: 10),
Row(
children: <Widget>[
_tool(t, Icons.add, '添加动作', t.ok, t.onAccent, () => c.addAction(startAngle: 0)),
const SizedBox(width: 8),
_tool(t, Icons.edit, '编辑', t.accent, t.onAccent, () {
final Action? a = c.selected;
if (a != null) showDialog<void>(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a));
}),
const SizedBox(width: 8),
_tool(t, Icons.copy, '复制', t.panel, t.sub, c.duplicateSelected, border: t.line2),
const SizedBox(width: 8),
_tool(t, Icons.delete_outline, '删除', t.panel, t.sub,
() => c.selectedId != null ? c.deleteAction(c.selectedId!) : null,
border: t.line2),
const SizedBox(width: 8),
_tool(t, Icons.align_horizontal_left, '对齐', t.panel, t.sub, c.alignPhase, border: t.line2),
const SizedBox(width: 8),
_tool(t, Icons.help_outline, '帮助', t.panel, t.sub,
() => showDialog<void>(context: context, builder: (_) => const HelpDialog()),
border: t.line2),
],
),
],
),
);
}
/// 渲染单个带图标与文字的工具按钮。
Widget _tool(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(9),
child: Container(
width: 66,
height: 56,
decoration: BoxDecoration(
color: bg,
borderRadius: BorderRadius.circular(9),
border: Border.all(color: border ?? bg),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(icon, size: 19, color: fg),
const SizedBox(height: 4),
Text(label, style: TextStyle(color: fg, fontSize: 10, fontWeight: FontWeight.w600)),
],
),
),
);
}
}
/// 圆周视图右侧浮动工具栏:纵向排列的编辑与帮助按钮。
class _FloatingToolbar extends StatelessWidget {
const _FloatingToolbar({required this.t, required this.c});
/// 主题令牌。
final Tokens t;
/// 全局应用控制器。
final AppController c;
/// 渲染纵向排列的浮动工具按钮组。
@override
Widget build(BuildContext context) {
/// 渲染单个浮动工具按钮。
Widget item(IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(10),
child: Container(
width: 46,
height: 46,
decoration: BoxDecoration(
color: bg,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: border ?? bg),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(icon, size: 17, color: fg),
const SizedBox(height: 1),
Text(label, style: TextStyle(color: fg, fontSize: 10, fontWeight: FontWeight.w600)),
],
),
),
),
);
}
return Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: t.panel.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: t.line2),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
item(Icons.add, '添加', t.ok, t.onAccent, () => c.addAction(startAngle: 0)),
item(Icons.edit, '编辑', t.accent, t.onAccent, () {
final Action? a = c.selected;
if (a != null) showDialog<void>(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a));
}),
item(Icons.copy, '复制', t.panel2, t.sub, c.duplicateSelected, border: t.line),
item(Icons.delete_outline, '删除', t.panel2, t.sub,
() => c.selectedId != null ? c.deleteAction(c.selectedId!) : null, border: t.line),
item(Icons.keyboard_arrow_up, '层+', t.panel2, t.sub,
() => c.selectedId != null ? c.changeLayer(c.selectedId!, 1) : null, border: t.line),
item(Icons.keyboard_arrow_down, '层−', t.panel2, t.sub,
() => c.selectedId != null ? c.changeLayer(c.selectedId!, -1) : null, border: t.line),
item(Icons.align_horizontal_left, '对齐', t.panel2, t.sub, c.alignPhase, border: t.line),
item(Icons.help_outline, '帮助', t.panel2, t.sub,
() => showDialog<void>(context: context, builder: (_) => const HelpDialog()), border: t.line),
],
),
);
}
}
/// 条形节拍缩略预览卡(在圆周视图右下角显示)。
class _BarPreviewCard extends StatelessWidget {
const _BarPreviewCard({required this.t, required this.project});
/// 主题令牌。
final Tokens t;
/// 当前项目。
final Project project;
/// 渲染条形缩略预览。
@override
Widget build(BuildContext context) {
return _Card(
t: t,
width: 320,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('条形节拍预览(实时联动)', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
const SizedBox(height: 10),
SizedBox(
height: project.actions.length * 22.0 + 18,
child: CustomPaint(painter: _MiniBarPainter(project, t)),
),
],
),
);
}
}
/// 条形缩略预览绘制器:按相位比例绘制各动作的横向色条。
class _MiniBarPainter extends CustomPainter {
_MiniBarPainter(this.project, this.t);
/// 当前项目。
final Project project;
/// 主题令牌。
final Tokens t;
/// 逐行绘制动作色条、跨圈尾段与底部刻度。
@override
void paint(Canvas canvas, Size size) {
final double w = size.width - 4;
final double rh = 19;
for (int i = 0; i < project.actions.length; i++) {
final Action a = project.actions[i];
final double y = i * (rh + 3);
final double x1 = 2 + a.startAngle / 360 * w;
final double x2 = 2 + math.min(a.endAngle, 360) / 360 * w;
final RRect r = RRect.fromRectAndRadius(
Rect.fromLTWH(x1, y, math.max(x2 - x1, 2), rh - 4),
const Radius.circular(3),
);
canvas.drawRRect(r, Paint()..color = Color(a.color).withValues(alpha: 0.9));
if (a.wrap) {
canvas.drawRRect(
RRect.fromRectAndRadius(Rect.fromLTWH(2, y, (a.endAngle - 360) / 360 * w, rh - 4), const Radius.circular(3)),
Paint()..color = Color(a.color).withValues(alpha: t.tailOp),
);
}
}
final double baseY = project.actions.length * (rh + 3) + 4;
canvas.drawLine(Offset(2, baseY), Offset(size.width - 2, baseY), Paint()..color = t.line2..strokeWidth = 1);
final TextPainter tp = TextPainter(
text: TextSpan(text: '0.0 ${timeUnitLabel(project.units.timeUnit)}', style: TextStyle(color: t.dim, fontSize: 10)),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(2, baseY + 4));
final TextPainter tp2 = TextPainter(
text: TextSpan(text: tfmt(project.cycle.durationMs, project.units), style: TextStyle(color: t.dim, fontSize: 10)),
textDirection: TextDirection.ltr,
)..layout();
tp2.paint(canvas, Offset(size.width - 2 - tp2.width, baseY + 4));
}
/// 预览始终重绘(数据实时联动)。
@override
bool shouldRepaint(covariant _MiniBarPainter old) => true;
}
/// 圆周节拍缩略预览卡(在条形视图右下角显示)。
class _CircularPreviewCard extends StatelessWidget {
const _CircularPreviewCard({required this.t, required this.project});
/// 主题令牌。
final Tokens t;
/// 当前项目。
final Project project;
/// 渲染圆周缩略预览。
@override
Widget build(BuildContext context) {
return _Card(
t: t,
width: 330,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('圆周节拍预览(实时联动)', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
SizedBox(
height: 250,
child: CustomPaint(painter: _MiniCircularPainter(project, t)),
),
Text('12 点钟起始 · 顺时针 · 每层一环', style: TextStyle(color: t.dim, fontSize: 10)),
],
),
);
}
}
/// 圆周缩略预览绘制器:每层一环,绘制同心圆与动作圆弧。
class _MiniCircularPainter extends CustomPainter {
_MiniCircularPainter(this.project, this.t);
/// 当前项目。
final Project project;
/// 主题令牌。
final Tokens t;
/// 绘制同心圆环、各动作圆弧、12 点钟箭头与“360°”标注。
@override
void paint(Canvas canvas, Size size) {
final Offset c = Offset(size.width / 2, size.height / 2);
final int n = project.actions.length;
final double r0 = 26;
final double pitch = n <= 1 ? 18 : math.min(20, (size.height / 2 - 30 - r0) / (n - 1));
const double pw = 9;
canvas.drawCircle(c, r0 + (n - 1) * pitch + pw + 12, Paint()..color = t.dial);
for (int i = 0; i < n; i++) {
final Action a = project.actions[i];
final double r = r0 + i * pitch;
canvas.drawCircle(
c,
r,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = pw
..color = i.isEven ? t.ringA : t.ringB,
);
for (final List<double> s in splitArcs(a.startAngle, a.endAngle)) {
canvas.drawPath(
arcPath(c, r, s[0], s[1]),
Paint()
..style = PaintingStyle.stroke
..strokeWidth = pw
..strokeCap = a.wrap ? StrokeCap.butt : StrokeCap.round
..color = Color(a.color).withValues(alpha: 0.95),
);
}
}
final double tip = r0 + (n - 1) * pitch + pw + 12;
final Path arrow = Path()
..moveTo(c.dx, c.dy - tip - 10)
..lineTo(c.dx - 7, c.dy - tip - 22)
..lineTo(c.dx + 7, c.dy - tip - 22)
..close();
canvas.drawPath(arrow, Paint()..color = t.accent);
final TextPainter tp = TextPainter(
text: TextSpan(text: '360°', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(c.dx - tp.width / 2, c.dy - 8));
}
/// 预览始终重绘(数据实时联动)。
@override
bool shouldRepaint(covariant _MiniCircularPainter old) => true;
}
+569
View File
@@ -0,0 +1,569 @@
// 画布交互视图:承载条形 / 圆周两种节拍视图的绘制与全部手势操作。
//
// 架构位置:位于 UI 层核心,向下调用布局(BarLayout / CircularLayout)
// 与渲染器(BarPainter / CircularPainter),向上通过 AppController 修改
// 项目状态。本文件负责:
// · 屏幕坐标 → 逻辑坐标的变换(考虑平移与缩放);
// · 点选、双击新建、拖拽移动相位、拖拽端点改持续角、Shift 拖拽改层;
// · 空白区域拖拽平移、Ctrl + 滚轮缩放;
// · 右键上下文菜单。
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;
/// 控制器快捷访问器。
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);
}
/// 动作端点弱吸附:贴合到整 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) 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);
}
/// 拖拽开始:判断落点是否命中动作。
/// 条形视图下靠近动作右端 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);
_mode = _DragMode.move;
_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 (shift) {
// Shift + 垂直拖拽:按每 26px 一层调整层号,并限制在 0–63。
final int deltaLayer = (dy / 26).round();
c.setLayer(_dragAction!.id, (_dragAction!.layer - deltaLayer).clamp(0, 63));
} else if (dy.abs() > dx.abs() + 6 && dy.abs() > 12) {
// 以垂直为主:上下拖拽调整行序,动作可自由换行(不再被相位锁死)。
final int target = ((p.dy - BarLayout.topPad) / layout.pitch).round().clamp(0, layout.ordered.length - 1);
c.moveActionRow(_dragAction!.id, target);
} 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) {
c.setActionDuration(_dragAction!.id, _startDuration + delta);
} else if (shift) {
// Shift + 径向拖拽:按层间距 pitch 换算层号增量。
final double dr = (p - layout.center).distance - (_startPointer - layout.center).distance;
final int dl = (dr / layout.pitch).round();
c.setLayer(_dragAction!.id, (_dragAction!.layer + dl).clamp(0, 63));
} else {
c.setActionStart(_dragAction!.id, _startAngle + delta);
}
}
}
/// 拖拽结束:重置拖拽会话状态。
void _onPanEnd(DragEndDetails d) {
_mode = _DragMode.none;
_dragAction = null;
_zoneIndex = -1;
_zoneGuideAngle = null;
}
/// 滚轮:按住 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,
)
: CircularPainter(
project: c.project,
tokens: t,
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
selectedIds: c.selectedIds.toSet(),
),
),
),
),
),
),
);
},
);
}
}
+1355
View File
File diff suppressed because it is too large Load Diff