v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复
- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json - 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档 - 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸 - 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名 - 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
This commit is contained in:
@@ -0,0 +1,470 @@
|
||||
/// DeepSeek 大模型客户端:把自然语言描述转换为可加载的 [Project]。
|
||||
///
|
||||
/// 架构位置:独立于 UI 与状态层的纯服务模块,仅依赖 `dart:io`(HttpClient)
|
||||
/// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [AiResult] 后交给
|
||||
/// [AppController.loadProject] 载入。
|
||||
///
|
||||
/// 能力:
|
||||
/// - **流式接收**:SSE 增量解析,实时报告「思考 / 输出」字符数;
|
||||
/// - **可取消**:通过 [AiCancelToken] 立即中断 HTTP 请求;
|
||||
/// - **超时保护**:空闲超过 `idleTimeout` 自动失败并给出可读提示;
|
||||
/// - **增量修改**:传入基准 [Project],让模型在现有工程上增删改而非整图重画;
|
||||
/// - **自动纠错**:输出无法解析为时序图时,把错误反馈给模型自动修复重试;
|
||||
/// - **结果清洗**:修正非法时长 / 越界角度,剔除指向不存在动作的依赖,归一化层号。
|
||||
///
|
||||
/// 约束:不引入任何原生插件或第三方 HTTP 包,全部使用 `dart:io` 实现。
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
|
||||
/// AI 请求参数。
|
||||
class AiSettings {
|
||||
/// 构造参数。
|
||||
const AiSettings({
|
||||
required this.apiKey,
|
||||
required this.model,
|
||||
required this.effort,
|
||||
});
|
||||
|
||||
/// DeepSeek API Key(仅驻留内存,不写入工程文件)。
|
||||
final String apiKey;
|
||||
|
||||
/// 模型 id,例如 `deepseek-chat`(Flash)或 `deepseek-reasoner`(Pro)。
|
||||
final String model;
|
||||
|
||||
/// 推理强度:`high` / `max`。
|
||||
final String effort;
|
||||
}
|
||||
|
||||
/// 可选的模型项(id + 展示名)。
|
||||
class AiModelOption {
|
||||
/// 构造。
|
||||
const AiModelOption(this.id, this.label);
|
||||
|
||||
/// 接口使用的模型 id。
|
||||
final String id;
|
||||
|
||||
/// 界面展示名称。
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// 预设模型列表:Flash(快速)与 Pro(深度推理)。
|
||||
///
|
||||
/// 模型 id 必须与 DeepSeek 当前 API 保持一致(`deepseek-flash` /
|
||||
/// `deepseek-v4-pro`);旧 id(`deepseek-chat` / `deepseek-reasoner`)
|
||||
/// 已下线,继续使用会直接返回 400 Model Not Exist。
|
||||
const List<AiModelOption> kAiModels = <AiModelOption>[
|
||||
AiModelOption('deepseek-flash', 'Flash · 快速'),
|
||||
AiModelOption('deepseek-v4-pro', 'Pro · 深度推理'),
|
||||
];
|
||||
|
||||
/// AI 调用异常(携带可读信息,便于界面直接展示)。
|
||||
class AiException implements Exception {
|
||||
/// 构造。
|
||||
AiException(this.message);
|
||||
|
||||
/// 错误信息。
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 流式生成进度:分别统计「思考」与「输出」已接收的字符数。
|
||||
class AiProgress {
|
||||
/// 构造。
|
||||
const AiProgress({
|
||||
required this.reasoningChars,
|
||||
required this.contentChars,
|
||||
required this.attempt,
|
||||
});
|
||||
|
||||
/// 已接收的思考(reasoning_content)字符数;非推理模型恒为 0。
|
||||
final int reasoningChars;
|
||||
|
||||
/// 已接收的正式输出(content)字符数。
|
||||
final int contentChars;
|
||||
|
||||
/// 第几次尝试(0 起;大于 0 表示正在自动修复上一次的输出)。
|
||||
final int attempt;
|
||||
}
|
||||
|
||||
/// 取消令牌:界面点击「取消生成」时置位,并触发底层 HTTP 中断。
|
||||
class AiCancelToken {
|
||||
bool _cancelled = false;
|
||||
void Function()? _abort;
|
||||
|
||||
/// 是否已被取消。
|
||||
bool get cancelled => _cancelled;
|
||||
|
||||
/// 绑定底层中断动作(关闭 HTTP 客户端 / socket)。
|
||||
void bindAbort(void Function() abort) => _abort = abort;
|
||||
|
||||
/// 请求取消:先置位再触发中断,保证两侧都能观察到。
|
||||
void cancel() {
|
||||
_cancelled = true;
|
||||
_abort?.call();
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成结果:清洗后的项目 + 自动修正说明(用于状态栏提示)。
|
||||
class AiResult {
|
||||
/// 构造。
|
||||
const AiResult(this.project, this.warnings);
|
||||
|
||||
/// 解析并清洗后的项目。
|
||||
final Project project;
|
||||
|
||||
/// 自动修正项说明;无修正时为空列表。
|
||||
final List<String> warnings;
|
||||
}
|
||||
|
||||
/// DeepSeek 客户端。
|
||||
class AiClient {
|
||||
AiClient._();
|
||||
|
||||
/// DeepSeek 兼容 OpenAI 的对话补全端点。
|
||||
static const String endpoint = 'https://api.deepseek.com/chat/completions';
|
||||
|
||||
/// 要求模型输出的系统提示词:严格描述 `seqdiagram/1.2` JSON 结构。
|
||||
static const String _systemPrompt = '''
|
||||
你是工业节拍 / 相位角设计助手。请把用户的自然语言描述转换成严格的 JSON,且**只能输出 JSON**,不要输出解释、注释或 Markdown 代码块。
|
||||
|
||||
JSON 结构(协议 edc/1.3):
|
||||
{
|
||||
"schema": "edc/1.3",
|
||||
"project": {
|
||||
"name": "项目名称",
|
||||
"units": { "timeUnit": "s", "phaseUnit": "deg", "precision": -1, "snapAngle": 1, "snapTime": 0.1, "cycleInputPolicy": "keepAngle" },
|
||||
"cycle": { "durationMs": 2400, "startAngle": 0, "direction": "cw", "origin": "twelve", "snapDeg": 1 },
|
||||
"stations": [ { "id": "ST1", "name": "工位1", "order": 0, "color": "#4cc9f0" } ],
|
||||
"actions": [
|
||||
{ "id": "A1", "name": "动作1", "stationId": "ST1", "driver": "气缸 Y1",
|
||||
"startAngle": 0, "durationAngle": 60, "layer": 0, "color": "#4cc9f0", "deps": [] }
|
||||
],
|
||||
"viewState": { "mode": "bar", "zoom": 1, "pan": [0, 0],
|
||||
"showDeps": true, "showRuler": true, "showPhaseBands": true, "showRingBg": true, "showLayerLabels": true },
|
||||
"phaseZones": [ { "name": "上料相位", "startAngle": 0, "endAngle": 70 } ]
|
||||
}
|
||||
}
|
||||
|
||||
规则:
|
||||
1. 时间只存于 cycle.durationMs(毫秒);角度为 0–360 度,0° 为 12 点钟方向、顺时针递增。
|
||||
2. 每个动作 durationAngle > 0;startAngle + durationAngle 可以超过 360 表示跨循环。
|
||||
3. layer 表示**并行执行资源**(执行器 / 工位轨道),从 0 开始连续编号:
|
||||
同一时间段内并行执行的动作必须处于不同 layer;前后串行、时间不重叠的动作
|
||||
应尽量复用同一 layer,避免层数过多(一般不超过 6 层)。
|
||||
4. deps 为前置依赖数组,元素形如 { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 };
|
||||
type 取 FS(完成-启动)/ SS(起始-起始)/ FF / SF。
|
||||
一个动作可以有多条 deps(多输入),也可以被多个动作引用(多输出);
|
||||
fromId / toId 必须引用 actions 中真实存在的动作 id,且不能指向自身。
|
||||
5. 颜色从调色板循环取用:#4cc9f0, #7bd88f, #ffd166, #ff8a5c, #f472b6, #a78bfa, #38bdf8, #34d399。
|
||||
6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。
|
||||
7. 动作命名简洁(不超过 8 个汉字);不要编造不存在的工位,stationId 必须引用 stations 中已有的 id。
|
||||
8. 只输出 JSON 本体,且必须是单个可直接 JSON 解析的对象。
|
||||
9. 只需要输出时序图数据(name / units / cycle / stations / actions / viewState / phaseZones),
|
||||
不需要也没有 `arch`、`keepEmptyLanes`、`laneSlots` 等字段;修改模式由程序负责保留原有架构图数据。
|
||||
''';
|
||||
|
||||
/// 根据自然语言 [prompt] 生成或修改项目(流式、可取消、带自动纠错)。
|
||||
///
|
||||
/// - [base] 非空时进入「增量修改」模式:连同现有工程一起发送,
|
||||
/// 要求模型输出修改后的完整 JSON(未涉及部分保持原样);
|
||||
/// - [onProgress]:每收到一段增量内容回调一次(含思考 / 输出字符数与尝试次数);
|
||||
/// - [cancelToken]:取消后立即中断请求并抛出「已取消」;
|
||||
/// - 空闲超过 [idleTimeout] 无任何数据视为超时;
|
||||
/// - 输出无法解析 / 校验失败时,把错误反馈给模型自动修复重试(最多 [maxRepairs] 次);
|
||||
/// - 成功后返回 [AiResult](含结果清洗说明)。
|
||||
static Future<AiResult> generate({
|
||||
required String prompt,
|
||||
required AiSettings settings,
|
||||
Project? base,
|
||||
void Function(AiProgress progress)? onProgress,
|
||||
AiCancelToken? cancelToken,
|
||||
Duration idleTimeout = const Duration(seconds: 180),
|
||||
int maxRepairs = 2,
|
||||
}) async {
|
||||
if (settings.apiKey.trim().isEmpty) {
|
||||
throw AiException('请先填写 DeepSeek API Key');
|
||||
}
|
||||
if (prompt.trim().isEmpty) {
|
||||
throw AiException('请输入自然语言描述');
|
||||
}
|
||||
|
||||
// 修改模式只发送时序部分:架构图 / 画布设置(arch、泳道、自动保存)
|
||||
// 体积大且与本次修改无关,不回传给模型,也能避免模型丢掉原有架构图。
|
||||
final String baseJson = base == null ? '' : jsonEncode(base.toJson(includeArch: false));
|
||||
final String firstUser = base == null
|
||||
? prompt.trim()
|
||||
: '现有工程 JSON:\n$baseJson\n\n'
|
||||
'修改要求:${prompt.trim()}\n\n'
|
||||
'请在现有工程基础上按要求修改(增删改动作 / 相位 / 依赖等),'
|
||||
'未涉及的部分保持原样,输出修改后的**完整** JSON。';
|
||||
|
||||
String? previousOutput;
|
||||
String lastError = '';
|
||||
for (int attempt = 0; attempt <= maxRepairs; attempt++) {
|
||||
if (cancelToken?.cancelled ?? false) throw AiException('已取消');
|
||||
final List<Map<String, String>> messages = <Map<String, String>>[
|
||||
<String, String>{'role': 'system', 'content': _systemPrompt},
|
||||
<String, String>{'role': 'user', 'content': firstUser},
|
||||
];
|
||||
if (attempt > 0) {
|
||||
String prev = previousOutput ?? '';
|
||||
if (prev.length > 8000) prev = prev.substring(prev.length - 8000);
|
||||
messages.add(<String, String>{'role': 'assistant', 'content': prev});
|
||||
messages.add(<String, String>{
|
||||
'role': 'user',
|
||||
'content': '你上次的输出无法解析为合法的时序图:$lastError\n'
|
||||
'请修正后只输出完整的 JSON 本体(不要解释、不要 Markdown 代码块)。',
|
||||
});
|
||||
}
|
||||
try {
|
||||
final String content = await _streamOnce(
|
||||
messages: messages,
|
||||
settings: settings,
|
||||
attempt: attempt,
|
||||
onProgress: onProgress,
|
||||
cancelToken: cancelToken,
|
||||
idleTimeout: idleTimeout,
|
||||
);
|
||||
previousOutput = content;
|
||||
final Map<String, dynamic> decoded =
|
||||
jsonDecode(_extractJson(content)) as Map<String, dynamic>;
|
||||
final Project project = Project.fromJson(decoded);
|
||||
final (Project fixed, List<String> warnings) = _sanitize(project);
|
||||
if (fixed.actions.isEmpty) {
|
||||
throw const FormatException('没有任何动作');
|
||||
}
|
||||
// 修改模式:只采纳 AI 返回的时序内容,架构图 / 画布设置 / 泳道设置
|
||||
// 一律沿用原工程,避免一次 AI 修改把架构图或用户视图状态清空。
|
||||
final Project result = base == null
|
||||
? fixed
|
||||
: base.copyWith(
|
||||
name: fixed.name,
|
||||
schema: fixed.schema,
|
||||
cycle: fixed.cycle,
|
||||
stations: fixed.stations,
|
||||
actions: fixed.actions,
|
||||
units: fixed.units,
|
||||
phaseZones: fixed.phaseZones,
|
||||
);
|
||||
return AiResult(result, warnings);
|
||||
} on AiException {
|
||||
rethrow; // 网络 / 鉴权 / 超时 / 取消等错误不重试
|
||||
} on FormatException catch (e) {
|
||||
lastError = e.message;
|
||||
if (attempt >= maxRepairs) {
|
||||
throw AiException('模型输出无法解析为时序图:${e.message}');
|
||||
}
|
||||
} catch (e) {
|
||||
lastError = '$e';
|
||||
if (attempt >= maxRepairs) {
|
||||
throw AiException('模型输出无法解析为时序图:$e');
|
||||
}
|
||||
}
|
||||
}
|
||||
throw AiException('生成失败:$lastError');
|
||||
}
|
||||
|
||||
/// 单次流式请求:返回模型输出的完整文本内容(不含思考内容)。
|
||||
static Future<String> _streamOnce({
|
||||
required List<Map<String, String>> messages,
|
||||
required AiSettings settings,
|
||||
required int attempt,
|
||||
void Function(AiProgress progress)? onProgress,
|
||||
AiCancelToken? cancelToken,
|
||||
required Duration idleTimeout,
|
||||
}) async {
|
||||
final HttpClient client = HttpClient()..connectionTimeout = const Duration(seconds: 20);
|
||||
cancelToken?.bindAbort(() => client.close(force: true));
|
||||
try {
|
||||
final HttpClientRequest req = await client.postUrl(Uri.parse(endpoint));
|
||||
req.headers.set(HttpHeaders.contentTypeHeader, 'application/json');
|
||||
req.headers.set(HttpHeaders.authorizationHeader, 'Bearer ${settings.apiKey.trim()}');
|
||||
req.write(jsonEncode(<String, dynamic>{
|
||||
'model': settings.model,
|
||||
'messages': messages,
|
||||
'stream': true,
|
||||
'temperature': 0.2,
|
||||
'max_tokens': 131072,
|
||||
'response_format': <String, String>{'type': 'json_object'},
|
||||
// 当前 DeepSeek 模型默认开启思考,这里显式开启并按 UI 选择传推理强度。
|
||||
'thinking': <String, String>{'type': 'enabled'},
|
||||
'reasoning_effort': settings.effort,
|
||||
}));
|
||||
final HttpClientResponse res = await req.close();
|
||||
if (res.statusCode != 200) {
|
||||
final String text = await res.transform(utf8.decoder).join();
|
||||
throw AiException(_apiError(res.statusCode, text));
|
||||
}
|
||||
final StringBuffer content = StringBuffer();
|
||||
final StringBuffer reasoning = StringBuffer();
|
||||
final Stream<String> lines =
|
||||
res.transform(utf8.decoder).transform(const LineSplitter()).timeout(idleTimeout);
|
||||
await for (final String line in lines) {
|
||||
if (cancelToken?.cancelled ?? false) throw AiException('已取消');
|
||||
if (!line.startsWith('data:')) continue;
|
||||
final String payload = line.substring(5).trim();
|
||||
if (payload.isEmpty) continue;
|
||||
if (payload == '[DONE]') break;
|
||||
Map<String, dynamic> chunk;
|
||||
try {
|
||||
chunk = jsonDecode(payload) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
continue; // 忽略无法解析的心跳 / 异常行
|
||||
}
|
||||
final List<dynamic> choices = (chunk['choices'] as List<dynamic>?) ?? const <dynamic>[];
|
||||
if (choices.isEmpty) continue;
|
||||
final Map<String, dynamic> delta =
|
||||
((choices.first as Map<String, dynamic>)['delta'] as Map<String, dynamic>?) ??
|
||||
const <String, dynamic>{};
|
||||
final String piece = (delta['content'] as String?) ?? '';
|
||||
final String think = (delta['reasoning_content'] as String?) ?? '';
|
||||
if (piece.isNotEmpty) content.write(piece);
|
||||
if (think.isNotEmpty) reasoning.write(think);
|
||||
if (piece.isNotEmpty || think.isNotEmpty) {
|
||||
onProgress?.call(AiProgress(
|
||||
reasoningChars: reasoning.length,
|
||||
contentChars: content.length,
|
||||
attempt: attempt,
|
||||
));
|
||||
}
|
||||
}
|
||||
if (cancelToken?.cancelled ?? false) throw AiException('已取消');
|
||||
if (content.toString().trim().isEmpty) throw AiException('模型返回为空');
|
||||
return content.toString();
|
||||
} on AiException {
|
||||
rethrow;
|
||||
} on TimeoutException {
|
||||
throw AiException('响应超时(${idleTimeout.inSeconds} 秒无数据),请检查网络后重试');
|
||||
} on SocketException catch (e) {
|
||||
if (cancelToken?.cancelled ?? false) throw AiException('已取消');
|
||||
throw AiException('网络连接失败:${e.message}');
|
||||
} on HttpException catch (e) {
|
||||
if (cancelToken?.cancelled ?? false) throw AiException('已取消');
|
||||
throw AiException('HTTP 错误:${e.message}');
|
||||
} on FormatException catch (e) {
|
||||
throw AiException('响应格式错误:${e.message}');
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 结果清洗:补齐工位、修正非法时长与越界角度、剔除指向不存在动作的
|
||||
/// 依赖、归一化层号。
|
||||
///
|
||||
/// 返回修正后的项目与人类可读的修正说明(供状态栏提示)。
|
||||
static (Project, List<String>) _sanitize(Project p) {
|
||||
// 工位是动作的归属单元:模型偶发漏写 stations 或编造 stationId 时,
|
||||
// 直接引用会让条形视图整组动作消失,这里兜底并提示。
|
||||
final List<Station> stations = p.stations.isEmpty
|
||||
? const <Station>[
|
||||
Station(id: 'ST1', name: '工位1', order: 0, color: 0xFF4CC9F0),
|
||||
]
|
||||
: p.stations;
|
||||
final Set<String> stationIds = <String>{for (final Station s in stations) s.id};
|
||||
final String fallbackStation = stations.first.id;
|
||||
int fixedStation = 0;
|
||||
final Set<String> ids = <String>{for (final Action a in p.actions) a.id};
|
||||
int fixedDur = 0;
|
||||
int droppedDeps = 0;
|
||||
final List<Action> actions = <Action>[];
|
||||
for (final Action a in p.actions) {
|
||||
double start = a.startAngle;
|
||||
double dur = a.durationAngle;
|
||||
if (!start.isFinite || start < 0) start = 0;
|
||||
if (start > 400) start = 400;
|
||||
if (!dur.isFinite) dur = 0;
|
||||
if (dur <= 0) {
|
||||
dur = 5;
|
||||
fixedDur++;
|
||||
} else if (dur > 720) {
|
||||
dur = 720;
|
||||
fixedDur++;
|
||||
}
|
||||
String stationId = a.stationId;
|
||||
if (!stationIds.contains(stationId)) {
|
||||
stationId = fallbackStation;
|
||||
fixedStation++;
|
||||
}
|
||||
final List<Dependency> deps = <Dependency>[];
|
||||
for (final Dependency d in a.deps) {
|
||||
if (d.fromId == a.id || !ids.contains(d.fromId) || !ids.contains(d.toId)) {
|
||||
droppedDeps++;
|
||||
continue;
|
||||
}
|
||||
deps.add(d);
|
||||
}
|
||||
actions.add(a.copyWith(
|
||||
stationId: stationId,
|
||||
startAngle: start,
|
||||
durationAngle: dur,
|
||||
deps: deps,
|
||||
));
|
||||
}
|
||||
// 层号归一化为连续的 0..N-1(保持相对顺序),避免稀疏层号造成空白轨道。
|
||||
final List<int> layers = <int>{for (final Action a in actions) a.layer}.toList()..sort();
|
||||
final Map<int, int> remap = <int, int>{
|
||||
for (int i = 0; i < layers.length; i++) layers[i]: i,
|
||||
};
|
||||
final List<Action> normalized = <Action>[
|
||||
for (final Action a in actions) a.copyWith(layer: remap[a.layer] ?? 0),
|
||||
];
|
||||
final List<String> warnings = <String>[];
|
||||
if (fixedDur > 0) warnings.add('修正 $fixedDur 处非法时长');
|
||||
if (fixedStation > 0) warnings.add('修正 $fixedStation 处无效工位');
|
||||
if (droppedDeps > 0) warnings.add('剔除 $droppedDeps 条无效依赖');
|
||||
return (p.copyWith(stations: stations, actions: normalized), warnings);
|
||||
}
|
||||
|
||||
/// 把非 200 响应转换为可读错误:优先取 DeepSeek 的 `error.message`,
|
||||
/// 并对常见状态码给出排查提示(模型下线 / Key 无效 / 余额不足)。
|
||||
static String _apiError(int code, String raw) {
|
||||
String detail = _brief(raw);
|
||||
try {
|
||||
final Object? j = jsonDecode(raw);
|
||||
if (j is Map<String, dynamic>) {
|
||||
final Object? err = j['error'];
|
||||
if (err is Map<String, dynamic> && err['message'] is String) {
|
||||
detail = _brief(err['message'] as String);
|
||||
} else if (j['message'] is String) {
|
||||
detail = _brief(j['message'] as String);
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
switch (code) {
|
||||
case 401:
|
||||
return 'API Key 无效或已过期(401):$detail';
|
||||
case 402:
|
||||
return 'DeepSeek 账户余额不足(402):$detail';
|
||||
case 429:
|
||||
return '请求过于频繁(429):$detail';
|
||||
default:
|
||||
return '接口返回 $code:$detail';
|
||||
}
|
||||
}
|
||||
|
||||
/// 从模型输出中剥离 Markdown 代码围栏并截取首个 JSON 对象。
|
||||
static String _extractJson(String raw) {
|
||||
String t = raw.trim();
|
||||
if (t.startsWith('```')) {
|
||||
t = t.replaceFirst(RegExp(r'^```[a-zA-Z]*\s*'), '');
|
||||
t = t.replaceFirst(RegExp(r'```\s*$'), '');
|
||||
}
|
||||
final int i = t.indexOf('{');
|
||||
final int j = t.lastIndexOf('}');
|
||||
if (i >= 0 && j > i) t = t.substring(i, j + 1);
|
||||
return t.trim();
|
||||
}
|
||||
|
||||
/// 截断过长的错误信息,避免弹窗过大。
|
||||
static String _brief(String s) {
|
||||
final String one = s.replaceAll(RegExp(r'\s+'), ' ').trim();
|
||||
return one.length > 200 ? '${one.substring(0, 200)}…' : one;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/// drawio 导出写入器:把流程图序列化为 diagrams.net(draw.io)可编辑的 `.drawio` 文件。
|
||||
///
|
||||
/// 架构位置:
|
||||
/// - 仅流程图视图支持(条形 / 圆周视图只有 SVG / PNG 两种导出);
|
||||
/// - 几何完全复用 [FlowLayout](与屏幕画布、SVG 导出同一套坐标与走线),
|
||||
/// 保证三种载体(画布 / drawio / SVG)内容一致;
|
||||
/// - 输出标准 `<mxfile>` 文档:节点保留动作颜色与「时长 · 工位」语义,
|
||||
/// 连线保留 FS / SS 类型与偏移时间标签,泳道为背景带、相位为竖排文字带,
|
||||
/// 导入 draw.io 后可直接继续排布与编辑。
|
||||
///
|
||||
/// 输出约定:
|
||||
/// - 坐标与原画布 1:1(不缩放),原点同样在左上角;
|
||||
/// - 页面尺寸按内容范围自动设置,四边各留 [_pad] 留白,整体平移到页内;
|
||||
/// - 不写入时间戳等易变字段,保证同一工程多次导出结果稳定(便于测试与归档)。
|
||||
library;
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'export_fit.dart';
|
||||
|
||||
/// drawio 文档写入器。
|
||||
///
|
||||
/// 通过内部 [StringBuffer] 逐段拼接 XML,最终由 [build] 返回完整文档。
|
||||
class DrawioWriter {
|
||||
/// 创建写入器。
|
||||
///
|
||||
/// 参数:
|
||||
/// - [project]:数据源(动作、依赖、相位分区、单位);
|
||||
/// - [tokens]:配色令牌(内部转为导出专用纯白主题,与 SVG / PNG 一致)。
|
||||
///
|
||||
/// 构造时不生成任何内容;调用 [build] 才写出文档。
|
||||
DrawioWriter({required this.project, required Tokens tokens})
|
||||
: tokens = exportTokens(tokens);
|
||||
|
||||
/// 数据源工程。
|
||||
final Project project;
|
||||
/// 导出专用配色令牌。
|
||||
final Tokens tokens;
|
||||
|
||||
/// 页内留白(四周各留的空白,逻辑像素)。
|
||||
static const double _pad = 40;
|
||||
|
||||
/// 输出缓冲区,累积 XML 文本片段。
|
||||
final StringBuffer _b = StringBuffer();
|
||||
|
||||
/// 生成完整 drawio 文档字符串。
|
||||
///
|
||||
/// 返回:以 `<mxfile>` 开头、`</mxfile>` 结尾的字符串。
|
||||
/// 副作用:会持续向内部缓冲区追加内容;约定每次导出新建实例。
|
||||
String build() {
|
||||
final FlowLayout layout = FlowLayout(project);
|
||||
if (layout.nodes.isEmpty) {
|
||||
return '<mxfile host="app.diagrams.net"><diagram id="flow" name="流程图">'
|
||||
'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root>'
|
||||
'</mxGraphModel></diagram></mxfile>';
|
||||
}
|
||||
// 平移到页内:原点统一挪到 (pad, pad),页面尺寸随内容自适应。
|
||||
final double ox = _pad - layout.bounds.left;
|
||||
final double oy = _pad - layout.bounds.top;
|
||||
final int pageW = (layout.bounds.width + _pad * 2).ceil();
|
||||
final int pageH = (layout.bounds.height + _pad * 2).ceil();
|
||||
|
||||
_b.write('<mxfile host="app.diagrams.net" agent="Sequence Diagram Studio" '
|
||||
'version="24.7.8" type="device">');
|
||||
_b.write('<diagram id="flow" name="${_esc(project.name.isEmpty ? '流程图' : project.name)}">');
|
||||
_b.write('<mxGraphModel dx="1600" dy="900" grid="1" gridSize="10" guides="1" '
|
||||
'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '
|
||||
'pageWidth="$pageW" pageHeight="$pageH" math="0" shadow="0">');
|
||||
_b.write('<root>');
|
||||
_b.write('<mxCell id="0"/>');
|
||||
_b.write('<mxCell id="1" parent="0"/>');
|
||||
|
||||
_lanes(layout, ox, oy);
|
||||
_phases(layout, ox, oy);
|
||||
_edges(layout);
|
||||
_nodes(layout, ox, oy);
|
||||
|
||||
_b.write('</root></mxGraphModel></diagram></mxfile>');
|
||||
return _b.toString();
|
||||
}
|
||||
|
||||
/// 写入泳道背景带与轨道标题(原样平移)。
|
||||
void _lanes(FlowLayout layout, double ox, double oy) {
|
||||
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
|
||||
final double top = layout.bounds.top + 20 + oy;
|
||||
final double bottom = layout.bounds.bottom - 20 + oy;
|
||||
for (int i = 0; i < layout.lanes.length; i++) {
|
||||
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2 + ox;
|
||||
_rectCell(
|
||||
'lane-${layout.lanes[i]}',
|
||||
'轨道 L${i + 1}',
|
||||
cx - FlowLayout.nodeW / 2 - 26,
|
||||
top,
|
||||
FlowLayout.nodeW + 52,
|
||||
bottom - top,
|
||||
'rounded=0;whiteSpace=wrap;html=1;verticalAlign=top;fontSize=11;fontStyle=1;'
|
||||
'fillColor=${_hex(i.isEven ? tokens.ringA : tokens.ringB)};fillOpacity=55;'
|
||||
'strokeColor=none;fontColor=${_hex(tokens.sub)};',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入相位竖带:竖排文字(`horizontal=0`)+ 低透明度填充,台阶错位保持一致。
|
||||
void _phases(FlowLayout layout, double ox, double oy) {
|
||||
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
|
||||
for (int i = 0; i < layout.spans.length; i++) {
|
||||
final FlowPhaseSpan s = layout.spans[i];
|
||||
final double top = FlowLayout.marginY + s.rankTop * rowPitch - 6 + oy;
|
||||
final double bottom =
|
||||
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6 + oy;
|
||||
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep + ox;
|
||||
_rectCell(
|
||||
'phase-$i',
|
||||
s.zone.name,
|
||||
left,
|
||||
top,
|
||||
FlowLayout.railW,
|
||||
bottom - top,
|
||||
'rounded=1;whiteSpace=wrap;html=1;horizontal=0;fontSize=10;fontStyle=1;'
|
||||
'fillColor=${_hex(tokens.accent)};fillOpacity=10;'
|
||||
'strokeColor=${_hex(tokens.accent)};strokeOpacity=45;fontColor=${_hex(tokens.sub)};',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入动作节点与开始 / 结束胶囊。
|
||||
void _nodes(FlowLayout layout, double ox, double oy) {
|
||||
for (final FlowNode n in layout.nodes) {
|
||||
final Rect r = n.rect;
|
||||
if (n.isStart || n.isEnd) {
|
||||
_rectCell(
|
||||
_cellId(n.id),
|
||||
n.title,
|
||||
r.left + ox,
|
||||
r.top + oy,
|
||||
r.width,
|
||||
r.height,
|
||||
'ellipse;whiteSpace=wrap;html=1;fontSize=13;fontStyle=1;'
|
||||
'fillColor=${_hex(tokens.panel2)};strokeColor=${_hex(tokens.accent)};'
|
||||
'fontColor=${_hex(tokens.accent)};',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
final Action a = n.action!;
|
||||
// 节点两行文字:标题(序号. 名称)+ 副标题(时长 · 工位)。
|
||||
_rectCell(
|
||||
_cellId(n.id),
|
||||
'${n.title}\n${n.subtitle}',
|
||||
r.left + ox,
|
||||
r.top + oy,
|
||||
r.width,
|
||||
r.height,
|
||||
'rounded=1;absoluteArcSize=1;arcSize=10;whiteSpace=wrap;html=1;fontSize=12;fontStyle=1;'
|
||||
'fillColor=${_hex(Color(a.color))};fillOpacity=92;'
|
||||
'strokeColor=${_hex(tokens.selOutline)};strokeOpacity=25;'
|
||||
'fontColor=${_hex(tokens.arcText)};',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入依赖连线:以 source / target 引用节点,drawio 自动正交布线并可再编辑。
|
||||
///
|
||||
/// 样式与画布一致:FS 绿实线、SS 琥珀虚线(标签标注偏移时间)、关键路径加粗。
|
||||
void _edges(FlowLayout layout) {
|
||||
int i = 0;
|
||||
for (final FlowEdge e in layout.edges) {
|
||||
i++;
|
||||
final bool fs = e.type == DepType.fs;
|
||||
final String col =
|
||||
_hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
|
||||
final String label = switch (e.type) {
|
||||
null => '',
|
||||
DepType.fs => 'FS',
|
||||
DepType.ss => e.offset == 0
|
||||
? 'SS'
|
||||
: 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}',
|
||||
DepType.ff => 'FF',
|
||||
DepType.sf => 'SF',
|
||||
};
|
||||
_b.write('<mxCell id="edge-$i-${_cellId(e.fromId)}-${_cellId(e.toId)}" '
|
||||
'value="${_esc(label)}" '
|
||||
'style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;jettySize=auto;'
|
||||
'orthogonalLoop=1;endArrow=block;endFill=1;'
|
||||
'strokeWidth=${e.critical ? 2.4 : 1.3};strokeColor=$col;'
|
||||
'${e.type == DepType.ss ? 'dashed=1;dashPattern=6 4;' : ''}'
|
||||
'fontSize=9;fontColor=$col;labelBackgroundColor=${_hex(tokens.bg)};" '
|
||||
'edge="1" parent="1" source="${_cellId(e.fromId)}" target="${_cellId(e.toId)}">'
|
||||
'<mxGeometry relative="1" as="geometry"/></mxCell>');
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入一个顶点(矩形 / 胶囊 / 竖带)单元格。
|
||||
void _rectCell(String id, String value, double x, double y, double w, double h,
|
||||
String style) {
|
||||
_b.write('<mxCell id="$id" value="${_esc(value)}" '
|
||||
'style="$style" vertex="1" parent="1">'
|
||||
'<mxGeometry x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" '
|
||||
'width="${w.toStringAsFixed(1)}" height="${h.toStringAsFixed(1)}" as="geometry"/>'
|
||||
'</mxCell>');
|
||||
}
|
||||
|
||||
/// 节点 id → drawio 单元格 id:开始 / 结束用可读短名,其余原样保留。
|
||||
static String _cellId(String nodeId) {
|
||||
if (nodeId == FlowNode.startId) return 'flow-start';
|
||||
if (nodeId == FlowNode.endId) return 'flow-end';
|
||||
return nodeId.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_');
|
||||
}
|
||||
|
||||
/// 转义 XML 文本 / 属性中的特殊字符;换行转为 ` `(drawio 多行标签约定)。
|
||||
static String _esc(String s) => s
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll('\n', ' ');
|
||||
|
||||
/// 把 Flutter [Color] 转为 `#rrggbb` 字符串(忽略 alpha)。
|
||||
static String _hex(Color c) {
|
||||
final int r = (c.r * 255).round();
|
||||
final int g = (c.g * 255).round();
|
||||
final int b = (c.b * 255).round();
|
||||
return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/// 导出适配:固定 1920×1080 画布下,把时序图内容缩放到内容区并居中,
|
||||
/// 供 PNG 渲染器与 SVG 写入器共用,保证两种导出几何完全一致。
|
||||
///
|
||||
/// 约定:
|
||||
/// - 画布固定 1920×1080;
|
||||
/// - 标题固定在左上角(标题区 0–128px);
|
||||
/// - 内容区 = (48, 128) → (1872, 1016),图例固定左下角;
|
||||
/// - 内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/export/export_geometry.dart';
|
||||
|
||||
export 'package:sequence_diagram/export/export_geometry.dart' show ExportFit, kExportContentArea, kExportPixelRatio, kExportSize, exportTokens;
|
||||
import 'package:sequence_diagram/modules/sequence/layout/layout.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/render/bar_painter.dart';
|
||||
|
||||
/// 计算内容在 [area] 内的适配变换。
|
||||
///
|
||||
/// 先以 1920×1080 为参考画布求内容包围盒,再等比缩放并居中。
|
||||
ExportFit computeExportFit(Project project, ViewMode mode, Rect area) {
|
||||
Rect bounds;
|
||||
if (mode == ViewMode.bar) {
|
||||
final BarLayout l = BarLayout(project, kExportSize);
|
||||
final int n = l.lanes.length;
|
||||
final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.plotBottom + 8;
|
||||
bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom);
|
||||
} else if (mode == ViewMode.circular) {
|
||||
final CircularLayout l = CircularLayout(project, kExportSize);
|
||||
final double rExt = l.tickR + 100;
|
||||
bounds = Rect.fromLTRB(l.center.dx - rExt, l.center.dy - rExt, l.center.dx + rExt, l.center.dy + rExt);
|
||||
} else {
|
||||
// 流程图:直接使用布局层给出的内容范围(含泳道、阶段栏与连线)。
|
||||
final FlowLayout l = FlowLayout(project);
|
||||
bounds = l.nodes.isEmpty ? const Rect.fromLTWH(0, 0, 800, 600) : l.bounds;
|
||||
}
|
||||
if (bounds.width <= 1 || bounds.height <= 1) {
|
||||
return const ExportFit(1, 0, 0);
|
||||
}
|
||||
final double s = math.min(area.width / bounds.width, area.height / bounds.height).clamp(0.2, 1.6);
|
||||
final double tx = area.left + (area.width - bounds.width * s) / 2 - bounds.left * s;
|
||||
final double ty = area.top + (area.height - bounds.height * s) / 2 - bounds.top * s;
|
||||
return ExportFit(s, tx, ty);
|
||||
}
|
||||
|
||||
/// 导出标题(与画布浮层一致)。
|
||||
String exportTitle(ViewMode mode) => switch (mode) {
|
||||
ViewMode.bar => '条形时序视图',
|
||||
ViewMode.circular => '圆周时序视图',
|
||||
ViewMode.flow => '流程图视图',
|
||||
};
|
||||
|
||||
/// 导出副标题:仅保留括号内的线型图例(与画布标题后方的说明一致)。
|
||||
///
|
||||
/// 更完整的视图语义(同心圆环 / 循环换算等)见应用内「帮助」。
|
||||
String exportSubtitle(ViewMode mode) => switch (mode) {
|
||||
ViewMode.bar => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
|
||||
ViewMode.circular => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
|
||||
// 流程图不重复线型说明,导出仅保留标题(与画布浮层一致)。
|
||||
ViewMode.flow => '',
|
||||
};
|
||||
|
||||
/// 导出图例(左下角固定)。
|
||||
String exportLegend(Project project) =>
|
||||
'时序图设计 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°';
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/// PNG 导出渲染器:把时序图渲染为固定 1920×1080 的位图。
|
||||
///
|
||||
/// 与 SVG 导出共用同一套适配计算([computeExportFit]),保证两种格式几何一致:
|
||||
/// - 背景铺满 1920×1080;
|
||||
/// - 标题固定在左上角、图例固定在左下角;
|
||||
/// - 内容(条形 / 圆周)按自身包围盒等比缩放并居中到内容区。
|
||||
library;
|
||||
|
||||
import 'dart:typed_data';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/render/bar_painter.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/render/circular_painter.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/render/flow_painter.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'export_fit.dart';
|
||||
|
||||
/// 渲染导出 PNG 并返回字节。
|
||||
///
|
||||
/// 参数:
|
||||
/// - [project]:数据源;
|
||||
/// - [tokens]:配色令牌(内部转为导出专用纯白主题);
|
||||
/// - [criticalActions]/[criticalDeps]:关键路径高亮(与屏幕一致)。
|
||||
///
|
||||
/// 输出:3840×2160 像素(1920×1080 逻辑画布 × 2 倍像素比),
|
||||
/// 保证平板 / 2K / 4K 屏幕上查看清晰锐利。
|
||||
Future<Uint8List> renderExportPng({
|
||||
required Project project,
|
||||
required Tokens tokens,
|
||||
required Set<String> criticalActions,
|
||||
required Set<String> criticalDeps,
|
||||
}) async {
|
||||
// 导出专用令牌:纯白背景、浅色文字。
|
||||
final Tokens et = exportTokens(tokens);
|
||||
final ui.PictureRecorder recorder = ui.PictureRecorder();
|
||||
final Canvas canvas = Canvas(recorder);
|
||||
final double w = kExportSize.width;
|
||||
final double h = kExportSize.height;
|
||||
// 2 倍像素比:整体放大绘制,矢量内容保持锐利。
|
||||
canvas.scale(kExportPixelRatio);
|
||||
|
||||
// 背景铺满(纯白)。
|
||||
canvas.drawRect(Rect.fromLTWH(0, 0, w, h), Paint()..color = et.bg);
|
||||
|
||||
// 标题:固定左上角。
|
||||
final ViewMode mode = project.viewState.mode;
|
||||
_text(canvas, exportTitle(mode), const Offset(48, 36),
|
||||
color: et.text, size: 34, weight: FontWeight.w700);
|
||||
_text(canvas, exportSubtitle(mode), const Offset(48, 88),
|
||||
color: et.sub, size: 16, weight: FontWeight.w400);
|
||||
|
||||
// 内容:适配缩放并居中到内容区。
|
||||
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
|
||||
canvas.save();
|
||||
canvas.translate(fit.tx, fit.ty);
|
||||
canvas.scale(fit.scale);
|
||||
if (mode == ViewMode.bar) {
|
||||
BarPainter(
|
||||
project: project,
|
||||
tokens: et,
|
||||
criticalActions: criticalActions,
|
||||
criticalDeps: criticalDeps,
|
||||
selectedIds: const <String>{},
|
||||
).paint(canvas, kExportSize);
|
||||
} else if (mode == ViewMode.flow) {
|
||||
FlowchartPainter(
|
||||
project: project,
|
||||
tokens: et,
|
||||
criticalActions: criticalActions,
|
||||
criticalDeps: criticalDeps,
|
||||
selectedIds: const <String>{},
|
||||
).paint(canvas, kExportSize);
|
||||
} else {
|
||||
CircularPainter(
|
||||
project: project,
|
||||
tokens: et,
|
||||
criticalActions: criticalActions,
|
||||
criticalDeps: criticalDeps,
|
||||
selectedIds: const <String>{},
|
||||
).paint(canvas, kExportSize);
|
||||
}
|
||||
canvas.restore();
|
||||
|
||||
// 图例:固定左下角。
|
||||
_text(canvas, exportLegend(project), Offset(48, h - 38),
|
||||
color: et.sub, size: 15, weight: FontWeight.w400);
|
||||
|
||||
final ui.Image image = await recorder
|
||||
.endRecording()
|
||||
.toImage((w * kExportPixelRatio).toInt(), (h * kExportPixelRatio).toInt());
|
||||
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
return data!.buffer.asUint8List();
|
||||
}
|
||||
|
||||
/// 用统一字体绘制单行文本。
|
||||
void _text(Canvas canvas, String s, Offset at,
|
||||
{required Color color, required double size, required FontWeight weight}) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: size,
|
||||
fontWeight: weight,
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
fontFamilyFallback: const <String>['Microsoft YaHei', 'Noto Sans SC', 'sans-serif'],
|
||||
),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
)..layout();
|
||||
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
/// SVG 导出写入器。
|
||||
///
|
||||
/// 职责:把当前 [Project] 序列化为独立、可缩放、带语义标注的 SVG 文档,
|
||||
/// 用于归档、打印,或与前端 / EDA 工具交换。
|
||||
///
|
||||
/// 架构位置:
|
||||
/// - 与渲染层 `BarPainter`/`CircularPainter` 共用 [BarLayout]/[CircularLayout]
|
||||
/// 的几何算法,确保屏幕显示与导出结果一致。
|
||||
/// - 颜色取自 [Tokens],并通过 [_hex] 转为 `#rrggbb`。
|
||||
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
|
||||
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
|
||||
///
|
||||
/// 输出约定(与 PNG 导出一致):
|
||||
/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放;
|
||||
/// - 标题固定在左上角、图例固定在左下角;
|
||||
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
|
||||
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/layout.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'export_fit.dart';
|
||||
|
||||
/// SVG 文档写入器。
|
||||
///
|
||||
/// 通过内部 [StringBuffer] 逐段拼接字符串,最终由 [build] 返回完整文档。
|
||||
class SvgWriter {
|
||||
/// 创建 SVG 写入器。
|
||||
///
|
||||
/// 参数:
|
||||
/// - [project]:数据源(动作、依赖、视图开关、单位)。
|
||||
/// - [tokens]:配色令牌。
|
||||
/// - [mode]:视图模式,决定生成条形还是圆形布局。
|
||||
///
|
||||
/// 构造时不生成任何内容;调用 [build] 才写出 SVG。
|
||||
///
|
||||
/// [tokens] 会经 [exportTokens] 转为导出专用令牌(纯白背景、浅色文字)。
|
||||
SvgWriter({required this.project, required Tokens tokens, required this.mode})
|
||||
: tokens = exportTokens(tokens);
|
||||
|
||||
/// 数据源工程。
|
||||
final Project project;
|
||||
/// 配色令牌。
|
||||
final Tokens tokens;
|
||||
/// 导出所用的视图模式。
|
||||
final ViewMode mode;
|
||||
|
||||
/// 输出缓冲区,累积 SVG 文本片段。
|
||||
final StringBuffer _b = StringBuffer();
|
||||
/// 统一字体栈常量。
|
||||
static const String _font = "'Microsoft YaHei','Noto Sans SC','Segoe UI',sans-serif";
|
||||
|
||||
/// 生成完整 SVG 文档字符串。
|
||||
///
|
||||
/// 输出约定(与 PNG 导出一致):
|
||||
/// - 画布固定 1920×1080;
|
||||
/// - 标题固定在左上角、图例固定在左下角;
|
||||
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
|
||||
///
|
||||
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
|
||||
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
|
||||
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
|
||||
String build() {
|
||||
const double w = 1920;
|
||||
const double h = 1080;
|
||||
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">');
|
||||
// 先写箭头 marker 定义,供后续依赖路径引用。
|
||||
_defs();
|
||||
// 背景层:铺满整张画布。
|
||||
_b.write('<g id="background">');
|
||||
_rect(0, 0, w, h, fill: _hex(tokens.bg));
|
||||
_b.write('</g>');
|
||||
// 标题:固定左上角。
|
||||
_b.write('<g id="title">');
|
||||
_text(48, 60, exportTitle(mode), color: _hex(tokens.text), size: 34, weight: '700');
|
||||
_text(48, 104, exportSubtitle(mode), color: _hex(tokens.sub), size: 16);
|
||||
_b.write('</g>');
|
||||
// 内容:适配缩放并居中到内容区。
|
||||
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
|
||||
_b.write('<g id="content" transform="${fit.svgTransform}">');
|
||||
if (mode == ViewMode.bar) {
|
||||
_barView(const Size(w, h));
|
||||
} else if (mode == ViewMode.circular) {
|
||||
_circularView(const Size(w, h));
|
||||
} else {
|
||||
_flowView();
|
||||
}
|
||||
_b.write('</g>');
|
||||
// 图例:固定左下角。
|
||||
_b.write('<g id="legend">');
|
||||
_text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15);
|
||||
_b.write('</g>');
|
||||
_b.write('</svg>');
|
||||
return _b.toString();
|
||||
}
|
||||
|
||||
/// 写入 `<defs>` 段,定义 FS / SS 两种箭头 marker。
|
||||
///
|
||||
/// marker 通过 id `arrow-fs`、`arrow-ss` 被依赖路径的 `marker-end` 引用;
|
||||
/// `orient="auto"` 使箭头自动跟随路径末端方向。
|
||||
void _defs() {
|
||||
_b.write('<defs>');
|
||||
_b.write('<marker id="arrow-fs" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
|
||||
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.fs)}"/></marker>');
|
||||
_b.write('<marker id="arrow-ss" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
|
||||
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.ss)}"/></marker>');
|
||||
_b.write('</defs>');
|
||||
}
|
||||
|
||||
/// 生成条形视图的 SVG 内容。
|
||||
///
|
||||
/// 参数 [size] 用于构建与屏幕一致的 [BarLayout]。
|
||||
/// 依次输出四个分组:
|
||||
/// - `g#ruler`:角度/时间双轴标尺(`data-axis="angle"`)。
|
||||
/// - `g#actions`:每个动作一个 `g`,带 `data-action/start/duration/layer/station`。
|
||||
/// - `g#labels`:左侧动作标识与工位/驱动文本。
|
||||
/// - `g#dependencies`(可选):依赖正交折线。
|
||||
void _barView(Size size) {
|
||||
final BarLayout layout = BarLayout(project, size);
|
||||
final UnitSettings u = project.units;
|
||||
final double cycle = project.cycle.durationMs;
|
||||
final double top = BarLayout.topPad - 62;
|
||||
|
||||
// 标尺分组:下排为相位角,上排为等价时间;data-axis 标记角度轴语义。
|
||||
_b.write('<g id="ruler" data-axis="angle">');
|
||||
_rect(layout.plotLeft, top, layout.span, 26, fill: _hex(tokens.accent), opacity: 0.07);
|
||||
for (int d = 0; d <= 360; d += 30) {
|
||||
final double x = layout.xFor(d.toDouble());
|
||||
_line(x, top + 26, x, top + 44, stroke: _hex(tokens.line2), sw: 1);
|
||||
_text(x, top - 10, tvalStr(d / 360 * cycle, u, dec: 1), color: _hex(tokens.dim), size: 11, anchor: 'middle');
|
||||
_text(x, top + 58, pfmt(d.toDouble(), u, dec: 0), color: _hex(tokens.accent), size: 11, anchor: 'middle');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 动作分组:每个动作一个 <g>,附带 data-* 语义属性,便于下游解析。
|
||||
_b.write('<g id="actions">');
|
||||
final List<Action> ordered = layout.ordered;
|
||||
for (int i = 0; i < ordered.length; i++) {
|
||||
final Action a = ordered[i];
|
||||
final Rect r = layout.rectFor(a);
|
||||
final Color c = Color(a.color);
|
||||
_b.write('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
|
||||
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
|
||||
_rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 3, opacity: 0.92);
|
||||
_text(r.left + 8, r.center.dy + 4, '${a.name} ${tfmt(a.durationAngle / 360 * cycle, u)}',
|
||||
color: _hex(tokens.arcText), size: 12, weight: '700');
|
||||
_b.write('</g>');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 标签分组:左侧动作标识与工位/驱动信息。
|
||||
_b.write('<g id="labels">');
|
||||
for (int i = 0; i < ordered.length; i++) {
|
||||
final Action a = ordered[i];
|
||||
final double y = layout.yForSlot(a.layer, layout.slotOf(a));
|
||||
_text(BarLayout.leftGutter + 6, y + 8, '${a.id} ${a.name}', color: _hex(tokens.text), size: 13, weight: '600');
|
||||
_text(BarLayout.leftGutter + 6, y + 24, '${a.stationId} · ${a.driver}', color: _hex(tokens.dim), size: 10.5);
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移时间语义。
|
||||
if (project.viewState.showDeps) {
|
||||
_b.write('<g id="dependencies">');
|
||||
final Map<String, int> index = <String, int>{};
|
||||
for (int i = 0; i < ordered.length; i++) {
|
||||
index[ordered[i].id] = i;
|
||||
}
|
||||
for (final Action to in ordered) {
|
||||
for (final Dependency d in to.deps) {
|
||||
final Action? from = project.actionById(d.fromId);
|
||||
if (from == null) continue;
|
||||
final Rect ra = layout.rectFor(from);
|
||||
final Rect rb = layout.rectFor(to);
|
||||
final bool fs = d.type == DepType.fs;
|
||||
final Color col = fs ? tokens.fs : tokens.ss;
|
||||
final double sx = fs ? ra.right : ra.left;
|
||||
final double sy = ra.center.dy;
|
||||
final double tx = rb.left + 12;
|
||||
final double ty = rb.center.dy - 10;
|
||||
final String dPath = 'M $sx $sy L $sx ${(sy + ty) / 2} L $tx ${(sy + ty) / 2} L $tx $ty';
|
||||
_b.write('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
|
||||
'd="$dPath" fill="none" stroke="${_hex(col)}" stroke-width="2" '
|
||||
'${fs ? '' : 'stroke-dasharray="6 4" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
|
||||
}
|
||||
}
|
||||
_b.write('</g>');
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成圆形视图的 SVG 内容。
|
||||
///
|
||||
/// 参数 [size] 用于构建 [CircularLayout]。
|
||||
/// 依次输出:
|
||||
/// - `g#layers`:同心圆环背景(奇偶层交替着色)。
|
||||
/// - `g#ruler`:每 30° 的刻度与度数。
|
||||
/// - `g#actions`:动作弧,跨循环动作经 [splitArcs] 拆成多段。
|
||||
/// - `g#dependencies`(可选):沿半径与圆弧的依赖路径。
|
||||
void _circularView(Size size) {
|
||||
final CircularLayout layout = CircularLayout(project, size);
|
||||
final Offset c = layout.center;
|
||||
final double th = layout.th;
|
||||
|
||||
// 圆环层背景分组。
|
||||
_b.write('<g id="layers">');
|
||||
for (int i = 0; i <= project.maxLayer; i++) {
|
||||
final double r = layout.radiusFor(i);
|
||||
_circle(c.dx, c.dy, r, stroke: _hex(i.isEven ? tokens.ringA : tokens.ringB), sw: th);
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 角度刻度分组,data-axis 标记角度轴语义。
|
||||
_b.write('<g id="ruler" data-axis="angle">');
|
||||
for (int d = 0; d < 360; d += 30) {
|
||||
final Offset p1 = polar(c, layout.tickR, d.toDouble());
|
||||
final Offset p2 = polar(c, layout.tickR + 16, d.toDouble());
|
||||
_line(p1.dx, p1.dy, p2.dx, p2.dy, stroke: _hex(tokens.line2), sw: 1);
|
||||
final Offset lp = polar(c, layout.tickR + 34, d.toDouble());
|
||||
_text(lp.dx, lp.dy, '$d°', color: _hex(tokens.sub), size: 11, anchor: 'middle');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 动作弧分组:跨循环动作由 splitArcs 拆段,逐段写 <path>。
|
||||
_b.write('<g id="actions">');
|
||||
for (final Action a in project.actions) {
|
||||
final double r = layout.radiusFor(a.layer);
|
||||
final Color col = Color(a.color);
|
||||
_b.write('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
|
||||
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
|
||||
for (final List<double> s in splitArcs(a.startAngle, a.endAngle)) {
|
||||
final String d = _arc(c, r, s[0], s[1]);
|
||||
_b.write('<path d="$d" fill="none" stroke="${_hex(col)}" stroke-width="$th" stroke-linecap="butt"/>');
|
||||
}
|
||||
final Offset mp = polar(c, r, (a.startAngle + a.endAngle) / 2);
|
||||
_text(mp.dx, mp.dy, '${a.id} ${a.name}', color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
|
||||
_b.write('</g>');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 依赖分组:路径由“半径 → 圆弧 → 半径”三段构成,与屏幕渲染一致。
|
||||
if (project.viewState.showDeps) {
|
||||
_b.write('<g id="dependencies">');
|
||||
for (final Action to in project.actions) {
|
||||
for (final Dependency d in to.deps) {
|
||||
final Action? A = project.actionById(d.fromId);
|
||||
final Action? B = project.actionById(d.toId);
|
||||
if (A == null || B == null) continue;
|
||||
final double rA = layout.radiusFor(A.layer);
|
||||
final double rB = layout.radiusFor(B.layer);
|
||||
final double aEnd = math.min(A.endAngle, 360);
|
||||
final double aStart = B.startAngle;
|
||||
final bool skip = (A.layer - B.layer).abs() > 1;
|
||||
final double rC = skip ? layout.rMax + 24 : (rA + rB) / 2;
|
||||
final Offset p0 = polar(c, rA, aEnd);
|
||||
final Offset p1 = polar(c, rC, aEnd);
|
||||
final Offset p2 = polar(c, rC, aStart);
|
||||
final double rTip = rC < rB ? rB - th / 2 - 4 : rB + th / 2 + 4;
|
||||
final Offset p3 = polar(c, rTip, aStart);
|
||||
final bool fs = d.type == DepType.fs;
|
||||
final Color col = fs ? tokens.fs : tokens.ss;
|
||||
final String dd = 'M ${p0.dx.toStringAsFixed(1)} ${p0.dy.toStringAsFixed(1)} '
|
||||
'L ${p1.dx.toStringAsFixed(1)} ${p1.dy.toStringAsFixed(1)} '
|
||||
'A $rC $rC 0 0 ${aStart >= aEnd ? 1 : 0} ${p2.dx.toStringAsFixed(1)} ${p2.dy.toStringAsFixed(1)} '
|
||||
'L ${p3.dx.toStringAsFixed(1)} ${p3.dy.toStringAsFixed(1)}';
|
||||
_b.write('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
|
||||
'd="$dd" fill="none" stroke="${_hex(col)}" stroke-width="2" '
|
||||
'${fs ? '' : 'stroke-dasharray="7 5" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
|
||||
}
|
||||
}
|
||||
_b.write('</g>');
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成流程图视图的 SVG 内容。
|
||||
///
|
||||
/// 几何完全复用 [FlowLayout](与屏幕画布、drawio 导出共用同一套走线),
|
||||
/// 依次输出:
|
||||
/// - `g#lanes`:泳道背景带与轨道标题;
|
||||
/// - `g#phases`:左侧相位竖带(分区名旋转 90°,重叠分区台阶错位);
|
||||
/// - `g#edges`:依赖折线(FS 实线 / SS 虚线,带箭头与 FS/SS 标签);
|
||||
/// - `g#actions`:动作节点与开始 / 结束胶囊(带 data-* 语义属性)。
|
||||
void _flowView() {
|
||||
final FlowLayout layout = FlowLayout(project);
|
||||
if (layout.nodes.isEmpty) return;
|
||||
|
||||
// 泳道背景带(与画布一致:环带色 55% 透明度 + 轨道标题)。
|
||||
_b.write('<g id="lanes">');
|
||||
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
|
||||
final double top = layout.bounds.top + 20;
|
||||
final double bottom = layout.bounds.bottom - 20;
|
||||
for (int i = 0; i < layout.lanes.length; i++) {
|
||||
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2;
|
||||
_rect(cx - FlowLayout.nodeW / 2 - 26, top, FlowLayout.nodeW + 52, bottom - top,
|
||||
fill: _hex(i.isEven ? tokens.ringA : tokens.ringB), rx: 14, opacity: 0.55);
|
||||
_text(cx, top + 16, '轨道 L${i + 1}',
|
||||
color: _hex(tokens.sub), size: 11, anchor: 'middle', weight: '700');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 相位竖带:窄带 + 旋转 90° 分区名,纵向对齐流程行、重叠分区台阶错位。
|
||||
_b.write('<g id="phases">');
|
||||
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
|
||||
for (final FlowPhaseSpan s in layout.spans) {
|
||||
final double pTop = FlowLayout.marginY + s.rankTop * rowPitch - 6;
|
||||
final double pBottom =
|
||||
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6;
|
||||
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep;
|
||||
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
|
||||
fill: _hex(tokens.accent), rx: 9, opacity: 0.10);
|
||||
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
|
||||
fill: 'none', rx: 9, stroke: _hex(tokens.accent), sw: 1, opacity: 0.45);
|
||||
final double tx = left + FlowLayout.railW / 2;
|
||||
final double ty = (pTop + pBottom) / 2;
|
||||
_b.write('<text transform="translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) rotate(-90)" '
|
||||
'font-family="$_font" font-size="10.5" fill="${_hex(tokens.sub)}" text-anchor="middle" '
|
||||
'dominant-baseline="middle" font-weight="700">${_esc(s.zone.name)}</text>');
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 依赖折线:FS 实线 / SS 虚线,带箭头与 FS/SS 标签。
|
||||
_b.write('<g id="edges">');
|
||||
for (final FlowEdgeRoute r in layout.routes) {
|
||||
final FlowEdge e = r.edge;
|
||||
final bool fs = e.type == DepType.fs;
|
||||
final String col = _hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
|
||||
final String d = <String>[
|
||||
for (int i = 0; i < r.points.length; i++)
|
||||
'${i == 0 ? 'M' : 'L'} ${r.points[i].dx.toStringAsFixed(1)} ${r.points[i].dy.toStringAsFixed(1)}',
|
||||
].join(' ');
|
||||
final String marker = e.type == null ? '' : ' marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"';
|
||||
final String dash = r.dashed ? ' stroke-dasharray="6 4"' : '';
|
||||
_b.write('<path d="$d" fill="none" stroke="$col" stroke-width="${e.critical ? 2 : 1.3}"'
|
||||
'$dash$marker/>');
|
||||
if (e.type != null) {
|
||||
final String text = switch (e.type!) {
|
||||
DepType.fs => 'FS',
|
||||
DepType.ss => e.offset == 0
|
||||
? 'SS'
|
||||
: 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}',
|
||||
DepType.ff => 'FF',
|
||||
DepType.sf => 'SF',
|
||||
};
|
||||
_text(r.labelAt.dx, r.labelAt.dy, text,
|
||||
color: col, size: 9, anchor: 'middle', weight: '600');
|
||||
}
|
||||
}
|
||||
_b.write('</g>');
|
||||
|
||||
// 动作节点与开始 / 结束胶囊。
|
||||
_b.write('<g id="actions">');
|
||||
for (final FlowNode n in layout.nodes) {
|
||||
final Rect r = n.rect;
|
||||
if (n.isStart || n.isEnd) {
|
||||
_rect(r.left, r.top, r.width, r.height,
|
||||
fill: _hex(tokens.panel2), rx: r.height / 2, stroke: _hex(tokens.accent), sw: 1.2);
|
||||
_text(r.center.dx, r.center.dy, n.title,
|
||||
color: _hex(tokens.accent), size: 13, anchor: 'middle', weight: '700');
|
||||
continue;
|
||||
}
|
||||
final Action a = n.action!;
|
||||
final Color c = Color(a.color);
|
||||
_b.write('<g id="${_esc(n.id)}" data-action="${_esc(n.id)}" data-start="${a.startAngle}" '
|
||||
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
|
||||
_rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 10, opacity: 0.92);
|
||||
_text(r.center.dx, r.top + 21, n.title,
|
||||
color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
|
||||
_text(r.center.dx, r.top + 41, n.subtitle,
|
||||
color: _hex(tokens.arcText), size: 10, anchor: 'middle');
|
||||
_b.write('</g>');
|
||||
}
|
||||
_b.write('</g>');
|
||||
}
|
||||
|
||||
/// 生成一段圆弧的 SVG `d` 路径字符串。
|
||||
///
|
||||
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
|
||||
/// 通过 [polar] 求端点,按跨度是否大于 180° 设置 large-arc 标志,
|
||||
/// sweep 固定为 1(顺时针)。
|
||||
String _arc(Offset c, double r, double a0, double a1) {
|
||||
final Offset s = polar(c, r, a0);
|
||||
final Offset e = polar(c, r, a1);
|
||||
final int large = (a1 - a0) > 180 ? 1 : 0;
|
||||
return 'M ${s.dx.toStringAsFixed(1)} ${s.dy.toStringAsFixed(1)} '
|
||||
'A ${r.toStringAsFixed(1)} ${r.toStringAsFixed(1)} 0 $large 1 ${e.dx.toStringAsFixed(1)} ${e.dy.toStringAsFixed(1)}';
|
||||
}
|
||||
|
||||
/// 写入一个 `<rect>` 元素。
|
||||
///
|
||||
/// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。
|
||||
void _rect(double x, double y, double w, double h,
|
||||
{String? fill, double rx = 0, double opacity = 1, String? stroke, double sw = 1}) {
|
||||
_b.write('<rect x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" width="${w.toStringAsFixed(1)}" '
|
||||
'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"'
|
||||
'${stroke == null ? '' : ' stroke="$stroke" stroke-width="$sw"'}'
|
||||
'/>');
|
||||
}
|
||||
|
||||
/// 写入一个 `<circle>` 元素。
|
||||
///
|
||||
/// 参数 [cx]/[cy] 圆心、[r] 半径;可选 [stroke] 描边色、[fill] 填充色、
|
||||
/// [sw] 描边宽度。
|
||||
void _circle(double cx, double cy, double r, {String? stroke, String? fill, double sw = 1}) {
|
||||
_b.write('<circle cx="${cx.toStringAsFixed(1)}" cy="${cy.toStringAsFixed(1)}" r="${r.toStringAsFixed(1)}" '
|
||||
'fill="${fill ?? 'none'}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
|
||||
}
|
||||
|
||||
/// 写入一个 `<line>` 元素。
|
||||
///
|
||||
/// 参数为两端点坐标;可选 [stroke] 描边色、[sw] 描边宽度。
|
||||
void _line(double x1, double y1, double x2, double y2, {String? stroke, double sw = 1}) {
|
||||
_b.write('<line x1="${x1.toStringAsFixed(1)}" y1="${y1.toStringAsFixed(1)}" x2="${x2.toStringAsFixed(1)}" '
|
||||
'y2="${y2.toStringAsFixed(1)}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
|
||||
}
|
||||
|
||||
/// 写入一个 `<text>` 元素。
|
||||
///
|
||||
/// 参数 [x]/[y] 锚点坐标、[s] 文本内容(会经 [_esc] 转义);
|
||||
/// 可选 [color] 颜色、[size] 字号、[anchor] 水平锚点、[weight] 字重。
|
||||
/// 垂直方向统一使用 `dominant-baseline="middle"` 居中。
|
||||
void _text(double x, double y, String s,
|
||||
{String? color, double size = 12, String anchor = 'start', String weight = '400'}) {
|
||||
_b.write('<text x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" font-family="$_font" '
|
||||
'font-size="$size" fill="${color ?? 'none'}" text-anchor="$anchor" font-weight="$weight" '
|
||||
'dominant-baseline="middle">${_esc(s)}</text>');
|
||||
}
|
||||
|
||||
/// 把 Flutter [Color] 转为 `#rrggbb` 字符串。
|
||||
///
|
||||
/// 忽略 alpha 通道;各通道四舍五入并补零到两位十六进制。
|
||||
static String _hex(Color c) {
|
||||
final int r = (c.r * 255).round();
|
||||
final int g = (c.g * 255).round();
|
||||
final int b = (c.b * 255).round();
|
||||
return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
/// 转义 XML 文本中的特殊字符(`&`、`<`、`>`、`"`),防止破坏 SVG 结构。
|
||||
static String _esc(String s) => s
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
/// 依赖连线的共享走线计算。
|
||||
///
|
||||
/// 条形视图 / 圆周视图的**画布绘制、标签放置与命中测试**(点选连线、
|
||||
/// 沿法线拖拽调整走线)都使用这里的同一份几何,避免绘制与命中不一致:
|
||||
/// - 自动错开:同一走线分组内的多条依赖依次错开,先解决“完全重叠”;
|
||||
/// - 手动偏移:[Dependency.routeOffset] 叠加在自动错开之上(拖拽连线的结果)。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'layout.dart';
|
||||
|
||||
// ===================== 通用工具 =====================
|
||||
|
||||
/// 点 [p] 到线段 [a]–[b] 的最短距离。
|
||||
double distanceToSegment(Offset p, Offset a, Offset b) {
|
||||
final Offset ab = b - a;
|
||||
final double len2 = ab.dx * ab.dx + ab.dy * ab.dy;
|
||||
if (len2 <= 0) return (p - a).distance;
|
||||
final double t = (((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2).clamp(0.0, 1.0);
|
||||
return (p - (a + ab * t)).distance;
|
||||
}
|
||||
|
||||
/// 点 [p] 到折线 [pts] 的最短距离。
|
||||
double distanceToPolyline(List<Offset> pts, Offset p) {
|
||||
double best = double.infinity;
|
||||
for (int i = 0; i + 1 < pts.length; i++) {
|
||||
final double d = distanceToSegment(p, pts[i], pts[i + 1]);
|
||||
if (d < best) best = d;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// 点 [p] 到路径 [path] 的近似最短距离(按弧长采样,步长 [step])。
|
||||
double distanceToPath(Path path, Offset p, {double step = 4}) {
|
||||
double best = double.infinity;
|
||||
for (final PathMetric m in path.computeMetrics()) {
|
||||
for (double d = 0; d < m.length; d += step) {
|
||||
final Tangent? t = m.getTangentForOffset(d);
|
||||
if (t == null) continue;
|
||||
final double dist = (t.position - p).distance;
|
||||
if (dist < best) best = dist;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// 第 [k] 档自动错开量(px):0、−6、+6、−12、+12 …
|
||||
///
|
||||
/// 同一走线分组内第二条起依次错开,避免多条依赖完全重叠。
|
||||
double staggerOffset(int k) {
|
||||
if (k <= 0) return 0;
|
||||
return (k.isOdd ? -1 : 1) * ((k + 1) ~/ 2) * 6.0;
|
||||
}
|
||||
|
||||
/// 拖拽调整走线时的移动轴(走线的“法线”方向)。
|
||||
///
|
||||
/// - [vertical]:上下拖动——平移水平走线段(条形 / 流程图的常见形态);
|
||||
/// - [horizontal]:左右拖动——平移纵向走线走廊(跨行绕行走廊 / 同层绕行)。
|
||||
enum RouteAxis { vertical, horizontal }
|
||||
|
||||
/// 拖拽走线时可用的最大手动偏移(px,双向)。
|
||||
const double kMaxRouteOffset = 200;
|
||||
|
||||
// ===================== 条形视图 =====================
|
||||
|
||||
/// 条形视图的一条依赖走线。
|
||||
class BarDepRoute {
|
||||
/// 构造。
|
||||
BarDepRoute(this.dep, this.points, this.arrowTip, this.arrowDir, this.chipCenter, this.axis,
|
||||
{this.chipRun = double.infinity,
|
||||
this.chipRunMargin = 0,
|
||||
this.chipAltAnchor = Offset.zero,
|
||||
this.junctionOnly = false});
|
||||
|
||||
/// 对应依赖。
|
||||
final Dependency dep;
|
||||
/// 折线顶点(含起点与箭头端点)。
|
||||
final List<Offset> points;
|
||||
/// 箭头端点。
|
||||
final Offset arrowTip;
|
||||
/// 箭头方向(分量式)。
|
||||
final Offset arrowDir;
|
||||
/// 标签中心(默认位置,避让前)。
|
||||
final Offset chipCenter;
|
||||
/// 拖拽方向:vertical = 上下拖动平移横线;horizontal = 左右拖动平移纵向走廊。
|
||||
final RouteAxis axis;
|
||||
|
||||
/// 标签挂钩的水平行程长度(跑长时用于判断是否需要把标签移到箭头外侧)。
|
||||
///
|
||||
/// 默认 [double.infinity] 表示不做外移判断(跨行走廊等)。
|
||||
final double chipRun;
|
||||
|
||||
/// 外移判断余量:行程 `< 标签宽 + 余量` 时把标签移到 [chipAltAnchor]。
|
||||
final double chipRunMargin;
|
||||
|
||||
/// 外移时标签的锚点(绘制端会再加半个标签宽)。
|
||||
final Offset chipAltAnchor;
|
||||
|
||||
/// 动作紧贴时只显示连接点标签,隐藏连线与箭头(由绘制层处理)。
|
||||
final bool junctionOnly;
|
||||
|
||||
/// 依赖键 `from->to`。
|
||||
String get key => '${dep.fromId}->${dep.toId}';
|
||||
}
|
||||
|
||||
/// 条形依赖在动作条一端的锚点。
|
||||
///
|
||||
/// [point] 为线条端点(目标端为箭头尖端);[dir] 为箭头进入方向(源端为
|
||||
/// 离开方向);[corner] 表示端点已退到条块的上/下角;[vSide] 为角点所在
|
||||
/// 一侧(-1 上、+1 下)。
|
||||
class _BarEnd {
|
||||
const _BarEnd(this.point, this.dir, this.corner, this.vSide);
|
||||
|
||||
final Offset point;
|
||||
final Offset dir;
|
||||
final bool corner;
|
||||
final int vSide;
|
||||
}
|
||||
|
||||
/// 判断端点前的水平通道是否被其它动作条遮挡(宽 8px,条高中间 ±3px)。
|
||||
///
|
||||
/// 遮挡时把端点退到端部的上/下角,保证线条从角上引出而不是贴着邻条走。
|
||||
bool _barEndBlocked(double edge, double outward, double centerY, Iterable<Rect> obstacles) {
|
||||
const double clearance = 9;
|
||||
final Rect probe = Rect.fromLTRB(
|
||||
math.min(edge, edge + outward * clearance),
|
||||
centerY - 3,
|
||||
math.max(edge, edge + outward * clearance),
|
||||
centerY + 3,
|
||||
);
|
||||
for (final Rect r in obstacles) {
|
||||
if (r.overlaps(probe)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 源端锚点:默认取条块左/右端点中心;端部有遮挡时取朝向目标一侧的上下角。
|
||||
_BarEnd _startEnd(Rect bar, int side, int cornerSide, Iterable<Rect> obstacles,
|
||||
{bool forceCorner = false}) {
|
||||
final double edge = side > 0 ? bar.right : bar.left;
|
||||
final double outward = side > 0 ? 1 : -1;
|
||||
final double cy = bar.center.dy;
|
||||
if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) {
|
||||
return _BarEnd(Offset(edge + outward * 2, cy), Offset(outward, 0), false, 0);
|
||||
}
|
||||
final int vs = cornerSide == 0 ? 1 : cornerSide;
|
||||
final double y = vs > 0 ? bar.bottom - 2 : bar.top + 2;
|
||||
return _BarEnd(Offset(edge + outward * 1.5, y), Offset(0, vs.toDouble()), true, vs);
|
||||
}
|
||||
|
||||
/// 目标端锚点:默认取条块左/右端点中心(箭头停在端点外 2px);端部有遮挡
|
||||
/// 时取朝向源条一侧的上下角,箭头从角外垂直指向条块。
|
||||
_BarEnd _targetEnd(Rect bar, int side, int cornerSide, Iterable<Rect> obstacles,
|
||||
{bool forceCorner = false}) {
|
||||
final double edge = side > 0 ? bar.right : bar.left;
|
||||
final double outward = side > 0 ? 1 : -1;
|
||||
final double cy = bar.center.dy;
|
||||
if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) {
|
||||
return _BarEnd(Offset(edge + outward * 2, cy), Offset(-outward, 0), false, 0);
|
||||
}
|
||||
final int vs = cornerSide == 0 ? 1 : cornerSide;
|
||||
final double y = vs > 0 ? bar.bottom + 2 : bar.top - 2;
|
||||
return _BarEnd(
|
||||
Offset(edge + outward * 1.5, y), Offset(0, -vs.toDouble()), true, vs);
|
||||
}
|
||||
|
||||
/// 计算条形视图的全部依赖走线(含自动错开与手动偏移)。
|
||||
///
|
||||
/// 端点规则(FS / SS / FF / SF 均按语义取条块前端或后端):
|
||||
/// 1. 默认从条块的左/右端点中心引出;FS/FF 从后端(右端)出发,
|
||||
/// SS/SF 从前端(左端)出发;目标端按 FS/SS 取前端、FF/SF 取后端;
|
||||
/// 2. 当端点临近被其它动作条遮挡(或同泳道走线会穿过条块)时,退到该端部
|
||||
/// 的上/下角引出,再从角外绕行。
|
||||
///
|
||||
/// 走线分三种情形:同泳道(水平线或上下绕行)、相邻泳道(Z 形)、跨多行
|
||||
/// (外侧纵向走廊);同组自动错开 + [Dependency.routeOffset] 手动偏移。
|
||||
List<BarDepRoute> buildBarDepRoutes(Project project, BarLayout layout) {
|
||||
final Map<String, Rect> rectById = <String, Rect>{
|
||||
for (final Action a in project.actions) a.id: layout.rectFor(a),
|
||||
};
|
||||
final Map<String, int> laneIndex = <String, int>{
|
||||
for (final Action a in project.actions) a.id: layout.laneIndexOf(a.layer),
|
||||
};
|
||||
final Map<String, int> seen = <String, int>{};
|
||||
final List<BarDepRoute> out = <BarDepRoute>[];
|
||||
for (final Action to in layout.ordered) {
|
||||
for (final Dependency d in to.deps) {
|
||||
final Action? from = project.actionById(d.fromId);
|
||||
if (from == null) continue;
|
||||
final Rect? ra = rectById[from.id];
|
||||
final Rect? rb = rectById[to.id];
|
||||
if (ra == null || rb == null) continue;
|
||||
// 端点遮挡检查要包含“对方条块”:动作前后贴紧时,源端被目标条块
|
||||
// 挡住、目标端被源条块挡住,此时应退到上下角并从条块外侧绕行。
|
||||
final List<Rect> obstaclesForStart = <Rect>[
|
||||
for (final MapEntry<String, Rect> e in rectById.entries)
|
||||
if (e.key != from.id) e.value,
|
||||
];
|
||||
final List<Rect> obstaclesForEnd = <Rect>[
|
||||
for (final MapEntry<String, Rect> e in rectById.entries)
|
||||
if (e.key != to.id) e.value,
|
||||
];
|
||||
final int ia = laneIndex[from.id] ?? 0;
|
||||
final int ib = laneIndex[to.id] ?? 0;
|
||||
const double barHalf = BarLayout.barH / 2;
|
||||
final double sy = ra.center.dy;
|
||||
final double ty = rb.center.dy;
|
||||
final int dirY = ty > sy ? 1 : (ty < sy ? -1 : 0);
|
||||
final bool sameRow = dirY == 0;
|
||||
final bool adjacentLane = (ib - ia).abs() <= 1;
|
||||
// 端点语义:FS/FF 从后端出发,SS/SF 从前端出发;目标端 FS/SS 为前端,
|
||||
// FF/SF 为后端。
|
||||
final int fromSide =
|
||||
(d.type == DepType.fs || d.type == DepType.ff) ? 1 : -1;
|
||||
final int toSide =
|
||||
(d.type == DepType.fs || d.type == DepType.ss) ? -1 : 1;
|
||||
final String groupKey =
|
||||
sameRow ? 'S$ia' : (adjacentLane ? 'A$ia→$ib' : 'M$ia→$ib');
|
||||
final int k = seen.putIfAbsent(groupKey, () => 0);
|
||||
seen[groupKey] = k + 1;
|
||||
final double stagger = staggerOffset(k);
|
||||
// 同泳道无上下方向时,按走线偏移/错开量决定绕上还是绕下。
|
||||
final int cornerSide = dirY != 0
|
||||
? dirY
|
||||
: (stagger + d.routeOffset >= 0 ? 1 : -1);
|
||||
|
||||
if (sameRow) {
|
||||
// 前后动作紧贴(首尾相接)时,连线/箭头会挤在接缝处且不可读:
|
||||
// 隐藏走线,只在接缝处显示依赖标签。
|
||||
final bool tight =
|
||||
(rb.left - ra.right).abs() <= 4 || (ra.left - rb.right).abs() <= 4;
|
||||
if (tight) {
|
||||
final bool toRight = rb.center.dx >= ra.center.dx;
|
||||
final double junctionX =
|
||||
toRight ? (ra.right + rb.left) / 2 : (ra.left + rb.right) / 2;
|
||||
out.add(BarDepRoute(
|
||||
d,
|
||||
const <Offset>[],
|
||||
Offset.zero,
|
||||
const Offset(1, 0),
|
||||
Offset(junctionX, ra.top - 10),
|
||||
RouteAxis.vertical,
|
||||
junctionOnly: true,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
// 同泳道:默认一条水平线;端点被遮挡或语义端点背向对方时,从
|
||||
// 端部上/下角绕行(避免线穿过两个条块)。
|
||||
final bool sourceFaces =
|
||||
(rb.center.dx - ra.center.dx) * fromSide >= 0;
|
||||
final bool targetFaces =
|
||||
(ra.center.dx - rb.center.dx) * toSide >= 0;
|
||||
_BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart);
|
||||
_BarEnd t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd);
|
||||
final bool straight = !s.corner && !t.corner && sourceFaces && targetFaces;
|
||||
if (straight) {
|
||||
final double y = sy + stagger + d.routeOffset;
|
||||
final Offset sp = Offset(s.point.dx, y);
|
||||
final Offset tp = Offset(t.point.dx, y);
|
||||
out.add(BarDepRoute(
|
||||
d,
|
||||
<Offset>[sp, tp],
|
||||
tp,
|
||||
t.dir,
|
||||
Offset((sp.dx + tp.dx) / 2, y - (barHalf + 9)),
|
||||
RouteAxis.vertical,
|
||||
chipRun: (tp.dx - sp.dx).abs(),
|
||||
chipRunMargin: 8,
|
||||
chipAltAnchor: Offset(tp.dx + 6, y - (barHalf + 9)),
|
||||
));
|
||||
} else {
|
||||
// 只对背向对方 / 被遮挡的那一端退角,另一端仍从端点中心进出。
|
||||
if (!sourceFaces || s.corner) {
|
||||
s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart, forceCorner: true);
|
||||
}
|
||||
if (!targetFaces || t.corner) {
|
||||
t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd, forceCorner: true);
|
||||
}
|
||||
final int side = s.corner
|
||||
? s.vSide
|
||||
: (t.corner ? t.vSide : cornerSide);
|
||||
double runY = sy + side * (barHalf + 10) + stagger + d.routeOffset;
|
||||
runY = side > 0
|
||||
? math.max(runY, ra.bottom + 6)
|
||||
: math.min(runY, ra.top - 6);
|
||||
final double tx =
|
||||
t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10;
|
||||
final List<Offset> pts = <Offset>[s.point, Offset(s.point.dx, runY), Offset(tx, runY)];
|
||||
if (t.corner) {
|
||||
pts.add(t.point);
|
||||
} else {
|
||||
pts.add(Offset(tx, t.point.dy));
|
||||
pts.add(t.point);
|
||||
}
|
||||
out.add(BarDepRoute(
|
||||
d,
|
||||
pts,
|
||||
t.point,
|
||||
t.dir,
|
||||
// 绕行线在条块外侧,标签也放到线外侧,避免压住动作条。
|
||||
Offset((ra.center.dx + rb.center.dx) / 2, runY + side * (barHalf + 9)),
|
||||
RouteAxis.vertical,
|
||||
chipRun: (tx - s.point.dx).abs(),
|
||||
chipRunMargin: 8,
|
||||
chipAltAnchor: Offset(
|
||||
t.point.dx + 6,
|
||||
t.corner ? t.point.dy + side * 10 : t.point.dy - 12,
|
||||
),
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
final _BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart);
|
||||
final _BarEnd t = _targetEnd(rb, toSide, -cornerSide, obstaclesForEnd);
|
||||
if (adjacentLane) {
|
||||
// 相邻泳道:端部引出后在两泳道之间的中线走水平段;同组错开 + 手动偏移。
|
||||
final double mid = (sy + ty) / 2 + stagger + d.routeOffset;
|
||||
final List<Offset> pts = <Offset>[s.point];
|
||||
if (!s.corner) {
|
||||
final double sx2 = s.point.dx + s.dir.dx * 10;
|
||||
pts.add(Offset(sx2, s.point.dy));
|
||||
pts.add(Offset(sx2, mid));
|
||||
} else {
|
||||
pts.add(Offset(s.point.dx, mid));
|
||||
}
|
||||
final double tx2 = t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10;
|
||||
pts.add(Offset(tx2, mid));
|
||||
if (t.corner) {
|
||||
pts.add(t.point);
|
||||
} else {
|
||||
pts.add(Offset(tx2, t.point.dy));
|
||||
pts.add(t.point);
|
||||
}
|
||||
out.add(BarDepRoute(
|
||||
d,
|
||||
pts,
|
||||
t.point,
|
||||
t.dir,
|
||||
Offset((ra.center.dx + rb.center.dx) / 2, mid),
|
||||
RouteAxis.vertical,
|
||||
chipRun: (tx2 - s.point.dx).abs(),
|
||||
chipRunMargin: 10,
|
||||
chipAltAnchor: Offset(
|
||||
t.point.dx + 6,
|
||||
t.point.dy + (t.corner ? t.dir.dy * 10 : -12),
|
||||
),
|
||||
));
|
||||
} else {
|
||||
// 跨多行:扫描区间内所有条块边界,在外侧选一条纵向走廊;同组按
|
||||
// ±12px 错开走廊,手动偏移作用于走廊横向位置。
|
||||
final double sx = s.point.dx;
|
||||
final double tx = t.point.dx;
|
||||
double maxRight = 0;
|
||||
double minLeft = double.infinity;
|
||||
final List<int> lanes = layout.lanes;
|
||||
for (int r = math.min(ia, ib) + 1; r < math.max(ia, ib); r++) {
|
||||
if (r < 0 || r >= lanes.length) continue;
|
||||
for (final Action aa in layout.actionsInLane(lanes[r])) {
|
||||
final Rect rr = layout.rectFor(aa);
|
||||
maxRight = math.max(maxRight, rr.right);
|
||||
minLeft = math.min(minLeft, rr.left);
|
||||
}
|
||||
}
|
||||
final double shift = stagger * 2 + d.routeOffset;
|
||||
double lane = math.max(math.max(sx, tx), maxRight) + 28 + shift;
|
||||
if (lane > layout.plotRight - 16) {
|
||||
lane = math.min(math.min(sx, tx), minLeft) - 28 - shift;
|
||||
}
|
||||
final double srcGapY = sy + dirY * (barHalf + 14);
|
||||
final double gapY = ty - dirY * (barHalf + 6);
|
||||
final List<Offset> pts = <Offset>[s.point];
|
||||
if (!s.corner) {
|
||||
final double sx2 = s.point.dx + s.dir.dx * 10;
|
||||
pts.add(Offset(sx2, s.point.dy));
|
||||
pts.add(Offset(sx2, srcGapY));
|
||||
} else {
|
||||
pts.add(Offset(s.point.dx, srcGapY));
|
||||
}
|
||||
pts.add(Offset(lane, srcGapY));
|
||||
pts.add(Offset(lane, gapY));
|
||||
if (t.corner) {
|
||||
pts.add(Offset(t.point.dx, gapY));
|
||||
pts.add(t.point);
|
||||
} else {
|
||||
final double tx2 = t.point.dx - t.dir.dx * 10;
|
||||
pts.add(Offset(tx2, gapY));
|
||||
pts.add(Offset(tx2, t.point.dy));
|
||||
pts.add(t.point);
|
||||
}
|
||||
out.add(BarDepRoute(
|
||||
d,
|
||||
pts,
|
||||
t.point,
|
||||
t.dir,
|
||||
Offset((lane + tx) / 2, gapY - (barHalf + 1)),
|
||||
RouteAxis.horizontal,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 命中条形依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。
|
||||
BarDepRoute? hitBarDep(List<BarDepRoute> routes, Offset p, double maxDist) {
|
||||
BarDepRoute? best;
|
||||
double bestD = maxDist;
|
||||
for (final BarDepRoute r in routes) {
|
||||
final double d = distanceToPolyline(r.points, p);
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = r;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ===================== 圆周视图 =====================
|
||||
|
||||
/// 圆周视图的一条依赖走线(径向 → 圆弧 → 径向)。
|
||||
class ArcDepRoute {
|
||||
/// 构造。
|
||||
ArcDepRoute(this.dep, this.center, this.rA, this.rB, this.rC, this.rTip, this.aEnd, this.aStart,
|
||||
this.degenerate, this.cw, this.large, this.chipR, this.chipDeg,
|
||||
{this.junctionOnly = false});
|
||||
|
||||
/// 对应依赖。
|
||||
final Dependency dep;
|
||||
/// 圆心。
|
||||
final Offset center;
|
||||
/// 源环半径。
|
||||
final double rA;
|
||||
/// 目标环半径。
|
||||
final double rB;
|
||||
/// 绕行半径(自动错开 + 手动偏移作用于此)。
|
||||
final double rC;
|
||||
/// 箭头落点半径。
|
||||
final double rTip;
|
||||
/// 源弧末端角(度)。
|
||||
final double aEnd;
|
||||
/// 目标弧起点角(度)。
|
||||
final double aStart;
|
||||
/// 起止角几乎重合(退化)时改画短箭头。
|
||||
final bool degenerate;
|
||||
/// 圆弧是否顺时针。
|
||||
final bool cw;
|
||||
/// 是否大弧。
|
||||
final int large;
|
||||
/// 标签极径。
|
||||
final double chipR;
|
||||
/// 标签极角。
|
||||
final double chipDeg;
|
||||
|
||||
/// 动作紧贴时只显示连接点标签,隐藏圆弧与箭头。
|
||||
final bool junctionOnly;
|
||||
|
||||
/// 依赖键 `from->to`。
|
||||
String get key => '${dep.fromId}->${dep.toId}';
|
||||
|
||||
/// 起点(源环上)。
|
||||
Offset get p0 => polar(center, rA, aEnd);
|
||||
/// 绕行起点(半径 rC 上)。
|
||||
Offset get p1 => polar(center, rC, aEnd);
|
||||
/// 绕行终点(半径 rC 上)。
|
||||
Offset get p2 => polar(center, rC, aStart);
|
||||
/// 箭头端点。
|
||||
Offset get p3 => polar(center, rTip, aStart);
|
||||
/// 退化短箭头的起点。
|
||||
Offset get q0 => polar(center, rTip - (rTip > rB ? 28 : -28), aStart);
|
||||
|
||||
/// 生成绘制路径(绘制与命中测试同源)。
|
||||
Path buildPath() {
|
||||
final Path p = Path();
|
||||
if (degenerate) {
|
||||
p.moveTo(q0.dx, q0.dy);
|
||||
p.lineTo(p3.dx, p3.dy);
|
||||
return p;
|
||||
}
|
||||
final Offset a0 = p0;
|
||||
final Offset a1 = p1;
|
||||
final Offset a2 = p2;
|
||||
final Offset a3 = p3;
|
||||
p.moveTo(a0.dx, a0.dy);
|
||||
p.lineTo(a1.dx, a1.dy);
|
||||
p.arcToPoint(a2, radius: Radius.circular(rC), largeArc: large == 1, clockwise: cw);
|
||||
p.lineTo(a3.dx, a3.dy);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// 箭头方向(分量式)。
|
||||
Offset get tipDir => degenerate ? (p3 - q0) : (p3 - p2);
|
||||
}
|
||||
|
||||
/// 计算圆周视图的全部依赖走线(含自动错开与手动偏移)。
|
||||
List<ArcDepRoute> buildArcDepRoutes(Project project, CircularLayout layout) {
|
||||
final Map<String, int> seen = <String, int>{};
|
||||
final List<ArcDepRoute> out = <ArcDepRoute>[];
|
||||
for (final Action to in project.actions) {
|
||||
for (final Dependency d in to.deps) {
|
||||
final Action? a = project.actionById(d.fromId);
|
||||
final Action? b = project.actionById(d.toId);
|
||||
if (a == null || b == null) continue;
|
||||
final double rA = layout.radiusFor(a.layer, layout.slotOf(a));
|
||||
final double rB = layout.radiusFor(b.layer, layout.slotOf(b));
|
||||
final double aEnd = math.min(a.endAngle, 360);
|
||||
final double aStart = b.startAngle;
|
||||
// 层差大于 1 时从最外圈绕行,避免穿过中间层弧线。
|
||||
final bool skip = (a.layer - b.layer).abs() > 1;
|
||||
final String groupKey = '${skip ? 'K' : 'N'}${a.layer}→${b.layer}';
|
||||
final int k = seen.putIfAbsent(groupKey, () => 0);
|
||||
seen[groupKey] = k + 1;
|
||||
// 同一环 / 相邻环的依赖如果画在环半径上会压住动作弧:把绕行半径
|
||||
// 放到环间空隙(同一环时即为外侧空隙),标签也跟随到空隙里。
|
||||
final double ringGap = math.max(layout.pitch - layout.th, 8);
|
||||
final bool sameRing = (rA - rB).abs() < layout.pitch * 0.35;
|
||||
final double baseC = skip
|
||||
? layout.rMax + 24
|
||||
: (sameRing ? rA + ringGap * 0.55 : (rA + rB) / 2);
|
||||
// 自动错开(步长 9px)+ 手动径向偏移(圆周视图的“法线”即半径方向)。
|
||||
double rC = baseC + staggerOffset(k) * 1.5 + d.routeOffset;
|
||||
rC = rC.clamp(18.0, layout.rMax + 170);
|
||||
final double rTip = rC < rB ? rB - layout.th / 2 - 4 : rB + layout.th / 2 + 4;
|
||||
final bool cw = aStart >= aEnd;
|
||||
final int large = (aStart - aEnd).abs() > 180 ? 1 : 0;
|
||||
final bool degenerate = (aStart - aEnd).abs() < 0.5;
|
||||
final bool junctionOnly = (aStart - aEnd).abs() <= 2.0;
|
||||
final double chipDeg = degenerate ? aStart : (aEnd + aStart) / 2;
|
||||
final double chipR = rC;
|
||||
out.add(ArcDepRoute(
|
||||
d,
|
||||
layout.center,
|
||||
rA,
|
||||
rB,
|
||||
rC,
|
||||
rTip,
|
||||
aEnd,
|
||||
aStart,
|
||||
degenerate,
|
||||
cw,
|
||||
large,
|
||||
chipR,
|
||||
chipDeg,
|
||||
junctionOnly: junctionOnly));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 命中圆周依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。
|
||||
ArcDepRoute? hitArcDep(List<ArcDepRoute> routes, Offset p, double maxDist) {
|
||||
ArcDepRoute? best;
|
||||
double bestD = maxDist;
|
||||
for (final ArcDepRoute r in routes) {
|
||||
final double d = distanceToPath(r.buildPath(), p);
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = r;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
/// 流程图布局:把时序图中的动作与依赖转换为纵向流程图(泳道 = 轨道)。
|
||||
///
|
||||
/// 产品规则(1.3 大版本,经需求确认):
|
||||
/// - 每个动作 = 一个工序节点,节点内显示「序号. 名称」与时长(含工位);
|
||||
/// - 泳道 = 动作的轨道(layer),横向并列,一眼看出哪些步骤在并行;
|
||||
/// - 依赖:FS 实线、SS 虚线(带偏移角标注);关键路径加粗高亮;
|
||||
/// - 自动补「开始 / 结束」节点:开始 → 时间最早的动作(动作1),
|
||||
/// 其余无前置的动作作为并行起点同样从开始引出;无后继的动作 → 结束;
|
||||
/// - 只读视图:交互仅支持点选联动与平移缩放,内容修改请回时序图。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'dep_routes.dart';
|
||||
import 'layout.dart';
|
||||
|
||||
/// 流程图节点(动作节点或开始 / 结束节点)。
|
||||
class FlowNode {
|
||||
/// 动作节点。
|
||||
FlowNode.action(Action this.action)
|
||||
: id = action.id,
|
||||
isStart = false,
|
||||
isEnd = false;
|
||||
|
||||
/// 开始节点。
|
||||
FlowNode.start()
|
||||
: action = null,
|
||||
id = startId,
|
||||
isStart = true,
|
||||
isEnd = false;
|
||||
|
||||
/// 结束节点。
|
||||
FlowNode.end()
|
||||
: action = null,
|
||||
id = endId,
|
||||
isStart = false,
|
||||
isEnd = true;
|
||||
|
||||
/// 开始节点的保留 id。
|
||||
static const String startId = '__flow_start__';
|
||||
/// 结束节点的保留 id。
|
||||
static const String endId = '__flow_end__';
|
||||
|
||||
/// 对应动作;开始 / 结束节点为 null。
|
||||
final Action? action;
|
||||
/// 节点 id(开始 / 结束使用保留 id)。
|
||||
final String id;
|
||||
/// 是否开始节点。
|
||||
final bool isStart;
|
||||
/// 是否结束节点。
|
||||
final bool isEnd;
|
||||
|
||||
/// 所属泳道(轨道号 layer)。
|
||||
int lane = 0;
|
||||
/// 纵向层级(0 = 开始节点所在层)。
|
||||
int rank = 0;
|
||||
/// 布局后的节点矩形(逻辑坐标)。
|
||||
Rect rect = Rect.zero;
|
||||
/// 主标题(动作节点为「序号. 名称」)。
|
||||
String title = '';
|
||||
/// 副标题(时长 · 工位)。
|
||||
String subtitle = '';
|
||||
}
|
||||
|
||||
/// 流程图连线。
|
||||
class FlowEdge {
|
||||
/// 构造;[type] 为依赖类型(开始 / 结束相关连线为 null)。
|
||||
FlowEdge(this.fromId, this.toId,
|
||||
{this.type, this.offset = 0, this.critical = false});
|
||||
|
||||
/// 起点节点 id。
|
||||
final String fromId;
|
||||
/// 终点节点 id。
|
||||
final String toId;
|
||||
/// 依赖类型;null 表示开始 / 结束的流程连线。
|
||||
final DepType? type;
|
||||
/// SS 等依赖的偏移角(度)。
|
||||
final double offset;
|
||||
/// 是否属于关键路径。
|
||||
final bool critical;
|
||||
}
|
||||
|
||||
/// 连线走线结果(供画布绘制 / SVG / drawio 导出共用)。
|
||||
class FlowEdgeRoute {
|
||||
/// 构造。
|
||||
FlowEdgeRoute(this.edge, this.points, this.tip, this.dir, this.labelAt, this.axis);
|
||||
|
||||
/// 对应的连线。
|
||||
final FlowEdge edge;
|
||||
/// 折线顶点序列(含起点与箭头端点)。
|
||||
final List<Offset> points;
|
||||
/// 箭头端点。
|
||||
final Offset tip;
|
||||
/// 箭头方向(分量式单位方向)。
|
||||
final Offset dir;
|
||||
/// FS / SS 标签位置。
|
||||
final Offset labelAt;
|
||||
/// 拖拽调整走线的方向:向下流为竖直(上下拖动),同层绕行为水平(左右拖动)。
|
||||
final RouteAxis axis;
|
||||
|
||||
/// 依赖键 `from->to`。
|
||||
String get key => '${edge.fromId}->${edge.toId}';
|
||||
|
||||
/// 是否虚线(SS 依赖)。
|
||||
bool get dashed => edge.type == DepType.ss;
|
||||
}
|
||||
|
||||
/// 相位分区在流程图中的纵向跨度(左侧阶段栏用)。
|
||||
class FlowPhaseSpan {
|
||||
/// 构造。
|
||||
FlowPhaseSpan(this.zone, this.rankTop, this.rankBottom);
|
||||
|
||||
/// 相位分区。
|
||||
final PhaseZone zone;
|
||||
/// 覆盖的最上层级。
|
||||
final int rankTop;
|
||||
/// 覆盖的最下层级。
|
||||
final int rankBottom;
|
||||
/// 与其它阶段纵向重叠时的横向错位档位(0 起,每档向右 [FlowLayout.railStep] px,
|
||||
/// 仅轻微错开以免重叠处看不清;纵向仍严格对齐流程行)。
|
||||
int slot = 0;
|
||||
}
|
||||
|
||||
/// 流程图布局结果:节点、连线、泳道与内容范围。
|
||||
class FlowLayout {
|
||||
/// 构造并从 [project] 生成流程图。
|
||||
///
|
||||
/// [criticalActions] / [criticalDeps] 用于标记关键路径(与其它视图一致)。
|
||||
FlowLayout(
|
||||
this.project, {
|
||||
this.criticalActions = const <String>{},
|
||||
this.criticalDeps = const <String>{},
|
||||
}) {
|
||||
_build();
|
||||
}
|
||||
|
||||
/// 数据源项目。
|
||||
final Project project;
|
||||
/// 关键路径上的动作 id。
|
||||
final Set<String> criticalActions;
|
||||
/// 关键路径上的依赖(`from->to`)。
|
||||
final Set<String> criticalDeps;
|
||||
|
||||
/// 动作节点尺寸(流程图与条形 / 圆周不同:横向更宽,给连线与箭头留出空间)。
|
||||
static const double nodeW = 216;
|
||||
/// 动作节点高度。
|
||||
static const double nodeH = 58;
|
||||
/// 开始 / 结束节点尺寸。
|
||||
static const double capW = 116;
|
||||
/// 开始 / 结束节点高度。
|
||||
static const double capH = 46;
|
||||
/// 层级(纵向)间距。
|
||||
static const double rankGap = 48;
|
||||
/// 泳道(横向)间距(加大给扇出连线让位,避免看起来拥挤)。
|
||||
static const double laneGap = 64;
|
||||
/// 左边距(左侧留出相位阶段栏 + 泳道间距)。
|
||||
static const double marginX = 150;
|
||||
/// 上边距(含泳道标题)。
|
||||
static const double marginY = 92;
|
||||
/// 相位阶段栏起始 x。
|
||||
static const double railX = 24;
|
||||
/// 相位竖带宽度(窄带,相当于把条形视图的相位色带竖起来)。
|
||||
static const double railW = 24;
|
||||
/// 相位台阶错位宽度(重叠的分区逐级向右错开,形成台阶)。
|
||||
static const double railStep = 24;
|
||||
|
||||
/// 全部节点(按创建顺序:动作 → 开始 → 结束)。
|
||||
final List<FlowNode> nodes = <FlowNode>[];
|
||||
/// 全部连线。
|
||||
final List<FlowEdge> edges = <FlowEdge>[];
|
||||
/// 泳道列表(轨道号,升序)。
|
||||
List<int> lanes = <int>[];
|
||||
/// 相位分区跨度(左侧阶段栏,按项目分区顺序)。
|
||||
final List<FlowPhaseSpan> spans = <FlowPhaseSpan>[];
|
||||
/// 连线走线结果(画布 / SVG / drawio 导出共用)。
|
||||
final List<FlowEdgeRoute> routes = <FlowEdgeRoute>[];
|
||||
/// 内容范围(所有节点矩形并集再外扩,供适应视图使用)。
|
||||
Rect bounds = Rect.zero;
|
||||
|
||||
/// 泳道内两个槽位之间的横向间距(留出依赖连线的走线空间)。
|
||||
static const double slotGap = 26;
|
||||
|
||||
/// 各泳道左边缘 x(放置完成后按内容自适应填充)。
|
||||
final List<double> laneStarts = <double>[];
|
||||
|
||||
/// 各泳道宽度(基础 = 槽位数,放置后按内容自动加宽)。
|
||||
final List<double> laneWidths = <double>[];
|
||||
|
||||
/// 第 [li] 条泳道的宽度(优先取内容自适应结果;未计算时按槽位数)。
|
||||
double laneWidth(int li) {
|
||||
if (li >= 0 && li < laneWidths.length) return laneWidths[li];
|
||||
if (li < 0 || li >= lanes.length) return nodeW;
|
||||
final int s = project.slotsOf(lanes[li]);
|
||||
return s * nodeW + (s - 1) * slotGap;
|
||||
}
|
||||
|
||||
/// 第 [li] 条泳道左边缘 x(优先取内容自适应结果,其次按槽位宽度累加)。
|
||||
double laneStartX(int li) {
|
||||
if (li >= 0 && li < laneStarts.length) return laneStarts[li];
|
||||
double x = marginX;
|
||||
for (int i = 0; i < li && i < lanes.length; i++) {
|
||||
x += laneWidth(i) + laneGap;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// 第 [li] 条泳道第 [slot] 列的节点中心 x(槽位钳制到有效范围)。
|
||||
double slotCenterX(int li, int slot) {
|
||||
final int s = (li >= 0 && li < lanes.length) ? project.slotsOf(lanes[li]) : 1;
|
||||
final int k = slot < 0 ? 0 : (slot >= s ? s - 1 : slot);
|
||||
return laneStartX(li) + k * (nodeW + slotGap) + nodeW / 2;
|
||||
}
|
||||
|
||||
/// 按 id 查找节点。
|
||||
FlowNode? nodeById(String id) {
|
||||
for (final FlowNode n in nodes) {
|
||||
if (n.id == id) return n;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 命中测试:返回坐标 [p] 下的动作(开始 / 结束节点不返回)。
|
||||
Action? hitTest(Offset p) {
|
||||
for (final FlowNode n in nodes) {
|
||||
if (n.action != null && n.rect.contains(p)) return n.action;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 构建节点、连线并完成布局。
|
||||
void _build() {
|
||||
lanes = project.renderLanes;
|
||||
final Map<String, FlowNode> byId = <String, FlowNode>{};
|
||||
|
||||
// 1) 动作节点(序号与条形视图一致:项目动作列表顺序 + 1)。
|
||||
for (int i = 0; i < project.actions.length; i++) {
|
||||
final Action a = project.actions[i];
|
||||
final String dur = tfmt(a.durationAngle / 360 * project.cycle.durationMs, project.units);
|
||||
final String st = project.stationById(a.stationId)?.name ?? a.stationId;
|
||||
final FlowNode n = FlowNode.action(a)
|
||||
..lane = a.layer
|
||||
..title = '${i + 1}. ${a.name}'
|
||||
..subtitle = '$dur · $st';
|
||||
nodes.add(n);
|
||||
byId[n.id] = n;
|
||||
}
|
||||
if (nodes.isEmpty) {
|
||||
bounds = Rect.zero;
|
||||
return;
|
||||
}
|
||||
|
||||
// 2) 依赖连线(FS 实线 / SS 虚线等)。
|
||||
for (final Action to in project.actions) {
|
||||
for (final Dependency d in to.deps) {
|
||||
if (d.fromId == to.id || !byId.containsKey(d.fromId)) continue;
|
||||
edges.add(FlowEdge(d.fromId, to.id,
|
||||
type: d.type,
|
||||
offset: d.offsetAngle,
|
||||
critical: criticalDeps.contains('${d.fromId}->${to.id}')));
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 开始 / 结束节点。
|
||||
// 「动作1」= 时间上最早开始的动作(并列时取 id 较小者)。
|
||||
final List<Action> ordered = List<Action>.of(project.actions)
|
||||
..sort((Action a, Action b) {
|
||||
final int c = a.startAngle.compareTo(b.startAngle);
|
||||
return c != 0 ? c : a.id.compareTo(b.id);
|
||||
});
|
||||
final Action first = ordered.first;
|
||||
Action last = ordered.first;
|
||||
for (final Action a in ordered) {
|
||||
if (a.endAngle > last.endAngle) last = a;
|
||||
}
|
||||
final FlowNode start = FlowNode.start()..lane = first.layer;
|
||||
final FlowNode end = FlowNode.end()..lane = last.layer;
|
||||
start.title = '开始';
|
||||
end.title = '结束';
|
||||
nodes.add(start);
|
||||
nodes.add(end);
|
||||
byId[start.id] = start;
|
||||
byId[end.id] = end;
|
||||
|
||||
final Set<String> hasPred = <String>{for (final FlowEdge e in edges) e.toId};
|
||||
final Set<String> hasSucc = <String>{for (final FlowEdge e in edges) e.fromId};
|
||||
// 开始 → 无前置的动作(含「动作1」;其它无前置动作视为并行起点)。
|
||||
for (final Action a in project.actions) {
|
||||
if (!hasPred.contains(a.id)) edges.add(FlowEdge(start.id, a.id));
|
||||
}
|
||||
// 无后继的动作 → 结束。
|
||||
for (final Action a in project.actions) {
|
||||
if (!hasSucc.contains(a.id)) edges.add(FlowEdge(a.id, end.id));
|
||||
}
|
||||
|
||||
// 4) 层级:从开始节点做最长路径(带迭代上限,兼容异常环)。
|
||||
final Map<String, int> rank = <String, int>{for (final FlowNode n in nodes) n.id: 0};
|
||||
bool changed = true;
|
||||
int guard = 0;
|
||||
while (changed && guard < nodes.length * 4 + 8) {
|
||||
changed = false;
|
||||
guard++;
|
||||
for (final FlowEdge e in edges) {
|
||||
final int nr = (rank[e.fromId] ?? 0) + 1;
|
||||
if (nr > (rank[e.toId] ?? 0)) {
|
||||
rank[e.toId] = nr;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (final FlowNode n in nodes) {
|
||||
n.rank = rank[n.id] ?? 0;
|
||||
}
|
||||
|
||||
// 5) 坐标:泳道 → 横列(居中于列),层级 → 纵行;同格多节点横向错开。
|
||||
final Map<int, int> laneIndex = <int, int>{
|
||||
for (int i = 0; i < lanes.length; i++) lanes[i]: i,
|
||||
};
|
||||
final Map<String, int> cellTotal = <String, int>{};
|
||||
for (final FlowNode n in nodes) {
|
||||
final String key = '${n.lane}:${n.rank}';
|
||||
cellTotal[key] = (cellTotal[key] ?? 0) + 1;
|
||||
}
|
||||
final Map<String, int> cellSeen = <String, int>{};
|
||||
// 泳道基础几何:宽度按槽位数,左边缘按前一泳道宽度累加。
|
||||
laneStarts.clear();
|
||||
laneWidths.clear();
|
||||
{
|
||||
double x = marginX;
|
||||
for (int i = 0; i < lanes.length; i++) {
|
||||
final int s = project.slotsOf(lanes[i]);
|
||||
laneStarts.add(x);
|
||||
laneWidths.add(s * nodeW + (s - 1) * slotGap);
|
||||
x += laneWidths.last + laneGap;
|
||||
}
|
||||
}
|
||||
for (final FlowNode n in nodes) {
|
||||
final int li = laneIndex[n.lane] ?? 0;
|
||||
final String key = '${n.lane}:${n.rank}';
|
||||
final int total = cellTotal[key] ?? 1;
|
||||
final int idx = cellSeen[key] ?? 0;
|
||||
cellSeen[key] = idx + 1;
|
||||
final double w = (n.isStart || n.isEnd) ? capW : nodeW;
|
||||
final double h = (n.isStart || n.isEnd) ? capH : nodeH;
|
||||
// 开始 / 结束节点居中于泳道带;动作节点按(泳道, 槽位)分列,
|
||||
// 同格多节点再沿横向错开。
|
||||
final double centerX;
|
||||
if (n.isStart || n.isEnd) {
|
||||
centerX = laneStartX(li) + laneWidth(li) / 2;
|
||||
} else {
|
||||
final int slot = effectiveSlot(project, n.action!);
|
||||
centerX = slotCenterX(li, slot) + (idx - (total - 1) / 2) * (nodeW * 0.62);
|
||||
}
|
||||
final double top = marginY + n.rank * (nodeH + rankGap) + (nodeH - h) / 2;
|
||||
n.rect = Rect.fromLTWH(centerX - w / 2, top, w, h);
|
||||
}
|
||||
|
||||
// 同层智能排开:同一 rank 行内若有水平重叠(同格多节点 / 跨列挤出),
|
||||
// 从左到右依次推开,保证节点之间至少留 10px,避免“堆叠到一起看不清”。
|
||||
final Map<int, List<FlowNode>> byRank = <int, List<FlowNode>>{};
|
||||
for (final FlowNode n in nodes) {
|
||||
byRank.putIfAbsent(n.rank, () => <FlowNode>[]).add(n);
|
||||
}
|
||||
for (final List<FlowNode> row in byRank.values) {
|
||||
row.sort((FlowNode a, FlowNode b) => a.rect.left.compareTo(b.rect.left));
|
||||
for (int i = 1; i < row.length; i++) {
|
||||
final FlowNode prev = row[i - 1];
|
||||
final FlowNode cur = row[i];
|
||||
final double minLeft = prev.rect.right + 10;
|
||||
if (cur.rect.left < minLeft) {
|
||||
cur.rect = cur.rect.shift(Offset(minLeft - cur.rect.left, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 泳道带按内容**智能加宽**:若某泳道的节点被推到基础宽度之外,
|
||||
// 先按内容算出需要的加宽量,再把该泳道及其后所有泳道整体右移,
|
||||
// 保证底部泳道带完整覆盖自己的动作节点(与条形 / 圆周视图的观感一致)。
|
||||
final List<double> extra = List<double>.filled(lanes.length, 0);
|
||||
for (int i = 0; i < lanes.length; i++) {
|
||||
double contentRight = double.negativeInfinity;
|
||||
for (final FlowNode n in nodes) {
|
||||
if ((laneIndex[n.lane] ?? 0) == i) {
|
||||
contentRight = math.max(contentRight, n.rect.right);
|
||||
}
|
||||
}
|
||||
if (contentRight.isFinite) {
|
||||
final double need = contentRight + 26 - (laneStarts[i] + laneWidths[i]);
|
||||
if (need > 0) extra[i] = need;
|
||||
}
|
||||
}
|
||||
if (extra.any((double e) => e > 0)) {
|
||||
double delta = 0;
|
||||
for (int i = 0; i < lanes.length; i++) {
|
||||
if (delta != 0) {
|
||||
for (final FlowNode n in nodes) {
|
||||
if ((laneIndex[n.lane] ?? 0) == i) {
|
||||
n.rect = n.rect.shift(Offset(delta, 0));
|
||||
}
|
||||
}
|
||||
laneStarts[i] += delta;
|
||||
}
|
||||
laneWidths[i] += extra[i];
|
||||
// 泳道加宽后,开始 / 结束胶囊重新居中于泳道带。
|
||||
if (extra[i] > 0) {
|
||||
for (final FlowNode n in nodes) {
|
||||
if ((n.isStart || n.isEnd) && (laneIndex[n.lane] ?? 0) == i) {
|
||||
final double cx = laneStarts[i] + laneWidths[i] / 2;
|
||||
n.rect = Rect.fromLTWH(
|
||||
cx - n.rect.width / 2, n.rect.top, n.rect.width, n.rect.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
delta += extra[i];
|
||||
}
|
||||
}
|
||||
|
||||
// 6) 连线走线:画布绘制 / SVG / drawio 导出共用(同源同层分支扇形错位)。
|
||||
// 依赖上保存的手动走线偏移(routeOffset)在此叠加:
|
||||
// 向下流为竖直偏移(拖动横线),同层绕行为水平偏移(拖动纵向走廊)。
|
||||
// 同源同层的多条分支预先分组,横线在可用空隙内**均匀铺开**,
|
||||
// 分支多时不再全部挤在同一条线上(流程图“智能排开”)。
|
||||
final Map<String, List<FlowEdge>> fanGroups = <String, List<FlowEdge>>{};
|
||||
for (final FlowEdge e in edges) {
|
||||
final FlowNode? a = byId[e.fromId];
|
||||
final FlowNode? b = byId[e.toId];
|
||||
if (a == null || b == null || b.rank <= a.rank) continue;
|
||||
fanGroups.putIfAbsent('${e.fromId}:${b.rank}', () => <FlowEdge>[]).add(e);
|
||||
}
|
||||
final Map<String, int> fanIndex = <String, int>{};
|
||||
for (final FlowEdge e in edges) {
|
||||
final FlowNode? a = byId[e.fromId];
|
||||
final FlowNode? b = byId[e.toId];
|
||||
if (a == null || b == null) continue;
|
||||
double routeOffset = 0;
|
||||
if (e.type != null) {
|
||||
final Action? to = project.actionById(e.toId);
|
||||
for (final Dependency d in to?.deps ?? const <Dependency>[]) {
|
||||
if (d.fromId == e.fromId) {
|
||||
routeOffset = d.routeOffset;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (b.rank > a.rank) {
|
||||
final String key = '${e.fromId}:${b.rank}';
|
||||
final List<FlowEdge> group = fanGroups[key] ?? <FlowEdge>[e];
|
||||
final int idx = fanIndex[key] ?? 0;
|
||||
fanIndex[key] = idx + 1;
|
||||
// 横线高度:单条分支沿用“空隙中线”;多条分支在
|
||||
// [源底 + 10, 目标顶 - 8] 内均匀铺开(第 idx+1 / n+1 份),再叠加手动偏移。
|
||||
final double gapLow = a.rect.bottom + 10;
|
||||
double gapHigh = double.infinity;
|
||||
for (final FlowEdge ge in group) {
|
||||
final FlowNode? gb = byId[ge.toId];
|
||||
if (gb != null && gb.rect.top - 8 < gapHigh) gapHigh = gb.rect.top - 8;
|
||||
}
|
||||
double lane;
|
||||
if (group.length <= 1) {
|
||||
lane = math.min((a.rect.bottom + b.rect.top) / 2 + routeOffset, b.rect.top - 8);
|
||||
} else {
|
||||
final double span = math.max(gapHigh - gapLow, 8);
|
||||
lane = gapLow + span * (idx + 1) / (group.length + 1) + routeOffset;
|
||||
}
|
||||
if (lane < gapLow) lane = gapLow;
|
||||
if (lane > gapHigh) lane = gapHigh;
|
||||
final double x0 = a.rect.center.dx;
|
||||
final double x1 = b.rect.center.dx;
|
||||
routes.add(FlowEdgeRoute(
|
||||
e,
|
||||
<Offset>[
|
||||
Offset(x0, a.rect.bottom),
|
||||
Offset(x0, lane),
|
||||
Offset(x1, lane),
|
||||
Offset(x1, b.rect.top),
|
||||
],
|
||||
Offset(x1, b.rect.top),
|
||||
const Offset(0, 1),
|
||||
Offset((x0 + x1) / 2, lane - 11),
|
||||
RouteAxis.vertical,
|
||||
));
|
||||
} else {
|
||||
// 同层 / 回连:右侧绕行;手动偏移作用于绕行走廊的横向位置。
|
||||
final double x = math.max(a.rect.right, b.rect.right) + 22 + routeOffset;
|
||||
routes.add(FlowEdgeRoute(
|
||||
e,
|
||||
<Offset>[
|
||||
Offset(a.rect.right, a.rect.center.dy),
|
||||
Offset(x, a.rect.center.dy),
|
||||
Offset(x, b.rect.center.dy),
|
||||
Offset(b.rect.right, b.rect.center.dy),
|
||||
],
|
||||
Offset(b.rect.right, b.rect.center.dy),
|
||||
const Offset(-1, 0),
|
||||
Offset(x + 16, (a.rect.center.dy + b.rect.center.dy) / 2),
|
||||
RouteAxis.horizontal,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 7) 相位分区跨度:每个动作行归属到“覆盖角度占比最大”的分区(并列取靠前分区)。
|
||||
// 这样阶段栏的每一段都真实对应分区归属,不会出现两个分区同时压住同一行、
|
||||
// 看起来“对不上号”的情况。
|
||||
final List<PhaseZone> zones = project.phaseZones;
|
||||
final Map<String, int> dominant = <String, int>{};
|
||||
for (final Action a in project.actions) {
|
||||
int best = -1;
|
||||
double bestSpan = 0;
|
||||
for (int i = 0; i < zones.length; i++) {
|
||||
final double span = _angleOverlapSpan(
|
||||
a.startAngle, a.endAngle, zones[i].startAngle, zones[i].endAngle);
|
||||
if (span > bestSpan + 0.001) {
|
||||
bestSpan = span;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
dominant[a.id] = best;
|
||||
}
|
||||
for (int i = 0; i < zones.length; i++) {
|
||||
final PhaseZone z = zones[i];
|
||||
int top = -1;
|
||||
int bottom = -1;
|
||||
for (final FlowNode n in nodes) {
|
||||
final Action? a = n.action;
|
||||
if (a == null || dominant[a.id] != i) continue;
|
||||
if (top < 0 || n.rank < top) top = n.rank;
|
||||
if (n.rank > bottom) bottom = n.rank;
|
||||
}
|
||||
if (top >= 0) spans.add(FlowPhaseSpan(z, top, bottom));
|
||||
}
|
||||
// 回退:没有任何主导行的分区,按“与动作行有角度重叠即覆盖”补上,
|
||||
// 避免分区(如仅少量跨界的下料相位)在阶段栏中缺失。
|
||||
for (int i = 0; i < zones.length; i++) {
|
||||
if (spans.any((FlowPhaseSpan s) => identical(s.zone, zones[i]))) continue;
|
||||
int top = -1;
|
||||
int bottom = -1;
|
||||
for (final FlowNode n in nodes) {
|
||||
final Action? a = n.action;
|
||||
if (a == null) continue;
|
||||
if (!angleRangesOverlap(a.startAngle, a.endAngle, zones[i].startAngle, zones[i].endAngle)) {
|
||||
continue;
|
||||
}
|
||||
if (top < 0 || n.rank < top) top = n.rank;
|
||||
if (n.rank > bottom) bottom = n.rank;
|
||||
}
|
||||
if (top >= 0) spans.add(FlowPhaseSpan(zones[i], top, bottom));
|
||||
}
|
||||
// 纵向仍重叠的相位:轻微向右错位(每档 [railStep] px)。采用贪心图着色,
|
||||
// 保证互相重叠的两个相位一定拿到不同档位(同档的必定不重叠)。
|
||||
for (int i = 0; i < spans.length; i++) {
|
||||
final Set<int> used = <int>{};
|
||||
for (int j = 0; j < i; j++) {
|
||||
final bool overlap = spans[i].rankTop <= spans[j].rankBottom &&
|
||||
spans[j].rankTop <= spans[i].rankBottom;
|
||||
if (overlap) used.add(spans[j].slot);
|
||||
}
|
||||
int slot = 0;
|
||||
while (used.contains(slot)) {
|
||||
slot++;
|
||||
}
|
||||
spans[i].slot = slot;
|
||||
}
|
||||
|
||||
// 8) 内容范围:节点 + 连线走线 + 左侧阶段栏(按实际错位档数计算宽度,
|
||||
// 保证「适应窗口」不裁切)。
|
||||
Rect b = nodes.first.rect;
|
||||
for (final FlowNode n in nodes) {
|
||||
b = b.expandToInclude(n.rect);
|
||||
}
|
||||
for (final FlowEdgeRoute r in routes) {
|
||||
for (final Offset p in r.points) {
|
||||
b = b.expandToInclude(Rect.fromCenter(center: p, width: 30, height: 30));
|
||||
}
|
||||
b = b.expandToInclude(Rect.fromCenter(center: r.labelAt, width: 70, height: 26));
|
||||
}
|
||||
bounds = b.inflate(math.max(60, laneGap));
|
||||
int maxSlot = 0;
|
||||
for (final FlowPhaseSpan s in spans) {
|
||||
if (s.slot > maxSlot) maxSlot = s.slot;
|
||||
}
|
||||
bounds = bounds.expandToInclude(
|
||||
Rect.fromLTRB(
|
||||
railX - 10,
|
||||
bounds.top,
|
||||
railX + maxSlot * railStep + railW + 24,
|
||||
bounds.bottom,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 两个角度区间(允许超过 360° 表示跨圈)的重叠跨度(度);无重叠返回 0。
|
||||
double _angleOverlapSpan(double a0, double a1, double b0, double b1) {
|
||||
double best = 0;
|
||||
for (final double shift in <double>[-360, 0, 360]) {
|
||||
final double lo = math.max(a0, b0 + shift);
|
||||
final double hi = math.min(a1, b1 + shift);
|
||||
if (hi > lo) best = math.max(best, hi - lo);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
/// 几何布局层:把领域模型 [Project] 映射为屏幕坐标,供绘制与命中测试使用。
|
||||
///
|
||||
/// 本层不持有任何可变状态、不修改模型,属于纯计算:
|
||||
/// - 顶层的极坐标/角度/圆弧工具函数服务于圆周视图;
|
||||
/// - [BarLayout] 负责条形(甘特)视图的行与列定位;
|
||||
/// - [CircularLayout] 负责圆周视图的同心环定位与命中测试。
|
||||
/// 视图层根据这些坐标进行绘制与交互命中判断。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
|
||||
/// 极坐标转直角坐标:以 [c] 为圆心、[r] 为半径、[deg] 为角度(0° 指向正上方)。
|
||||
Offset polar(Offset c, double r, double deg) {
|
||||
final double t = (deg - 90) * math.pi / 180;
|
||||
return Offset(c.dx + r * math.cos(t), c.dy + r * math.sin(t));
|
||||
}
|
||||
|
||||
/// 已知圆心 [c] 与点 [p],求该点相对圆心的角度(度,0° 为正上方,范围 [0,360))。
|
||||
double angleOf(Offset c, Offset p) {
|
||||
final double a = math.atan2(p.dy - c.dy, p.dx - c.dx) * 180 / math.pi + 90;
|
||||
return a < 0 ? a + 360 : a;
|
||||
}
|
||||
|
||||
/// 构造从角度 [a0] 到 [a1] 的圆弧路径。
|
||||
///
|
||||
/// 参数 [c]:圆心;[r]:半径;[a0]/[a1]:起止角(度)。
|
||||
/// 返回:以起点 moveTo、经 arcToPoint 连接终点的 [Path];根据扫过角度决定
|
||||
/// 是否使用 largeArc,并根据扫角正负决定顺时针方向。
|
||||
Path arcPath(Offset c, double r, double a0, double a1) {
|
||||
final Path p = Path();
|
||||
final Offset s = polar(c, r, a0);
|
||||
final Offset e = polar(c, r, a1);
|
||||
p.moveTo(s.dx, s.dy);
|
||||
final double sweep = a1 - a0;
|
||||
final int large = sweep.abs() > 180 ? 1 : 0;
|
||||
p.arcToPoint(
|
||||
e,
|
||||
radius: Radius.circular(r),
|
||||
largeArc: large == 1,
|
||||
clockwise: sweep >= 0,
|
||||
);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// 将跨越 360° 的区间拆分为两段,便于分别绘制。
|
||||
///
|
||||
/// 若 [a1] <= 360 直接返回 `[[a0, a1]]`;否则返回 `[[a0, 360], [0, a1-360]]`。
|
||||
List<List<double>> splitArcs(double a0, double a1) {
|
||||
if (a1 <= 360) return <List<double>>[<double>[a0, a1]];
|
||||
return <List<double>>[
|
||||
<double>[a0, 360],
|
||||
<double>[0, a1 - 360],
|
||||
];
|
||||
}
|
||||
|
||||
/// 计算动作在条形视图中的行顺序。
|
||||
///
|
||||
/// **泳道模型**:`Action.layer` 同时作为「泳道 / 圆周轨道」编号,
|
||||
/// 对应一个物理执行器;同一泳道可容纳**多个互不重叠**的动作。
|
||||
/// 排序规则:先按泳道号,再按起始角,最后按 id。
|
||||
List<Action> orderActions(Project project) {
|
||||
final List<Action> list = List<Action>.of(project.actions);
|
||||
list.sort((Action a, Action b) {
|
||||
if (a.layer != b.layer) return a.layer.compareTo(b.layer);
|
||||
final int c = a.startAngle.compareTo(b.startAngle);
|
||||
if (c != 0) return c;
|
||||
return a.id.compareTo(b.id);
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
/// 判断两条角度区间是否重叠(用于同一泳道内“动作不可重叠”的约束)。
|
||||
///
|
||||
/// 参数均为角度区间 `[start, end]`;跨圈(end > 360)按模 360 归一后判断。
|
||||
bool angleRangesOverlap(double s1, double e1, double s2, double e2) {
|
||||
// 归一到 [0,360),并把跨圈区间拆成两段后逐一比较。
|
||||
List<List<double>> seg(double s, double e) {
|
||||
double a = s % 360;
|
||||
if (a < 0) a += 360;
|
||||
double b = e % 360;
|
||||
if (b < 0) b += 360;
|
||||
if (e - s >= 360) return <List<double>>[<double>[0, 360]];
|
||||
if (b >= a) return <List<double>>[<double>[a, b]];
|
||||
return <List<double>>[<double>[a, 360], <double>[0, b]];
|
||||
}
|
||||
|
||||
for (final List<double> x in seg(s1, e1)) {
|
||||
for (final List<double> y in seg(s2, e2)) {
|
||||
if (x[0] < y[1] - 0.001 && y[0] < x[1] - 0.001) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 动作 [a] 在 [project] 中其泳道内的有效槽位(与泳道槽位数钳制一致)。
|
||||
///
|
||||
/// 1 槽泳道恒为 0;旧数据中的历史行序(超出范围 / -1)会被钳制到有效槽位。
|
||||
int effectiveSlot(Project project, Action a) {
|
||||
final int slots = project.slotsOf(a.layer);
|
||||
if (slots <= 1) return 0;
|
||||
final int r = a.row;
|
||||
return r < 0 ? 0 : (r >= slots ? slots - 1 : r);
|
||||
}
|
||||
|
||||
/// 条形(甘特)视图布局。
|
||||
///
|
||||
/// 横轴为相位角(0°–360°),纵轴为动作行。行顺序由 [ordered] 决定,
|
||||
/// 行高 [pitch] 会根据可用高度自适应(限制在 46–66 之间)。
|
||||
class BarLayout {
|
||||
/// 构造条形布局并计算行高。
|
||||
///
|
||||
/// 参数 [project]:项目数据;[size]:可用画布尺寸。
|
||||
/// 副作用:初始化 [pitch]。
|
||||
BarLayout(this.project, this.size) {
|
||||
// 可用高度 = 总高 - 顶部留白 - 底部预留;按**总子行数**(各泳道槽位数之和)
|
||||
// 均分并夹取到 [44, 58];单槽泳道时与旧版行为完全一致。
|
||||
// 多槽位工程采用「组内紧凑 + 泳道间拉开」:子行更紧、泳道之间额外留白,
|
||||
// 一眼能看出哪些子行属于同一条泳道。
|
||||
final int n = subRowCount;
|
||||
final int laneN = lanes.length;
|
||||
final double extraTotal = _grouped && laneN > 1 ? (laneN - 1) * laneExtraGap : 0;
|
||||
final double usable = size.height - topPad - bottomReserve;
|
||||
pitch = n == 0 ? 58 : ((usable - extraTotal) / n).clamp(_grouped ? 36 : 44, 58);
|
||||
}
|
||||
|
||||
/// 是否启用「组内紧凑 + 泳道间拉开」的间隔分组(仅多槽位工程)。
|
||||
bool get _grouped => project.hasMultiSlotLanes;
|
||||
|
||||
/// 泳道之间的额外纵向留白(仅多槽位分组时生效,像素)。
|
||||
static const double laneExtraGap = 16;
|
||||
|
||||
/// 布局所依据的项目数据。
|
||||
final Project project;
|
||||
|
||||
/// 可用画布尺寸。
|
||||
final Size size;
|
||||
|
||||
/// 左侧标签栏宽度(像素):紧贴图表,避免动作名离图太远。
|
||||
static const double leftGutter = 210;
|
||||
|
||||
/// 顶部留白(为标题/刻度等预留)。
|
||||
static const double topPad = 210;
|
||||
|
||||
/// 单个动作条的高度(像素):单行文字即可,条块更苗条(留出更多泳道间隙放依赖标签)。
|
||||
static const double barH = 18;
|
||||
|
||||
/// 行的视觉参考高度(像素)。
|
||||
static const double rowVisual = 36;
|
||||
|
||||
/// 底部预留空间(像素)。
|
||||
static const double bottomReserve = 350;
|
||||
|
||||
/// 相邻动作行之间的垂直距离(像素)。
|
||||
late final double pitch;
|
||||
|
||||
/// 绘图区左边界。
|
||||
double get plotLeft => leftGutter;
|
||||
|
||||
/// 绘图区右边界(右侧留 56px)。
|
||||
double get plotRight => size.width - 56;
|
||||
|
||||
/// 绘图区横向跨度(像素)。
|
||||
double get span => plotRight - plotLeft;
|
||||
|
||||
/// 决定行先后的动作列表;见顶层函数 [orderActions]。
|
||||
List<Action> get ordered => orderActions(project);
|
||||
|
||||
/// 泳道编号(= 物理执行器轨道):来自 [Project.renderLanes]。
|
||||
///
|
||||
/// 开启「保留空泳道」时包含动作已全部移走的空泳道(序号不变)。
|
||||
List<int> get lanes => project.renderLanes;
|
||||
|
||||
/// 泳道号在 [lanes] 中的序号。
|
||||
int laneIndexOf(int lane) => lanes.indexOf(lane);
|
||||
|
||||
/// 泳道内包含的动作(按起始角排序)。
|
||||
List<Action> actionsInLane(int lane) =>
|
||||
ordered.where((Action a) => a.layer == lane).toList();
|
||||
|
||||
/// 泳道 [lane] 的槽位数(1–5)。
|
||||
int slotsOf(int lane) => project.slotsOf(lane);
|
||||
|
||||
/// 动作 [a] 的实际槽位(钳制到所属泳道的有效范围;1 槽泳道恒为 0)。
|
||||
int slotOf(Action a) => effectiveSlot(project, a);
|
||||
|
||||
/// 全部泳道的子行总数(Σ 槽位)。
|
||||
int get subRowCount {
|
||||
int n = 0;
|
||||
for (final int lane in lanes) {
|
||||
n += slotsOf(lane);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// 泳道 [lane] 之前(不含)的纵向高度(子行 + 分组留白)。
|
||||
double _laneOffsetBefore(int lane) {
|
||||
double h = 0;
|
||||
for (final int l in lanes) {
|
||||
if (l == lane) break;
|
||||
h += slotsOf(l) * pitch + (_grouped ? laneExtraGap : 0);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/// 泳道号转纵坐标(该泳道顶部 y)。
|
||||
double yForLane(int lane) => topPad + _laneOffsetBefore(lane);
|
||||
|
||||
/// 泳道内槽位转纵坐标(该槽位所在子行的顶部 y)。
|
||||
double yForSlot(int lane, int slot) => yForLane(lane) + slot * pitch;
|
||||
|
||||
/// 内容底部 y(最后一个子行之后)。
|
||||
double get plotBottom {
|
||||
double h = subRowCount * pitch;
|
||||
if (_grouped && lanes.length > 1) h += (lanes.length - 1) * laneExtraGap;
|
||||
return topPad + h;
|
||||
}
|
||||
|
||||
/// 由纵坐标反查最近的泳道号(用于拖拽换道)。
|
||||
int laneAt(double y) => laneSlotAt(y).$1;
|
||||
|
||||
/// 由纵坐标反查(泳道号, 槽位)——拖拽换道 / 换槽位时使用。
|
||||
(int, int) laneSlotAt(double y) {
|
||||
if (lanes.isEmpty) return (0, 0);
|
||||
double top = topPad;
|
||||
for (int li = 0; li < lanes.length; li++) {
|
||||
final int lane = lanes[li];
|
||||
final int s = slotsOf(lane);
|
||||
final double h = s * pitch;
|
||||
// 泳道之间的额外留白按半份归属本道,保证指针落在空隙中也能命中相邻泳道。
|
||||
final double boundary =
|
||||
top + h + (_grouped && li < lanes.length - 1 ? laneExtraGap * 0.5 : 0);
|
||||
if (y < boundary || li == lanes.length - 1) {
|
||||
final int slot = ((y - top) / pitch).round().clamp(0, s - 1);
|
||||
return (lane, slot);
|
||||
}
|
||||
top += h + (_grouped ? laneExtraGap : 0);
|
||||
}
|
||||
return (lanes.last, slotsOf(lanes.last) - 1);
|
||||
}
|
||||
|
||||
/// 相位角(度)转横坐标;角度先钳制到 `[0, 360]`。
|
||||
double xFor(double deg) => plotLeft + (deg.clamp(0, 360) / 360) * span;
|
||||
|
||||
/// 计算动作 [a] 的条形矩形(按所属泳道的 y)。
|
||||
///
|
||||
/// 宽度至少为 3px,避免极短动作不可见;跨圈部分会被截断到 360°。
|
||||
Rect rectFor(Action a) {
|
||||
final double y = yForSlot(a.layer, slotOf(a));
|
||||
final double x0 = xFor(a.startAngle);
|
||||
final double x1 = xFor(math.min(a.endAngle, 360));
|
||||
return Rect.fromLTWH(x0, y, math.max(x1 - x0, 3), barH);
|
||||
}
|
||||
|
||||
/// 命中测试:返回坐标 [p] 处最上层的动作,未命中返回 null。
|
||||
///
|
||||
/// 从后往前遍历(后绘制的在上层),并按 [slop] 向外膨胀矩形提升可点性
|
||||
/// (触屏平台可传入更大的容差)。
|
||||
Action? hitTest(Offset p, {double slop = 4}) {
|
||||
for (int i = ordered.length - 1; i >= 0; i--) {
|
||||
final Action a = ordered[i];
|
||||
final Rect r = rectFor(a).inflate(slop);
|
||||
if (r.contains(p)) return a;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 横坐标反算相位角(度),结果钳制在 `[0, 360]`。
|
||||
double angleAt(double x) => ((x - plotLeft) / span * 360).clamp(0, 360);
|
||||
}
|
||||
|
||||
/// 圆周(环形)视图布局。
|
||||
///
|
||||
/// 每个动作的层 [Action.layer] 决定其所在同心环的半径,角度区间决定环上的弧段。
|
||||
class CircularLayout {
|
||||
/// 构造圆周布局并计算圆心、环间距与环宽。
|
||||
///
|
||||
/// 参数 [project]:项目数据;[size]:可用画布尺寸。
|
||||
/// 副作用:初始化 [center]、[pitch]、[ringWidth]。
|
||||
CircularLayout(this.project, this.size) {
|
||||
// 圆心略微下移 18px 以平衡顶部刻度标签的视觉重心。
|
||||
center = Offset(size.width / 2, size.height / 2 + 18);
|
||||
// 子环总数 = Σ 各轨道槽位数(泳道加宽后同一轨道可有多条并行子环);
|
||||
// 单槽时与旧版(按轨道数)完全一致。
|
||||
final int rings = subRingCount;
|
||||
final int laneN = lanes.length;
|
||||
// 多槽位工程采用「组内紧凑 + 轨道间拉开」:同一轨道的子环更紧、
|
||||
// 轨道之间额外留白,一眼能看出哪些子环属于同一轨道。
|
||||
final double extraTotal = _grouped && laneN > 1 ? (laneN - 1) * ringExtraGap : 0;
|
||||
// 最大半径受较短边约束,减去 74px 留给刻度与边距。
|
||||
final double maxR = math.min(size.width, size.height) / 2 - 74;
|
||||
// 在 r0 与 maxR 之间均分各子环,环间距夹取(多槽位时允许更紧)。
|
||||
pitch = rings <= 1
|
||||
? 46
|
||||
: ((maxR - r0 - extraTotal) / (rings - 1)).clamp(_grouped ? 24 : 32, 56);
|
||||
// 动作环带宽度:只求容纳文字;多槽位分组时子环更窄,轨道间靠留白区分。
|
||||
ringWidth = (pitch * 0.42).clamp(_grouped ? 10 : 14, 17);
|
||||
}
|
||||
|
||||
/// 是否启用「组内紧凑 + 轨道间拉开」的间隔分组(仅多槽位工程)。
|
||||
bool get _grouped => project.hasMultiSlotLanes;
|
||||
|
||||
/// 轨道之间的额外径向留白(仅多槽位分组时生效,像素)。
|
||||
static const double ringExtraGap = 18;
|
||||
|
||||
/// 布局所依据的项目数据。
|
||||
final Project project;
|
||||
|
||||
/// 可用画布尺寸。
|
||||
final Size size;
|
||||
|
||||
/// 最内层(第 0 层)半径(像素)。
|
||||
static const double r0 = 58;
|
||||
|
||||
/// 圆心坐标。
|
||||
late final Offset center;
|
||||
|
||||
/// 相邻层之间的半径差(像素)。
|
||||
late final double pitch;
|
||||
|
||||
/// 环的视觉宽度(像素)。
|
||||
late final double ringWidth;
|
||||
|
||||
/// 轨道编号(= 泳道):来自 [Project.renderLanes](含保留的空轨道)。
|
||||
List<int> get lanes => project.renderLanes;
|
||||
|
||||
/// 轨道号在 [lanes] 中的序号。
|
||||
int laneIndexOf(int lane) => lanes.indexOf(lane);
|
||||
|
||||
/// 轨道 [lane] 的槽位数(1–5)。
|
||||
int slotsOf(int lane) => project.slotsOf(lane);
|
||||
|
||||
/// 动作 [a] 的实际槽位(钳制;1 槽轨道恒为 0)。
|
||||
int slotOf(Action a) => effectiveSlot(project, a);
|
||||
|
||||
/// 全部轨道的子环总数(Σ 槽位)。
|
||||
int get subRingCount {
|
||||
int n = 0;
|
||||
for (final int lane in lanes) {
|
||||
n += slotsOf(lane);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// 轨道 [lane] 之前(不含)的子环数。
|
||||
int subRingIndexOfLane(int lane) {
|
||||
int n = 0;
|
||||
for (final int l in lanes) {
|
||||
if (l == lane) break;
|
||||
n += slotsOf(l);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// 由半径反查最近的轨道号(用于拖拽换轨)。
|
||||
int laneAtRadius(double r) => laneSlotAtRadius(r).$1;
|
||||
|
||||
/// 由半径反查(轨道号, 槽位)——拖拽换轨 / 换子环时使用。
|
||||
(int, int) laneSlotAtRadius(double r) {
|
||||
if (lanes.isEmpty) return (0, 0);
|
||||
double base = r0;
|
||||
for (int li = 0; li < lanes.length; li++) {
|
||||
final int lane = lanes[li];
|
||||
final int s = slotsOf(lane);
|
||||
final double h = s * pitch;
|
||||
// 轨道之间的额外留白按半份归属本道,落在空隙中也能命中相邻轨道。
|
||||
final double boundary =
|
||||
base + h + (_grouped && li < lanes.length - 1 ? ringExtraGap * 0.5 : 0);
|
||||
if (r < boundary || li == lanes.length - 1) {
|
||||
final int slot = ((r - base) / pitch).round().clamp(0, s - 1);
|
||||
return (lane, slot);
|
||||
}
|
||||
base += h + (_grouped ? ringExtraGap : 0);
|
||||
}
|
||||
return (lanes.last, slotsOf(lanes.last) - 1);
|
||||
}
|
||||
|
||||
/// 轨道 [lane] 第 [slot] 条子环的半径(未知轨道回退到最内圈)。
|
||||
double radiusFor(int lane, [int slot = 0]) {
|
||||
final int i = laneIndexOf(lane);
|
||||
if (i < 0) return r0;
|
||||
final int s = slotsOf(lane);
|
||||
final int k = slot < 0 ? 0 : (slot >= s ? s - 1 : slot);
|
||||
return r0 +
|
||||
(subRingIndexOfLane(lane) + k) * pitch +
|
||||
(_grouped ? i * ringExtraGap : 0);
|
||||
}
|
||||
|
||||
/// 最外层半径。
|
||||
double get rMax {
|
||||
if (lanes.isEmpty) return r0;
|
||||
final double extra = _grouped && lanes.length > 1 ? (lanes.length - 1) * ringExtraGap : 0;
|
||||
return r0 + (subRingCount - 1) * pitch + extra;
|
||||
}
|
||||
|
||||
/// 刻度标签所在的半径(最外层再向外偏移)。
|
||||
/// 刻度环半径:在外层动作环之外留出足够间距,
|
||||
/// 供相位分区带独立占位(不与动作环挤在一起)。
|
||||
double get tickR => rMax + ringWidth / 2 + 38;
|
||||
|
||||
/// 环宽别名,供绘制代码使用。
|
||||
double get th => ringWidth;
|
||||
|
||||
/// 命中测试:返回坐标 [p] 命中的动作,未命中返回 null。
|
||||
///
|
||||
/// 算法:计算点相对圆心的距离 [d] 与角度 [a];遍历所有动作,先按径向
|
||||
/// 距离过滤(与所在环的偏差不超过半个环宽 + [slop]),再判断角度是否落在
|
||||
/// 该动作弧段内;在候选中取径向偏差最小者(触屏平台可传入更大的容差)。
|
||||
Action? hitTest(Offset p, {double slop = 3}) {
|
||||
final double d = (p - center).distance;
|
||||
final double a = angleOf(center, p);
|
||||
Action? best;
|
||||
double bestDelta = double.infinity;
|
||||
for (final Action a2 in project.actions) {
|
||||
final double r = radiusFor(a2.layer, slotOf(a2));
|
||||
if ((d - r).abs() > ringWidth / 2 + slop) continue;
|
||||
if (_inArc(a2, a)) {
|
||||
final double delta = (d - r).abs();
|
||||
if (delta < bestDelta) {
|
||||
bestDelta = delta;
|
||||
best = a2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// 判断角度 [deg] 是否落在动作 [a] 的弧段内(含 0.5° 容差)。
|
||||
///
|
||||
/// 当动作不跨圈(endAngle <= 360)时为普通区间判断;跨圈时区间回绕,
|
||||
/// 条件变为 `n >= start-0.5 或 n <= (end-360)+0.5`。
|
||||
bool _inArc(Action a, double deg) {
|
||||
final double e = a.endAngle;
|
||||
final double n = deg % 360;
|
||||
if (e <= 360) {
|
||||
return n >= a.startAngle - 0.5 && n <= e + 0.5;
|
||||
}
|
||||
return n >= a.startAngle - 0.5 || n <= (e - 360) + 0.5;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/// 动作条拖拽吸附:把整体拖动的水平位移吸附到最近的动作条端点、整 5°、
|
||||
/// 0/360 或相位分区边界。
|
||||
///
|
||||
/// 架构位置:布局层纯函数,不依赖 UI 状态;`CanvasView` 在整体拖动时调用,
|
||||
/// 单元测试可直接验证吸附结果。
|
||||
library;
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
|
||||
/// 计算整体拖动后的动作起始角。
|
||||
///
|
||||
/// - [project]:当前工程;
|
||||
/// - [excludeId]:正在拖动的动作 id(不参与吸附,避免自吸附);
|
||||
/// - [rawStart]:未吸附的起始角;
|
||||
/// - [duration]:动作持续角(整体拖动不改变长度);
|
||||
/// - [toleranceDeg]:吸附容差(度)。
|
||||
///
|
||||
/// 返回 `(吸附后的起始角, 参考角度)`;参考角度用于绘制竖向虚线,
|
||||
/// 未吸附时为 null。
|
||||
(double, double?) snapActionStart({
|
||||
required Project project,
|
||||
required String excludeId,
|
||||
required double rawStart,
|
||||
required double duration,
|
||||
required double toleranceDeg,
|
||||
}) {
|
||||
final double tol = toleranceDeg <= 0 ? 0 : toleranceDeg;
|
||||
final List<double> candidates = <double>[0, 360];
|
||||
for (int d = 0; d <= 360; d += 5) {
|
||||
candidates.add(d.toDouble());
|
||||
}
|
||||
for (final Action a in project.actions) {
|
||||
if (a.id == excludeId) continue;
|
||||
candidates.add(a.startAngle);
|
||||
candidates.add(a.endAngle);
|
||||
}
|
||||
for (final PhaseZone z in project.phaseZones) {
|
||||
candidates.add(z.startAngle);
|
||||
candidates.add(z.endAngle);
|
||||
}
|
||||
final double end = rawStart + duration;
|
||||
double best = rawStart;
|
||||
double bestD = tol;
|
||||
double? guide;
|
||||
// 起点与终点同时参与匹配:取绝对调整量最小的一条候选。
|
||||
for (final double cand in candidates) {
|
||||
final double ds = (cand - rawStart).abs();
|
||||
if (ds < bestD) {
|
||||
bestD = ds;
|
||||
best = cand;
|
||||
guide = cand;
|
||||
}
|
||||
final double de = (cand - end).abs();
|
||||
if (de < bestD) {
|
||||
bestD = de;
|
||||
best = cand - duration;
|
||||
guide = cand;
|
||||
}
|
||||
}
|
||||
return (best.clamp(0, 360 - duration), guide);
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
/// 条形(时间轴)视图绘制器。
|
||||
///
|
||||
/// 职责:把 [Project] 中的动作按“双轴”条形图渲染到 Flutter 画布上——
|
||||
/// 横轴同时表达相位角度与等价的绝对时间,纵轴按工位顺序排列动作行。
|
||||
///
|
||||
/// 架构位置:
|
||||
/// - 全部几何计算委托给 [BarLayout](`modules/sequence/layout/layout.dart`),
|
||||
/// 本绘制器只负责取几何结果并落笔,不自行推导坐标。
|
||||
/// - 颜色一律取自 [Tokens],因此与圆形视图及 SVG 导出保持同一视觉体系。
|
||||
/// - 关键路径信息([criticalActions]、[criticalDeps])由上层分析后传入,
|
||||
/// 本类不参与计算,仅负责高亮呈现。
|
||||
///
|
||||
/// 绘制顺序(见 [paint]):
|
||||
/// 相位带 → 时间/相位标尺 → 循环边界 → 动作行 → 依赖连线。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/layout/layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
|
||||
/// 条形时间轴视图的 [CustomPainter] 实现。
|
||||
///
|
||||
/// 坐标约定:横轴 `x` 表示 0°–360° 相位(并线性映射到 0–cycle 时间),
|
||||
/// 纵轴 `y` 表示动作行。角度到像素的换算由 [BarLayout.xFor] 完成。
|
||||
class BarPainter extends CustomPainter {
|
||||
/// 创建条形视图绘制器。
|
||||
///
|
||||
/// 参数:
|
||||
/// - [project]:待绘制的工程数据(动作、工位、依赖、视图开关)。
|
||||
/// - [tokens]:当前主题令牌,决定所有颜色。
|
||||
/// - [criticalActions]:关键路径上的动作 id 集合,用于描边高亮。
|
||||
/// - [criticalDeps]:关键路径上的依赖集合,键格式 `fromId->toId`。
|
||||
/// - [selectedId]:当前选中动作 id,可为空。
|
||||
/// - [selectedDep]:当前选中的依赖连线键(`from->to`),用于高亮。
|
||||
///
|
||||
/// 无副作用;实例不缓存布局,每次 [paint] 都重新计算。
|
||||
BarPainter({
|
||||
required this.project,
|
||||
required this.tokens,
|
||||
required this.criticalActions,
|
||||
required this.criticalDeps,
|
||||
required this.selectedIds,
|
||||
this.selectedDep,
|
||||
this.guideAngle,
|
||||
this.dropLane,
|
||||
this.dropValid = true,
|
||||
});
|
||||
|
||||
/// 待绘制的工程数据源。
|
||||
final Project project;
|
||||
/// 当前主题令牌。
|
||||
final Tokens tokens;
|
||||
/// 关键路径上的动作 id 集合。
|
||||
final Set<String> criticalActions;
|
||||
/// 关键路径上的依赖边集合,元素格式为 `fromId->toId`。
|
||||
final Set<String> criticalDeps;
|
||||
/// 当前选中的动作 id 集合(支持多选)。
|
||||
final Set<String> selectedIds;
|
||||
|
||||
/// 当前选中的依赖连线键(`from->to`);非空时该走线以强调色高亮。
|
||||
final String? selectedDep;
|
||||
|
||||
/// 拖拽相位分区边界时的参考角(度);非空时绘制一条竖直虚线参考。
|
||||
final double? guideAngle;
|
||||
|
||||
/// 上下拖拽换泳道时,光标所在的目标泳道号;非空时高亮该泳道。
|
||||
final int? dropLane;
|
||||
|
||||
/// 目标泳道是否可放置(时间不重叠);false 时用警示色高亮。
|
||||
final bool dropValid;
|
||||
|
||||
/// 标尺横线所在的 y 坐标(画布坐标)。
|
||||
static const double axisTop = 164;
|
||||
/// 相位色带的顶部 y 坐标。
|
||||
static const double phaseBandTop = 92;
|
||||
/// 相位刻度值所在行的 y(分区带与刻度线之间,上排)。
|
||||
static const double phaseValY = 136;
|
||||
/// 时间刻度值所在行的 y(分区带与刻度线之间,下排)。
|
||||
static const double timeValY = 150;
|
||||
|
||||
/// 绘制整张条形视图。
|
||||
///
|
||||
/// 参数 [canvas]:目标画布;[size]:可用尺寸(用于构建 [BarLayout])。
|
||||
/// 副作用:向 [canvas] 写入若干图元,不修改任何模型状态。
|
||||
/// 图层顺序遵循“先背景后前景”:相位带、标尺、边界、动作行、依赖。
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final BarLayout layout = BarLayout(project, size);
|
||||
final UnitSettings u = project.units;
|
||||
final double cycle = project.cycle.durationMs;
|
||||
|
||||
if (project.viewState.showPhaseBands) _phaseBands(canvas, layout);
|
||||
// 换泳道拖拽:高亮目标泳道(可放置=强调色,重叠=警示色)。
|
||||
// 泳道加宽(多槽位)后高亮覆盖该泳道的全部槽位。
|
||||
if (dropLane != null && layout.lanes.contains(dropLane)) {
|
||||
final double y = layout.yForLane(dropLane!);
|
||||
final double h = layout.slotsOf(dropLane!) * layout.pitch;
|
||||
final Color c = dropValid ? tokens.accent : tokens.danger;
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(
|
||||
Rect.fromLTWH(20, y - 8, layout.plotRight - 20, h),
|
||||
const Radius.circular(10),
|
||||
),
|
||||
Paint()..color = c.withValues(alpha: 0.12),
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(
|
||||
Rect.fromLTWH(20, y - 8, layout.plotRight - 20, h),
|
||||
const Radius.circular(10),
|
||||
),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.4
|
||||
..color = c.withValues(alpha: 0.8),
|
||||
);
|
||||
}
|
||||
if (project.viewState.showRuler) _ruler(canvas, layout, u, cycle);
|
||||
_boundaries(canvas, layout);
|
||||
_rows(canvas, layout, u, cycle);
|
||||
if (project.viewState.showDeps) _deps(canvas, layout, u);
|
||||
// 分区拖拽参考线绘制在最上层,保证清晰可见。
|
||||
if (guideAngle != null) _guide(canvas, layout, u);
|
||||
}
|
||||
|
||||
/// 绘制相位分区拖拽时的竖直虚线参考线,并在顶部标注当前角度。
|
||||
void _guide(Canvas canvas, BarLayout layout, UnitSettings u) {
|
||||
final double deg = guideAngle!;
|
||||
final double x = layout.xFor(deg.clamp(0, 360));
|
||||
final double bottom = layout.plotBottom - 4;
|
||||
final Paint p = Paint()
|
||||
..color = tokens.accent
|
||||
..strokeWidth = 1.4;
|
||||
// 虚线:从相位带一直画到图表底部。
|
||||
const double dash = 6;
|
||||
const double gap = 6;
|
||||
double y = phaseBandTop - 8;
|
||||
while (y < bottom) {
|
||||
canvas.drawLine(Offset(x, y), Offset(x, math.min(y + dash, bottom)), p);
|
||||
y += dash + gap;
|
||||
}
|
||||
_text(canvas, '${deg.toStringAsFixed(1)}°', Offset(x, phaseBandTop - 18),
|
||||
color: tokens.accent, size: 11, align: TextAlign.center, weight: FontWeight.w700);
|
||||
}
|
||||
|
||||
/// 过滤出有效(跨度 > 0)的相位分区。
|
||||
///
|
||||
/// 相位分区来自 [Project.phaseZones],可在工艺参数面板中编辑;
|
||||
/// 这里只做基本合法性过滤,保证异常数据不会画出负宽度色带。
|
||||
List<PhaseZone> _phaseZones() {
|
||||
return project.phaseZones.where((PhaseZone z) => z.endAngle > z.startAngle).toList();
|
||||
}
|
||||
|
||||
/// 绘制相位色带。
|
||||
///
|
||||
/// 算法:把每个相位分区映射到横轴像素,绘制一个圆角矩形,填充强调色的
|
||||
/// 低透明度版本并描边;宽度足够(> 64px)时居中标注分区名称。
|
||||
/// 若分区跨越 360°(结束角 > 360),则在左侧补画从 0° 起的续段,
|
||||
/// 对应“跨循环”语义。
|
||||
void _phaseBands(Canvas canvas, BarLayout layout) {
|
||||
for (final PhaseZone z in _phaseZones()) {
|
||||
final double x0 = layout.xFor(z.startAngle);
|
||||
final double x1 = layout.xFor(z.endAngle);
|
||||
final Rect r = Rect.fromLTWH(x0, phaseBandTop, math.max(x1 - x0, 2), 32);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(6)),
|
||||
Paint()..color = tokens.accent.withValues(alpha: 0.08),
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(6)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..color = tokens.line2,
|
||||
);
|
||||
// 名称居中且按色带宽度截断,保证不越出色块。
|
||||
if (r.width > 26) {
|
||||
_textClipped(canvas, z.name, Offset(r.center.dx, r.center.dy), r.width - 10,
|
||||
color: tokens.sub, size: 11);
|
||||
}
|
||||
if (z.endAngle > 360) {
|
||||
final double wx = layout.xFor(z.endAngle - 360) - layout.plotLeft;
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(Rect.fromLTWH(layout.plotLeft, phaseBandTop, wx, 32), const Radius.circular(6)),
|
||||
Paint()..color = tokens.accent.withValues(alpha: 0.08),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制双轴标尺。
|
||||
///
|
||||
/// 每 15° 一个刻度,30° 为主刻度(更长);每 60° 标注文字:
|
||||
/// 下排为相位(度,强调色),上排为等价的绝对时间(由 [tvalStr] 格式化)。
|
||||
/// 参数 [u] 提供单位设置,[cycle] 为一个完整循环的毫秒数。
|
||||
void _ruler(Canvas canvas, BarLayout layout, UnitSettings u, double cycle) {
|
||||
canvas.drawLine(Offset(layout.plotLeft, axisTop), Offset(layout.plotRight, axisTop),
|
||||
Paint()..color = tokens.line2..strokeWidth = 1);
|
||||
for (int d = 0; d <= 360; d += 15) {
|
||||
final double x = layout.xFor(d.toDouble());
|
||||
final bool major = d % 30 == 0;
|
||||
canvas.drawLine(
|
||||
Offset(x, axisTop),
|
||||
Offset(x, axisTop + (major ? 28 : 14)),
|
||||
Paint()
|
||||
..color = major ? tokens.line2 : tokens.line
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
if (d % 60 == 0) {
|
||||
// 上排:相位刻度值;下排:时间刻度值(均位于分区带与刻度线之间)。
|
||||
_text(canvas, pfmt(d.toDouble(), u, dec: 0), Offset(x, phaseValY),
|
||||
color: tokens.accent, size: 10, align: TextAlign.center);
|
||||
_text(canvas, tvalStr(d / 360 * cycle, u, dec: u.timeUnit == TimeUnit.ms ? 0 : 1),
|
||||
Offset(x, timeValY), color: tokens.sub, size: 10, align: TextAlign.center);
|
||||
}
|
||||
}
|
||||
// 轴单位图例:与对应刻度值同排,置于最左侧。
|
||||
_text(canvas, '相位 / ${phaseUnitLabel(u.phaseUnit)}', Offset(layout.plotLeft - 12, phaseValY),
|
||||
color: tokens.accent, size: 10, align: TextAlign.right);
|
||||
_text(canvas, '时间 / ${timeUnitLabel(u.timeUnit)}', Offset(layout.plotLeft - 12, timeValY),
|
||||
color: tokens.sub, size: 10, align: TextAlign.right);
|
||||
}
|
||||
|
||||
/// 绘制循环起止边界线(0° 与 360°)。
|
||||
///
|
||||
/// 0° 使用 [Tokens.ok]、360° 使用 [Tokens.warn] 的虚线竖线表示;
|
||||
/// 不再额外标注文字(坐标轴已能说明起止)。虚线由 [_dashedLine] 手工分段绘制。
|
||||
void _boundaries(Canvas canvas, BarLayout layout) {
|
||||
for (final double d in <double>[0, 360]) {
|
||||
final double x = layout.xFor(d);
|
||||
final Color col = d == 0 ? tokens.ok : tokens.warn;
|
||||
final Paint p = Paint()
|
||||
..color = col.withValues(alpha: 0.7)
|
||||
..strokeWidth = 1.4;
|
||||
_dashedLine(canvas, Offset(x, axisTop + 28), Offset(x, layout.plotBottom - 4), p);
|
||||
}
|
||||
}
|
||||
|
||||
/// 在两点之间绘制固定 dash/gap 的虚线。
|
||||
///
|
||||
/// 参数 [a]/[b]:线段端点;[p]:画笔(颜色与线宽由调用方决定)。
|
||||
/// 通过沿单位方向向量步进生成短线段,不依赖 dashPathEffect。
|
||||
void _dashedLine(Canvas canvas, Offset a, Offset b, Paint p) {
|
||||
const double dash = 6;
|
||||
const double gap = 6;
|
||||
final double total = (b - a).distance;
|
||||
final Offset dir = (b - a) / total;
|
||||
double t = 0;
|
||||
while (t < total) {
|
||||
final double end = math.min(t + dash, total);
|
||||
canvas.drawLine(a + dir * t, a + dir * end, p);
|
||||
t = end + gap;
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制所有动作行。
|
||||
///
|
||||
/// 每行包含:
|
||||
/// - 隔行背景(偶数行填充 [Tokens.panel2] 半透明色,便于横向阅读);
|
||||
/// - 左侧序号色块,以及 `序号. id 名称`、`工位 · 驱动` 文本;
|
||||
/// - 行底分隔线;
|
||||
/// - 主条块(带阴影、选中描边、关键路径描边);
|
||||
/// - 跨循环延续段(当 [Action.wrap] 且开启自动拆分时);
|
||||
/// - 条块内或条块外的名称与时长标注。
|
||||
///
|
||||
/// 参数 [layout] 提供行列几何,[u]/[cycle] 用于时长文本换算。
|
||||
void _rows(Canvas canvas, BarLayout layout, UnitSettings u, double cycle) {
|
||||
final List<int> lanes = layout.lanes;
|
||||
for (int li = 0; li < lanes.length; li++) {
|
||||
final int lane = lanes[li];
|
||||
final double y = layout.yForLane(lane);
|
||||
final int slots = layout.slotsOf(lane);
|
||||
final double laneH = slots * layout.pitch;
|
||||
final List<Action> acts = layout.actionsInLane(lane);
|
||||
// 单槽泳道保持与旧版完全一致的背景带 / 底线几何;多槽位覆盖整个泳道带。
|
||||
final double bandH = slots == 1 ? BarLayout.rowVisual : laneH;
|
||||
// 隔泳道背景色带(覆盖该泳道全部槽位),弱化边界。
|
||||
if (li.isEven) {
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(
|
||||
Rect.fromLTWH(20, y - 8, layout.plotRight - 20, bandH),
|
||||
const Radius.circular(10),
|
||||
),
|
||||
Paint()..color = tokens.panel2.withValues(alpha: 0.5),
|
||||
);
|
||||
}
|
||||
// 多槽位泳道:槽位之间用浅色虚线分隔,提示并列关系。
|
||||
if (slots > 1) {
|
||||
for (int s = 1; s < slots; s++) {
|
||||
final double sy = y + s * layout.pitch - 8;
|
||||
_dashedLine(
|
||||
canvas,
|
||||
Offset(layout.plotLeft, sy),
|
||||
Offset(layout.plotRight, sy),
|
||||
Paint()
|
||||
..color = tokens.line2.withValues(alpha: 0.75)
|
||||
..strokeWidth = 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
// 泳道标题(合并显示;单槽最多两行,多槽位按泳道高度持续换行)。
|
||||
_laneHeader(canvas, layout, li, acts,
|
||||
slots == 1 ? y : y + laneH / 2 - BarLayout.rowVisual / 2, slots, laneH);
|
||||
// 泳道底分隔线(单槽时与旧版一致;加深颜色便于区分泳道)。
|
||||
canvas.drawLine(
|
||||
Offset(layout.plotLeft, slots == 1 ? y + BarLayout.rowVisual - 4 : y + laneH - 4),
|
||||
Offset(layout.plotRight, slots == 1 ? y + BarLayout.rowVisual - 4 : y + laneH - 4),
|
||||
Paint()
|
||||
..color = tokens.line2
|
||||
..strokeWidth = 1.3,
|
||||
);
|
||||
// 该泳道内的所有动作条(按槽位分行放置)。
|
||||
for (final Action a in acts) {
|
||||
_bar(canvas, layout, a, u, cycle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制一条泳道的标题:序号徽标 + 合并动作名 + 副标题。
|
||||
///
|
||||
/// 合并动作名在宽度 [BarLayout.leftGutter]-68 内自动换行:单槽泳道最多两行
|
||||
/// (保持旧版外观);多槽位泳道按泳道高度**持续换行**直到放不下为止
|
||||
/// (副标题跟随实际行数下移)。
|
||||
void _laneHeader(Canvas canvas, BarLayout layout, int li, List<Action> acts, double y,
|
||||
int slots, double laneH) {
|
||||
final double labelMax = BarLayout.leftGutter - 68;
|
||||
final Color c0 = acts.isEmpty ? tokens.accent : Color(acts.first.color);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(Rect.fromLTWH(32, y + 8, 18, 18), const Radius.circular(5)),
|
||||
Paint()..color = c0,
|
||||
);
|
||||
_text(canvas, '${li + 1}', Offset(41, y + 17),
|
||||
color: tokens.chip, size: 10, align: TextAlign.center, weight: FontWeight.w700);
|
||||
if (acts.isEmpty) return;
|
||||
|
||||
// 先按足够大的行数测量“真实行高”(字体回退下行高可能大于字号,
|
||||
// 之前按固定 13px 估算导致标题换行多行后压住灰色副标题)。
|
||||
final String joined = acts.map((Action a) => '${a.id} ${a.name}').join(' / ');
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: joined,
|
||||
style: TextStyle(
|
||||
color: tokens.text,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 40,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: labelMax);
|
||||
final int totalLines = tp.computeLineMetrics().length;
|
||||
final double lineH = totalLines == 0 ? 14 : tp.height / totalLines;
|
||||
|
||||
// 行数上限:单槽保持两行(旧版外观);多槽位按泳道高度换算并给副标题留一行。
|
||||
final bool single = slots <= 1;
|
||||
final int maxLines =
|
||||
single ? 2 : ((laneH - lineH - 8) / lineH).floor().clamp(2, 40);
|
||||
if (tp.computeLineMetrics().length != maxLines && maxLines < totalLines) {
|
||||
tp.maxLines = maxLines;
|
||||
tp.ellipsis = '…';
|
||||
tp.layout(maxWidth: labelMax);
|
||||
}
|
||||
tp.paint(canvas, Offset(60, y + 2));
|
||||
|
||||
final Station? st = project.stationById(acts.first.stationId);
|
||||
final String sub = '${st?.name ?? acts.first.stationId} · ${acts.first.driver}'
|
||||
'${acts.length > 1 ? ' · 共 ${acts.length} 个' : ''}';
|
||||
// 副标题紧随实际标题高度;单槽保持旧版下边距(y+32)但绝不高于标题底部,
|
||||
// 多槽位下若剩余高度不足则不再绘制,避免压住标题文字。
|
||||
final double subY = single
|
||||
? math.max(y + 36, y + 2 + tp.height + 6)
|
||||
: y + 2 + tp.height + 6;
|
||||
if (single || subY + 11 <= y + laneH) {
|
||||
_textMax(canvas, sub, Offset(60, subY), labelMax, color: tokens.dim, size: 10);
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制单个动作条块(投影 / 填充 / 描边 / 跨圈尾段 / 文字标注)。
|
||||
void _bar(Canvas canvas, BarLayout layout, Action a, UnitSettings u, double cycle) {
|
||||
final Color c = Color(a.color);
|
||||
final Rect r = layout.rectFor(a);
|
||||
final bool sel = selectedIds.contains(a.id);
|
||||
final bool crit = criticalActions.contains(a.id);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r.shift(const Offset(1.5, 2)), const Radius.circular(3)),
|
||||
Paint()..color = tokens.shadow.withValues(alpha: tokens.shadowOp),
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(3)),
|
||||
Paint()..color = c.withValues(alpha: 0.92),
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(3)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.selOutline.withValues(alpha: sel ? 0.9 : 0.25),
|
||||
);
|
||||
if (crit) {
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(3)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = tokens.crit,
|
||||
);
|
||||
}
|
||||
// 选中时在两端绘制把手:提示可拖拽端点改时长(触屏目标更大、更好抓)。
|
||||
if (sel) {
|
||||
_handle(canvas, Offset(r.left, r.center.dy));
|
||||
_handle(canvas, Offset(r.right, r.center.dy));
|
||||
}
|
||||
if (a.wrap && u.autoSplitWrap) {
|
||||
final double wx = layout.xFor(a.endAngle - 360) - layout.plotLeft;
|
||||
final Rect tail = Rect.fromLTWH(layout.plotLeft, r.top, math.max(wx, 2), r.height);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(tail, const Radius.circular(3)),
|
||||
Paint()..color = c.withValues(alpha: tokens.tailOp),
|
||||
);
|
||||
_text(canvas, '跨循环延续 ${(a.endAngle - 360).toStringAsFixed(0)}°',
|
||||
Offset(layout.plotLeft + wx + 18, r.center.dy), color: tokens.warn, size: 10);
|
||||
}
|
||||
final double durMs = a.durationAngle / 360 * cycle;
|
||||
final String full = '${a.name} ${tfmt(durMs, u)}';
|
||||
// 默认「名称 + 时长」一起写在条块内、紧跟名称之后(单行,条块更苗条);
|
||||
// 仅当条块太短、放不下时才移到条块外侧。
|
||||
final double fullW = _tp(full, 11, tokens.arcText, FontWeight.w700).width;
|
||||
if (r.width >= fullW + 20) {
|
||||
_text(canvas, full, Offset(r.left + 10, r.center.dy),
|
||||
color: tokens.arcText, size: 11, weight: FontWeight.w700);
|
||||
} else if (r.right + 190 > layout.plotRight) {
|
||||
_text(canvas, full, Offset(r.left - 10, r.center.dy),
|
||||
color: c, size: 11, weight: FontWeight.w600, align: TextAlign.right);
|
||||
} else {
|
||||
_text(canvas, full, Offset(r.right + 10, r.center.dy),
|
||||
color: c, size: 11, weight: FontWeight.w600);
|
||||
}
|
||||
_text(canvas, 'Δ${a.durationAngle.toStringAsFixed(0)}°', Offset(layout.plotRight - 4, r.center.dy),
|
||||
color: tokens.dim, size: 10, align: TextAlign.right);
|
||||
}
|
||||
|
||||
/// 绘制端点把手:白边圆点,提示可拖拽端点改时长。
|
||||
void _handle(Canvas canvas, Offset o) {
|
||||
canvas.drawCircle(o, 6, Paint()..color = tokens.accent);
|
||||
canvas.drawCircle(
|
||||
o,
|
||||
6,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = Colors.white,
|
||||
);
|
||||
}
|
||||
|
||||
/// 绘制动作依赖连线(正交折线)。
|
||||
///
|
||||
/// 算法要点:
|
||||
/// - 建立“动作 id → 行号”索引,用于判断两行相对位置。
|
||||
/// - FS 依赖从源条块右端出发;SS 依赖从源条块左端出发。
|
||||
/// - 相邻行(行距 ≤ 1)走短折线;跨多行时在行区间外侧选一条“泳道”
|
||||
/// 作为竖直通道,泳道位置按区间内条块的最右/最左边界外扩,
|
||||
/// 并叠加 `(k % 3) * 16` 的错位,避免多条线完全重叠。
|
||||
/// - 关键路径依赖先画一层加粗低透明度的“光晕”,再画主线。
|
||||
/// - 末端绘制箭头与类型标签(FS 顺序 / SS +偏移时间)。
|
||||
///
|
||||
/// 参数 [layout] 提供条块矩形;[u] 当前未直接使用,保留以对齐调用接口。
|
||||
void _deps(Canvas canvas, BarLayout layout, UnitSettings u) {
|
||||
// 走线统一由 [buildBarDepRoutes] 计算:同组自动错开 + 手动偏移,
|
||||
// 与画布的命中测试 / 拖拽调整共用同一份几何。
|
||||
final List<BarDepRoute> routes = buildBarDepRoutes(project, layout);
|
||||
// 依赖标签先收集、后统一避让放置(见方法末尾 _placeChips)。
|
||||
final List<_ChipSpec> chips = <_ChipSpec>[];
|
||||
for (final BarDepRoute r in routes) {
|
||||
final Dependency d = r.dep;
|
||||
final Color col = d.type == DepType.fs ? tokens.fs : tokens.ss;
|
||||
final bool crit = criticalDeps.contains(r.key);
|
||||
final bool sel = selectedDep == r.key;
|
||||
final Color draw = sel ? tokens.accent : col;
|
||||
if (!r.junctionOnly) {
|
||||
final Path p = Path()
|
||||
..moveTo(r.points.first.dx, r.points.first.dy);
|
||||
for (int i = 1; i < r.points.length; i++) {
|
||||
p.lineTo(r.points[i].dx, r.points[i].dy);
|
||||
}
|
||||
// 关键路径依赖:先铺一层加粗低透明度光晕,再画主线。
|
||||
if (crit) {
|
||||
canvas.drawPath(
|
||||
p,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 5
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = col.withValues(alpha: 0.18),
|
||||
);
|
||||
}
|
||||
canvas.drawPath(
|
||||
p,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = sel ? 2.0 : (crit ? 1.1 : 0.85)
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = sel ? draw : draw.withValues(alpha: 0.95),
|
||||
);
|
||||
_arrow(canvas, r.arrowTip, r.arrowDir, draw);
|
||||
}
|
||||
final String label = switch (d.type) {
|
||||
DepType.fs => 'FS',
|
||||
DepType.ss => d.offsetAngle == 0
|
||||
? 'SS'
|
||||
: 'SS+${deg2msStr(d.offsetAngle, project.units, project.cycle.durationMs, dec: 2)}',
|
||||
DepType.ff => 'FF',
|
||||
DepType.sf => 'SF',
|
||||
};
|
||||
// 标签固定在两端动作之间的走线中点;不再因为行程短而横向挪到
|
||||
// 目标条块上方。统一避让时会同时避开动作条与其它标签。
|
||||
chips.add(_ChipSpec(r.chipCenter, label, draw));
|
||||
}
|
||||
_placeChips(canvas, layout, chips);
|
||||
}
|
||||
|
||||
/// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。
|
||||
///
|
||||
/// 参数 [col] 为填充色;[dir] 只需提供方向(本函数不归一化,直接按分量使用)。
|
||||
void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) {
|
||||
const double s = 6.5;
|
||||
final Offset b = tip - dir * s;
|
||||
final Offset n = Offset(-dir.dy, dir.dx) * s * 0.5;
|
||||
final Path p = Path()
|
||||
..moveTo(tip.dx, tip.dy)
|
||||
..lineTo(b.dx + n.dx, b.dy + n.dy)
|
||||
..lineTo(b.dx - n.dx, b.dy - n.dy)
|
||||
..close();
|
||||
canvas.drawPath(p, Paint()..color = col);
|
||||
}
|
||||
|
||||
/// 统一放置并绘制依赖标签,避免标签之间相互重叠。
|
||||
///
|
||||
/// 对每个标签依次尝试:原位 → 上下错开 → 上下再错开 → 左右错开 → 斜向错开,
|
||||
/// 取第一个不与已放置标签相交的位置,实现“智能避让”。标签内不再绘制五角星
|
||||
/// (关键路径改用线条光晕表示),字号与色块同时收小,画面更干净。
|
||||
void _placeChips(Canvas canvas, BarLayout layout, List<_ChipSpec> chips) {
|
||||
final List<Rect> placed = <Rect>[];
|
||||
final List<Rect> bars = <Rect>[
|
||||
for (final Action a in project.actions) layout.rectFor(a).inflate(1),
|
||||
];
|
||||
for (final _ChipSpec chip in chips) {
|
||||
final TextPainter tp = _tp(chip.label, 8.5, chip.color, FontWeight.w600);
|
||||
final double w = tp.width + 12;
|
||||
const double h = 14;
|
||||
final List<Offset> trials = <Offset>[
|
||||
Offset.zero,
|
||||
Offset(0, -(h + 3)), Offset(0, h + 3),
|
||||
Offset(0, -2 * (h + 3)), Offset(0, 2 * (h + 3)),
|
||||
Offset(0, -3 * (h + 3)), Offset(0, 3 * (h + 3)),
|
||||
Offset(w + 6, 0), Offset(-w - 6, 0),
|
||||
Offset(w + 6, -(h + 3)), Offset(-w - 6, -(h + 3)),
|
||||
Offset(w + 6, h + 3), Offset(-w - 6, h + 3),
|
||||
];
|
||||
Rect r = Rect.fromCenter(center: chip.center, width: w, height: h);
|
||||
for (final Offset t in trials) {
|
||||
final Rect cand = r.shift(t);
|
||||
final bool hitChip =
|
||||
placed.any((Rect o) => o.inflate(1.5).overlaps(cand));
|
||||
final bool hitBar = bars.any((Rect o) => o.overlaps(cand));
|
||||
if (!hitChip && !hitBar) {
|
||||
r = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
placed.add(r);
|
||||
_chipRect(canvas, r, tp, chip.color);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按给定矩形绘制一颗标签胶囊(无星标)。
|
||||
void _chipRect(Canvas canvas, Rect r, TextPainter tp, Color col) {
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(5)),
|
||||
Paint()..color = tokens.chip,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(5)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = col,
|
||||
);
|
||||
tp.paint(canvas, Offset(r.left + 6, r.center.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 构造并布局一个 [TextPainter]。
|
||||
///
|
||||
/// 统一使用微软雅黑字体;参数 [s] 文本、[size] 字号、[color] 颜色、
|
||||
/// [weight] 字重、[align] 对齐方式。返回已完成 layout 的实例。
|
||||
TextPainter _tp(String s, double size, Color color, FontWeight weight, {TextAlign align = TextAlign.left}) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
textAlign: align,
|
||||
)..layout();
|
||||
return tp;
|
||||
}
|
||||
|
||||
/// 便捷文本绘制。
|
||||
///
|
||||
/// 在 [at] 处按 [align] 对齐绘制字符串 [s](默认左对齐、垂直居中)。
|
||||
/// [color] 缺省时使用 [Tokens.text]。
|
||||
/// 在 [at] 处绘制左对齐的单行文字,并按 [maxWidth] 截断(超出显示省略号)。
|
||||
void _textMax(Canvas canvas, String s, Offset at, double maxWidth,
|
||||
{Color? color, double size = 12, FontWeight weight = FontWeight.normal}) {
|
||||
if (maxWidth <= 4) return;
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(color: color ?? tokens.text, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: maxWidth);
|
||||
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 在 [center] 处绘制居中的单行文字,并按 [maxWidth] 截断(超出显示省略号)。
|
||||
void _textClipped(Canvas canvas, String s, Offset center, double maxWidth,
|
||||
{Color? color, double size = 11, FontWeight weight = FontWeight.w600}) {
|
||||
if (maxWidth <= 4) return;
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(color: color ?? tokens.text, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: maxWidth);
|
||||
tp.paint(canvas, Offset(center.dx - tp.width / 2, center.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
void _text(Canvas canvas, String s, Offset at,
|
||||
{Color? color, double size = 12, FontWeight weight = FontWeight.normal, TextAlign align = TextAlign.left}) {
|
||||
final TextPainter tp = _tp(s, size, color ?? tokens.text, weight, align: align);
|
||||
double dx = at.dx;
|
||||
if (align == TextAlign.center) dx -= tp.width / 2;
|
||||
if (align == TextAlign.right) dx -= tp.width;
|
||||
tp.paint(canvas, Offset(dx, at.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 始终返回 `true`。
|
||||
///
|
||||
/// 绘制完全依赖每次重建的布局与外部状态,且本绘制器不做缓存,
|
||||
/// 因此保守地要求每次重绘。
|
||||
@override
|
||||
bool shouldRepaint(covariant BarPainter old) => true;
|
||||
}
|
||||
|
||||
/// 依赖标签的待放置描述:中心点、文本与颜色。
|
||||
///
|
||||
/// 在依赖遍历中收集,随后由 `BarPainter._placeChips` 统一做避让放置。
|
||||
class _ChipSpec {
|
||||
const _ChipSpec(this.center, this.label, this.color);
|
||||
|
||||
/// 期望的标签中心(逻辑坐标)。
|
||||
final Offset center;
|
||||
/// 标签文本(如 `FS` / `SS+0.20 s`)。
|
||||
final String label;
|
||||
/// 边框与文字颜色(按依赖类型区分)。
|
||||
final Color color;
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
/// 圆形(极坐标)视图绘制器。
|
||||
///
|
||||
/// 职责:把 [Project] 中的动作绘制为同心圆环——角度表示相位
|
||||
/// (0° 位于 12 点钟方向,顺时针递增),半径表示动作所属层级(layer)。
|
||||
///
|
||||
/// 架构位置:
|
||||
/// - 几何换算(圆心、各层半径、刻度半径)来自 [CircularLayout];
|
||||
/// 极坐标换算复用 `layout.dart` 中的 [polar] 与 [arcPath]。
|
||||
/// - 颜色取自 [Tokens],与条形视图及 SVG 导出保持同一视觉体系。
|
||||
/// - 跨循环动作通过 [splitArcs] 拆成两段弧绘制,保证角度连续、视觉闭合。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/layout/layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
|
||||
/// 圆形视图的 [CustomPainter] 实现。
|
||||
///
|
||||
/// 所有角度以“12 点钟为 0°、顺时针为正”为约定,由 [polar] 完成换算。
|
||||
class CircularPainter extends CustomPainter {
|
||||
/// 创建圆形视图绘制器。
|
||||
///
|
||||
/// 参数:
|
||||
/// - [project]:待绘制的工程数据(动作、依赖、视图开关)。
|
||||
/// - [tokens]:当前主题令牌,决定所有颜色。
|
||||
/// - [criticalActions]:关键路径上的动作 id 集合。
|
||||
/// - [criticalDeps]:关键路径上的依赖集合,键格式 `fromId->toId`。
|
||||
/// - [selectedId]:当前选中动作 id,可为空。
|
||||
///
|
||||
/// 无副作用;实例不缓存布局,每次 [paint] 都重新计算。
|
||||
CircularPainter({
|
||||
required this.project,
|
||||
required this.tokens,
|
||||
required this.criticalActions,
|
||||
required this.criticalDeps,
|
||||
required this.selectedIds,
|
||||
this.selectedDep,
|
||||
this.guideAngle,
|
||||
});
|
||||
|
||||
/// 待绘制的工程数据源。
|
||||
final Project project;
|
||||
/// 当前主题令牌。
|
||||
final Tokens tokens;
|
||||
/// 关键路径上的动作 id 集合。
|
||||
final Set<String> criticalActions;
|
||||
/// 关键路径上的依赖边集合,元素格式为 `fromId->toId`。
|
||||
final Set<String> criticalDeps;
|
||||
/// 当前选中的动作 id 集合(支持多选)。
|
||||
final Set<String> selectedIds;
|
||||
|
||||
/// 当前选中的依赖连线键(`from->to`);非空时该走线以强调色高亮。
|
||||
final String? selectedDep;
|
||||
|
||||
/// 拖拽动作弧端点时的参考角(度);非空时绘制一条径向虚线参考。
|
||||
final double? guideAngle;
|
||||
|
||||
/// 绘制整个圆形视图。
|
||||
///
|
||||
/// 参数 [canvas]/[size] 遵循 Flutter 绘制约定。
|
||||
/// 图层顺序:表盘底 → 圆环背景 → 象限线 → 层号 → 依赖 → 动作弧
|
||||
/// → 起点标记 / 方向箭头 / 刻度。
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final CircularLayout layout = CircularLayout(project, size);
|
||||
final UnitSettings u = project.units;
|
||||
final Offset c = layout.center;
|
||||
final double th = layout.th;
|
||||
final double tickR = layout.tickR;
|
||||
|
||||
// 表盘底板:半径略大于最外圈刻度,形成一圈底色与边框。
|
||||
canvas.drawCircle(c, tickR + 10, Paint()..color = tokens.dial);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
tickR + 10,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2
|
||||
..color = tokens.line2,
|
||||
);
|
||||
|
||||
// 圆环背景:每条轨道用一条粗描边构成环带,奇偶交替着色,
|
||||
// 并在环带内外沿各画一条细描边作为边界。
|
||||
final List<int> lanes = layout.lanes;
|
||||
final int layers = lanes.length;
|
||||
if (project.viewState.showRingBg) {
|
||||
for (int i = 0; i < layers; i++) {
|
||||
final int lane = lanes[i];
|
||||
final int slots = layout.slotsOf(lane);
|
||||
final Color band = i.isEven ? tokens.ringA : tokens.ringB;
|
||||
if (slots <= 1) {
|
||||
// 单槽轨道:与旧版完全一致(一条环带 + 内外沿细描边)。
|
||||
final double r = layout.radiusFor(lane, 0);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
r,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = th
|
||||
..color = band,
|
||||
);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
r - th / 2,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.ringEdge,
|
||||
);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
r + th / 2,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.ringEdge,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// 多槽位轨道:整条轨道用一条加宽的色带(同一泳道同一颜色),
|
||||
// 槽位之间用浅色虚线分隔;不同轨道之间仍按奇偶交替(与现在一致)。
|
||||
final double rIn = layout.radiusFor(lane, 0);
|
||||
final double rOut = layout.radiusFor(lane, slots - 1);
|
||||
final double rc = (rIn + rOut) / 2;
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
rc,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = (rOut - rIn) + th
|
||||
..color = band,
|
||||
);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
rIn - th / 2,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.ringEdge,
|
||||
);
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
rOut + th / 2,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.ringEdge,
|
||||
);
|
||||
final Paint dash = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.ringEdge.withValues(alpha: 0.95);
|
||||
for (int s = 1; s < slots; s++) {
|
||||
_dashedCircle(canvas, c, rIn + (s - 0.5) * layout.pitch, dash);
|
||||
}
|
||||
}
|
||||
}
|
||||
canvas.drawCircle(c, math.max(CircularLayout.r0 - th / 2, 8), Paint()..color = tokens.dial);
|
||||
|
||||
// 相位分区环:在最外动作环与刻度环之间画一圈分区色带并标注名称。
|
||||
if (project.viewState.showPhaseBands) _phaseRing(canvas, layout);
|
||||
|
||||
// 轨道标签:为每条轨道挑选一个空位角度,避免压住该轨道的动作弧;
|
||||
// 多槽位轨道把标签放在轨道带的垂直中心(半径方向)。
|
||||
if (project.viewState.showLayerLabels) {
|
||||
for (int i = 0; i < layers; i++) {
|
||||
final int lane = lanes[i];
|
||||
final int slots = layout.slotsOf(lane);
|
||||
final double r = layout.radiusFor(lane) + (slots - 1) * layout.pitch / 2;
|
||||
final double free = _freeAngle(lane);
|
||||
final Offset lp = polar(c, r, free);
|
||||
_text(canvas, 'L${i + 1}', lp, color: tokens.ringLabel, size: 10, align: TextAlign.center, weight: FontWeight.w700);
|
||||
}
|
||||
}
|
||||
|
||||
// 依赖连线先于动作弧绘制,使其位于弧之下、不被遮挡。
|
||||
if (project.viewState.showDeps) {
|
||||
// 走线统一由 [buildArcDepRoutes] 计算(同组自动错开 + 手动径向偏移),
|
||||
// 与画布命中测试 / 拖拽调整共用同一份几何。
|
||||
final List<ArcDepRoute> routes = buildArcDepRoutes(project, layout);
|
||||
final List<_ArcChip> chips = <_ArcChip>[];
|
||||
for (final ArcDepRoute r in routes) {
|
||||
final _ArcChip? chip = _drawDepRoute(canvas, layout, r);
|
||||
if (chip != null) chips.add(chip);
|
||||
}
|
||||
_placeArcChips(canvas, layout, chips);
|
||||
}
|
||||
|
||||
// 逐个绘制动作弧。
|
||||
for (final Action a in project.actions) {
|
||||
_action(canvas, layout, a, u);
|
||||
}
|
||||
|
||||
// 拖拽端点时的径向虚线参考。
|
||||
if (guideAngle != null) _guide(canvas, layout);
|
||||
|
||||
// 起点标记、循环方向提示与外围刻度。
|
||||
_startMarker(canvas, layout);
|
||||
_directionArrow(canvas, layout);
|
||||
if (project.viewState.showRuler) _ticks(canvas, layout);
|
||||
}
|
||||
|
||||
/// 绘制相位分区环:在最外动作环与刻度环之间画一圈分区色带,标注分区名称,
|
||||
/// 并在每条边界处画一条径向虚线,便于与条形视图的分区对应。
|
||||
void _phaseRing(Canvas canvas, CircularLayout layout) {
|
||||
final List<PhaseZone> zones =
|
||||
project.phaseZones.where((PhaseZone z) => z.endAngle > z.startAngle).toList();
|
||||
if (zones.isEmpty) return;
|
||||
final Offset c = layout.center;
|
||||
// 加宽分区带(16px);tickR 已在外层动作环之外留出更大间距,避免挤在一起。
|
||||
final double rBand = layout.tickR - 16;
|
||||
const double bandW = 16;
|
||||
|
||||
// 底环,作为分区的“轨道”。
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
rBand,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = bandW
|
||||
..color = tokens.track,
|
||||
);
|
||||
|
||||
// 分区配色(循环取用强调色系)。
|
||||
const List<Color> pal = <Color>[
|
||||
Color(0xFF4CC9F0),
|
||||
Color(0xFF7C5CFF),
|
||||
Color(0xFF34D399),
|
||||
Color(0xFFFFD166),
|
||||
Color(0xFFF472B6),
|
||||
];
|
||||
|
||||
for (int i = 0; i < zones.length; i++) {
|
||||
final PhaseZone z = zones[i];
|
||||
final Color col = pal[i % pal.length];
|
||||
// 分区色带(跨圈会拆成两段)。
|
||||
for (final List<double> s in splitArcs(z.startAngle, z.endAngle)) {
|
||||
canvas.drawPath(
|
||||
arcPath(c, rBand, s[0], s[1]),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = bandW
|
||||
..color = col.withValues(alpha: 0.85),
|
||||
);
|
||||
}
|
||||
// 名称沿圆弧排列(切向),并按弧长截断,保证不超出色带。
|
||||
final double mid = ((z.startAngle + z.endAngle) / 2) % 360;
|
||||
final double span = (z.endAngle - z.startAngle).clamp(0, 360);
|
||||
final double arcLen = 2 * math.pi * rBand * (span / 360);
|
||||
_arcLabel(canvas, c, rBand, mid, z.name, tokens.arcText, 11, math.max(arcLen - 10, 22));
|
||||
// 边界径向虚线。
|
||||
for (final double b in <double>[z.startAngle, z.endAngle]) {
|
||||
final Offset p1 = polar(c, rBand - bandW / 2 - 5, b);
|
||||
final Offset p2 = polar(c, rBand + bandW / 2 + 5, b);
|
||||
_dashed(canvas, p1, p2, col.withValues(alpha: 0.9));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 在两点之间画一条虚线(用于分区边界参考)。
|
||||
void _dashed(Canvas canvas, Offset a, Offset b, Color col) {
|
||||
const double dash = 3;
|
||||
const double gap = 3;
|
||||
final double total = (b - a).distance;
|
||||
if (total <= 0) return;
|
||||
final Offset dir = (b - a) / total;
|
||||
double t = 0;
|
||||
final Paint paint = Paint()
|
||||
..color = col
|
||||
..strokeWidth = 1.4
|
||||
..strokeCap = StrokeCap.round;
|
||||
while (t < total) {
|
||||
final double end = math.min(t + dash, total);
|
||||
canvas.drawLine(a + dir * t, a + dir * end, paint);
|
||||
t = end + gap;
|
||||
}
|
||||
}
|
||||
|
||||
/// 沿圆弧切向绘制文字,并按 [maxWidth] 截断,保证不超出色带。
|
||||
///
|
||||
/// 文字位于半径 [r]、角度 [midDeg] 处,旋转到该点的切线方向;
|
||||
/// 当文字位于左半圈(90°–270°)时翻转 180°,避免倒置。
|
||||
void _arcLabel(Canvas canvas, Offset c, double r, double midDeg, String text, Color col, double size, double maxWidth) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(color: col, fontSize: size, fontWeight: FontWeight.w700, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
ellipsis: '…',
|
||||
)..layout(maxWidth: maxWidth);
|
||||
final Offset pos = polar(c, r, midDeg);
|
||||
final double rad = midDeg * math.pi / 180;
|
||||
final bool flip = midDeg > 90 && midDeg < 270;
|
||||
canvas.save();
|
||||
canvas.translate(pos.dx, pos.dy);
|
||||
canvas.rotate(flip ? rad + math.pi : rad);
|
||||
tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2));
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
/// 为指定 [layer] 选一个尽量不被动作弧覆盖的角度,用于放置层号“L1/L2…”。
|
||||
///
|
||||
/// 从候选角列表(围绕正上方 270° 左右摆动)中挑选第一个与本层任何
|
||||
/// 动作弧都不重叠的角度;若全部冲突则回退到 270°。
|
||||
double _freeAngle(int layer) {
|
||||
const List<double> cands = <double>[270, 278, 262, 286, 254, 294, 246, 302, 238, 310];
|
||||
final List<Action> inLayer = project.actions.where((Action a) => a.layer == layer).toList();
|
||||
for (final double cand in cands) {
|
||||
bool ok = true;
|
||||
for (final Action a in inLayer) {
|
||||
if (_inArc(a, cand)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok) return cand;
|
||||
}
|
||||
return 270;
|
||||
}
|
||||
|
||||
/// 判断角度 [deg] 是否落在动作 [a] 的弧范围内。
|
||||
///
|
||||
/// 处理两类情况:普通动作(结束角 ≤ 360)用闭区间判定;
|
||||
/// 跨循环动作(结束角 > 360)用“大于起点 或 小于回绕终点”的并集判定。
|
||||
/// 两侧各留 0.5° 容差以吸收浮点误差。
|
||||
bool _inArc(Action a, double deg) {
|
||||
final double n = deg % 360;
|
||||
if (a.endAngle <= 360) return n >= a.startAngle - 0.5 && n <= a.endAngle + 0.5;
|
||||
return n >= a.startAngle - 0.5 || n <= (a.endAngle - 360) + 0.5;
|
||||
}
|
||||
|
||||
/// 绘制单个动作弧。
|
||||
///
|
||||
/// 算法:
|
||||
/// - 通过 [splitArcs] 把可能跨循环的动作拆成一到两段,逐段绘制。
|
||||
/// - 每段先画加宽阴影弧,再画本体弧;跨循环的“尾巴”段(第二段)
|
||||
/// 以 [Tokens.tailOp] 淡化,并额外叠一层高透明度描边以示区分。
|
||||
/// - 关键动作沿弧画 [Tokens.crit] 描边;选中动作在外侧画强调色细弧。
|
||||
/// - 在弧中点附近放置 `序号. id 名称` 与起止角度文本;
|
||||
/// 短弧(时长 < 38°)使用更小字号并收紧行距。
|
||||
///
|
||||
/// 参数 [u] 为当前单位设置(保留以对齐调用接口,当前未直接使用)。
|
||||
void _action(Canvas canvas, CircularLayout layout, Action a, UnitSettings u) {
|
||||
final Offset c = layout.center;
|
||||
final double r = layout.radiusFor(a.layer, layout.slotOf(a));
|
||||
final double th = layout.th;
|
||||
final Color col = Color(a.color);
|
||||
final bool sel = selectedIds.contains(a.id);
|
||||
final bool crit = criticalActions.contains(a.id);
|
||||
// 跨循环动作会被拆成 [a0,360] 与 [0,a1-360] 两段。
|
||||
final List<List<double>> segs = splitArcs(a.startAngle, a.endAngle);
|
||||
|
||||
for (int k = 0; k < segs.length; k++) {
|
||||
// 第二段且为跨循环时视为“尾巴”,需淡化处理。
|
||||
final bool tail = a.wrap && k == 1;
|
||||
// 方头 + 小圆角:路径角度严格等于真实起止角,弧带长度即真实时长
|
||||
//(原来的圆头端帽会在两端各多出半个环宽,造成长度误读)。
|
||||
final Path p = _bandPath(c, r, th, segs[k][0], segs[k][1], 3);
|
||||
// 圆周色块不加描边 / 阴影,保持干净。
|
||||
canvas.drawPath(p, Paint()..color = col.withValues(alpha: tail ? tokens.tailOp : 1));
|
||||
if (tail) {
|
||||
canvas.drawPath(p, Paint()..color = col.withValues(alpha: 0.9));
|
||||
}
|
||||
}
|
||||
if (crit) {
|
||||
for (final List<double> s in segs) {
|
||||
canvas.drawPath(
|
||||
arcPath(c, r, s[0], s[1]),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = tokens.crit,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (sel) {
|
||||
for (final List<double> s in segs) {
|
||||
canvas.drawPath(
|
||||
arcPath(c, r + th / 2 + 8, s[0], s[1]),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.6
|
||||
..color = tokens.accent,
|
||||
);
|
||||
}
|
||||
// 选中时在弧两端绘制把手:提示可拖拽端点改持续角(触屏更好抓)。
|
||||
for (final Offset h in <Offset>[
|
||||
polar(c, r, a.startAngle),
|
||||
polar(c, r, math.min(a.endAngle, 360)),
|
||||
]) {
|
||||
canvas.drawCircle(h, 6, Paint()..color = tokens.accent);
|
||||
canvas.drawCircle(
|
||||
h,
|
||||
6,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = Colors.white,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 文字沿圆弧排列并按弧长截断;短弧优先保留动作名,避免只剩
|
||||
// “1. A1 动…” 这类难以辨认的省略文本。
|
||||
final double mid = (a.startAngle + a.endAngle) / 2;
|
||||
final int step = project.actions.indexOf(a) + 1;
|
||||
final double span = a.wrap ? (360 - a.startAngle) : a.durationAngle;
|
||||
final double arcLen = 2 * math.pi * r * (span.clamp(0, 360) / 360);
|
||||
final double maxW = math.max(arcLen - 12, 20);
|
||||
double widthOf(String text) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: text,
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
maxLines: 1,
|
||||
)..layout();
|
||||
final double w = tp.width;
|
||||
tp.dispose();
|
||||
return w;
|
||||
}
|
||||
String label = '$step. ${a.id} ${a.name}';
|
||||
if (widthOf(label) > maxW) label = '$step. ${a.name}';
|
||||
if (widthOf(label) > maxW) label = a.name;
|
||||
if (widthOf(label) > maxW) label = '$step. ${a.id}';
|
||||
_arcLabel(canvas, c, r, mid, label, tokens.arcText, 11, maxW);
|
||||
}
|
||||
|
||||
/// 构造「方头 + 小圆角」的圆环动作带(填充路径)。
|
||||
///
|
||||
/// 与「圆头描边」不同,路径覆盖的角度范围严格等于 [a0] → [a1](顺时针):
|
||||
/// 两端为径向直边、四角带 [cornerR] 的小圆角,因此弧带的长度就是动作的
|
||||
/// 真实时长,不会再像圆头端帽那样在两端各多出半个环宽造成长度误读。
|
||||
Path _bandPath(Offset c, double r, double w, double a0, double a1, double cornerR) {
|
||||
final double ro = r + w / 2;
|
||||
final double ri = r - w / 2;
|
||||
final double rc = math.min(cornerR, w / 2 - 0.5);
|
||||
final double span = a1 - a0;
|
||||
final Path p = Path();
|
||||
if (rc <= 0.5 || span <= 0.5) {
|
||||
// 退化情形:直接方头四边形。
|
||||
final Offset a = polar(c, ro, a0);
|
||||
p.moveTo(a.dx, a.dy);
|
||||
final Offset b = polar(c, ro, a1);
|
||||
p.lineTo(b.dx, b.dy);
|
||||
final Offset d = polar(c, ri, a1);
|
||||
p.lineTo(d.dx, d.dy);
|
||||
final Offset e = polar(c, ri, a0);
|
||||
p.lineTo(e.dx, e.dy);
|
||||
p.close();
|
||||
return p;
|
||||
}
|
||||
// 小圆角在内 / 外缘占用的角向宽度(度),不超过跨度的 40%。
|
||||
final double dOut = math.min(rc / ro * 180 / math.pi, span * 0.4);
|
||||
final double dIn = math.min(rc / ri * 180 / math.pi, span * 0.4);
|
||||
final Offset oStart = polar(c, ro, a0 + dOut);
|
||||
final Offset oEnd = polar(c, ro, a1 - dOut);
|
||||
final Offset iEnd = polar(c, ri, a1 - dIn);
|
||||
final Offset iStart = polar(c, ri, a0 + dIn);
|
||||
p.moveTo(oStart.dx, oStart.dy);
|
||||
// 外缘弧(顺时针)
|
||||
p.arcToPoint(oEnd,
|
||||
radius: Radius.circular(ro), largeArc: span - 2 * dOut > 180, clockwise: true);
|
||||
// 尾端:外角 → 小圆角 → 端面 → 小圆角 → 内缘
|
||||
final Offset co = polar(c, ro, a1);
|
||||
final Offset fo = polar(c, ro - rc, a1);
|
||||
p.quadraticBezierTo(co.dx, co.dy, fo.dx, fo.dy);
|
||||
final Offset fi = polar(c, ri + rc, a1);
|
||||
p.lineTo(fi.dx, fi.dy);
|
||||
final Offset ci = polar(c, ri, a1);
|
||||
p.quadraticBezierTo(ci.dx, ci.dy, iEnd.dx, iEnd.dy);
|
||||
// 内缘弧(逆时针返回)
|
||||
p.arcToPoint(iStart,
|
||||
radius: Radius.circular(ri), largeArc: span - 2 * dIn > 180, clockwise: false);
|
||||
// 起始端:内角 → 小圆角 → 端面 → 小圆角 → 外角
|
||||
final Offset ci0 = polar(c, ri, a0);
|
||||
final Offset fi0 = polar(c, ri + rc, a0);
|
||||
p.quadraticBezierTo(ci0.dx, ci0.dy, fi0.dx, fi0.dy);
|
||||
final Offset fo0 = polar(c, ro - rc, a0);
|
||||
p.lineTo(fo0.dx, fo0.dy);
|
||||
final Offset co0 = polar(c, ro, a0);
|
||||
p.quadraticBezierTo(co0.dx, co0.dy, oStart.dx, oStart.dy);
|
||||
p.close();
|
||||
return p;
|
||||
}
|
||||
|
||||
/// 绘制一条圆周依赖走线(几何来自 [ArcDepRoute],与命中测试 / 拖拽共用)。
|
||||
///
|
||||
/// 关键依赖先画低透明度粗描边、再画主线;选中的连线以强调色加粗高亮。
|
||||
/// 标签不在此处直接绘制:收集后统一避让放置(见 [_placeArcChips])。
|
||||
_ArcChip? _drawDepRoute(Canvas canvas, CircularLayout layout, ArcDepRoute r) {
|
||||
final Dependency d = r.dep;
|
||||
final Color col = d.type == DepType.fs ? tokens.fs : tokens.ss;
|
||||
final bool crit = criticalDeps.contains(r.key);
|
||||
final bool sel = selectedDep == r.key;
|
||||
final Color draw = sel ? tokens.accent : col;
|
||||
|
||||
if (!r.junctionOnly) {
|
||||
final Path p = r.buildPath();
|
||||
if (crit) {
|
||||
canvas.drawPath(
|
||||
p,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 5
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = col.withValues(alpha: 0.2),
|
||||
);
|
||||
}
|
||||
canvas.drawPath(
|
||||
p,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = sel ? 2.2 : (crit ? 1.2 : (d.type == DepType.fs ? 1.0 : 0.9))
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = draw,
|
||||
);
|
||||
_arrow(canvas, r.p3, r.tipDir, draw);
|
||||
}
|
||||
|
||||
String label = d.type == DepType.fs
|
||||
? 'FS'
|
||||
: (d.offsetAngle == 0
|
||||
? 'SS'
|
||||
: 'SS+${deg2msStr(d.offsetAngle, project.units, project.cycle.durationMs, dec: 2)}');
|
||||
if (d.type == DepType.ff) label = 'FF';
|
||||
if (d.type == DepType.sf) label = 'SF';
|
||||
return _ArcChip(r.chipR, r.chipDeg, '${d.fromId}→${d.toId} $label', draw);
|
||||
}
|
||||
|
||||
/// 统一绘制圆周视图的依赖标签:沿半径方向逐级外移 / 内移避让,避免相互重叠。
|
||||
///
|
||||
/// 估算每个标签的占位矩形(文本长度 × 字号),若与已放置标签相交则按
|
||||
/// +14 / −14 / +28 / −28 … 的步长沿半径方向挪动,直到找到空位。
|
||||
void _placeArcChips(Canvas canvas, CircularLayout layout, List<_ArcChip> chips) {
|
||||
final Offset c = layout.center;
|
||||
final List<Rect> placed = <Rect>[];
|
||||
const double size = 8.5;
|
||||
for (final _ArcChip chip in chips) {
|
||||
final TextPainter tp = _tp(chip.text, size, chip.color, FontWeight.w600);
|
||||
final double w = tp.width + 10;
|
||||
const double h = 14;
|
||||
double r = chip.r;
|
||||
Rect rect = Rect.fromCenter(center: polar(c, r, chip.deg), width: w, height: h);
|
||||
for (int i = 1; i <= 10; i++) {
|
||||
if (!placed.any((Rect o) => o.inflate(1.5).overlaps(rect))) break;
|
||||
final double step = 14.0 * ((i + 1) ~/ 2);
|
||||
r = chip.r + (i.isOdd ? step : -step);
|
||||
rect = Rect.fromCenter(center: polar(c, r, chip.deg), width: w, height: h);
|
||||
}
|
||||
placed.add(rect);
|
||||
// 标签沿圆弧切线方向旋转(与动作弧同向),放在环间空隙中。
|
||||
final Offset pos = polar(c, r, chip.deg);
|
||||
final double rad = chip.deg * math.pi / 180;
|
||||
final bool flip = chip.deg > 90 && chip.deg < 270;
|
||||
canvas.save();
|
||||
canvas.translate(pos.dx, pos.dy);
|
||||
canvas.rotate(flip ? rad + math.pi : rad);
|
||||
final Rect local = Rect.fromCenter(
|
||||
center: Offset.zero,
|
||||
width: w,
|
||||
height: h,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(local, const Radius.circular(5)),
|
||||
Paint()..color = tokens.chip,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(local, const Radius.circular(5)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = chip.color,
|
||||
);
|
||||
tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2));
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
|
||||
/// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。
|
||||
///
|
||||
/// 与条形视图不同,这里会先把 [dir] 归一化;长度过短时直接返回。
|
||||
void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) {
|
||||
final double len = dir.distance;
|
||||
if (len < 0.001) return;
|
||||
final Offset u = dir / len;
|
||||
const double s = 6;
|
||||
final Offset b = tip - u * s;
|
||||
final Offset n = Offset(-u.dy, u.dx) * s * 0.5;
|
||||
final Path p = Path()
|
||||
..moveTo(tip.dx, tip.dy)
|
||||
..lineTo(b.dx + n.dx, b.dy + n.dy)
|
||||
..lineTo(b.dx - n.dx, b.dy - n.dy)
|
||||
..close();
|
||||
canvas.drawPath(p, Paint()..color = col);
|
||||
}
|
||||
|
||||
/// 以虚线绘制圆周(用于多槽位轨道内部的槽位分隔线)。
|
||||
void _dashedCircle(Canvas canvas, Offset center, double r, Paint paint,
|
||||
{double dash = 6, double gap = 5}) {
|
||||
final Path path = Path()..addOval(Rect.fromCircle(center: center, radius: r));
|
||||
for (final ui.PathMetric metric in path.computeMetrics()) {
|
||||
double dist = 0;
|
||||
while (dist < metric.length) {
|
||||
final double end = math.min(dist + dash, metric.length);
|
||||
canvas.drawPath(metric.extractPath(dist, end), paint);
|
||||
dist = end + gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制拖拽端点时的径向虚线参考与角度标注。
|
||||
void _guide(Canvas canvas, CircularLayout layout) {
|
||||
final Offset c = layout.center;
|
||||
final double deg = guideAngle!;
|
||||
final Offset p1 = polar(c, math.max(CircularLayout.r0 - 24, 8), deg);
|
||||
final Offset p2 = polar(c, layout.tickR + 6, deg);
|
||||
final Paint paint = Paint()
|
||||
..color = tokens.accent
|
||||
..strokeWidth = 1.4
|
||||
..strokeCap = StrokeCap.round;
|
||||
const double dash = 6;
|
||||
const double gap = 6;
|
||||
final double total = (p2 - p1).distance;
|
||||
if (total > 0) {
|
||||
final Offset dir = (p2 - p1) / total;
|
||||
double t = 0;
|
||||
while (t < total) {
|
||||
final double end = math.min(t + dash, total);
|
||||
canvas.drawLine(p1 + dir * t, p1 + dir * end, paint);
|
||||
t = end + gap;
|
||||
}
|
||||
}
|
||||
_text(canvas, '${deg.toStringAsFixed(1)}°', polar(c, layout.tickR + 22, deg),
|
||||
color: tokens.accent, size: 11, align: TextAlign.center, weight: FontWeight.w700);
|
||||
}
|
||||
|
||||
/// 绘制 0° 起点标记:顶部朝下的三角与“0° · 12 点钟”文字。
|
||||
void _startMarker(Canvas canvas, CircularLayout layout) {
|
||||
final Offset c = layout.center;
|
||||
// 放在刻度数字之外,避免与顶部的“0°”刻度标签重叠。
|
||||
final double r = layout.tickR + 46;
|
||||
final Offset tip = Offset(c.dx, c.dy - r - 22);
|
||||
final Path p = Path()
|
||||
..moveTo(tip.dx, tip.dy)
|
||||
..lineTo(tip.dx - 9, tip.dy - 15)
|
||||
..lineTo(tip.dx + 9, tip.dy - 15)
|
||||
..close();
|
||||
canvas.drawPath(p, Paint()..color = tokens.accent);
|
||||
_text(canvas, '0° · 12 点钟', Offset(c.dx, tip.dy - 30),
|
||||
color: tokens.accent, size: 11, align: TextAlign.center, weight: FontWeight.w600);
|
||||
}
|
||||
|
||||
/// 绘制循环方向指示:外圈一段短弧 + 沿切线的箭头,标注顺时针。
|
||||
void _directionArrow(Canvas canvas, CircularLayout layout) {
|
||||
final Offset c = layout.center;
|
||||
// 放在度数 / 时间两排标签之外,避免箭头与文字相撞。
|
||||
final double r = layout.tickR + 72;
|
||||
canvas.drawPath(
|
||||
arcPath(c, r, 25, 60),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.8
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = tokens.accent2,
|
||||
);
|
||||
// 箭头指向弧的终点,方向与切线一致(顺时针)。
|
||||
const double te = 60;
|
||||
final double trad = te * math.pi / 180;
|
||||
final Offset tip = polar(c, r, te);
|
||||
final Offset tan = Offset(math.cos(trad), math.sin(trad));
|
||||
const double s = 7;
|
||||
final Offset b = tip - tan * s;
|
||||
final Offset n = Offset(-tan.dy, tan.dx) * s * 0.5;
|
||||
final Path head = Path()
|
||||
..moveTo(tip.dx, tip.dy)
|
||||
..lineTo(b.dx + n.dx, b.dy + n.dy)
|
||||
..lineTo(b.dx - n.dx, b.dy - n.dy)
|
||||
..close();
|
||||
canvas.drawPath(head, Paint()..color = tokens.accent2);
|
||||
_text(canvas, '顺时针 CW', polar(c, r + 20, 42),
|
||||
color: tokens.accent2, size: 10, align: TextAlign.center, weight: FontWeight.w600);
|
||||
}
|
||||
|
||||
/// 绘制外围角度刻度。
|
||||
///
|
||||
/// 每 5° 一个刻度,10° 为中刻度,30° 为主刻度并标注度数;
|
||||
/// 90° 的整数倍使用强调色加粗。度数外侧再标注等价的绝对时间。
|
||||
void _ticks(Canvas canvas, CircularLayout layout) {
|
||||
final Offset c = layout.center;
|
||||
final double r = layout.tickR;
|
||||
final UnitSettings u = project.units;
|
||||
final double cycle = project.cycle.durationMs;
|
||||
for (int d = 0; d < 360; d += 5) {
|
||||
final bool major = d % 30 == 0;
|
||||
final bool mid = d % 10 == 0;
|
||||
final Offset p1 = polar(c, r, d.toDouble());
|
||||
final Offset p2 = polar(c, r + (major ? 20 : (mid ? 13 : 7)), d.toDouble());
|
||||
canvas.drawLine(
|
||||
p1,
|
||||
p2,
|
||||
Paint()
|
||||
..strokeWidth = major ? 1.4 : 1
|
||||
..color = major ? tokens.line2 : tokens.line,
|
||||
);
|
||||
if (major) {
|
||||
final Offset lp = polar(c, r + 34, d.toDouble());
|
||||
_text(canvas, '$d°', lp,
|
||||
color: d % 90 == 0 ? tokens.accent : tokens.sub,
|
||||
size: 10,
|
||||
align: TextAlign.center,
|
||||
weight: d % 90 == 0 ? FontWeight.w700 : FontWeight.normal);
|
||||
// 度数外侧增加一个时间数值(字号与度数保持一致)。
|
||||
final Offset tp = polar(c, r + 48, d.toDouble());
|
||||
_text(canvas, tvalStr(d / 360 * cycle, u, dec: u.timeUnit == TimeUnit.ms ? 0 : 1), tp,
|
||||
color: tokens.sub, size: 10, align: TextAlign.center);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 构造并布局一个 [TextPainter]。
|
||||
///
|
||||
/// 统一使用微软雅黑字体;返回已完成 layout 的实例。
|
||||
TextPainter _tp(String s, double size, Color color, FontWeight weight) {
|
||||
return TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
)..layout();
|
||||
}
|
||||
|
||||
/// 便捷文本绘制。
|
||||
///
|
||||
/// 在 [at] 处按 [align] 对齐绘制字符串 [s](默认左对齐、垂直居中)。
|
||||
/// [color] 缺省时使用 [Tokens.text]。
|
||||
void _text(Canvas canvas, String s, Offset at,
|
||||
{Color? color, double size = 12, FontWeight weight = FontWeight.normal, TextAlign align = TextAlign.left}) {
|
||||
final TextPainter tp = _tp(s, size, color ?? tokens.text, weight);
|
||||
double dx = at.dx;
|
||||
if (align == TextAlign.center) dx -= tp.width / 2;
|
||||
if (align == TextAlign.right) dx -= tp.width;
|
||||
tp.paint(canvas, Offset(dx, at.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 始终返回 `true`。
|
||||
///
|
||||
/// 绘制完全依赖每次重建的布局与外部状态,且本绘制器不做缓存,
|
||||
/// 因此保守地要求每次重绘。
|
||||
@override
|
||||
bool shouldRepaint(covariant CircularPainter old) => true;
|
||||
}
|
||||
|
||||
/// 圆周视图依赖标签的待放置描述:半径、角度、文本与颜色。
|
||||
///
|
||||
/// 先在依赖遍历中收集,再由 [CircularPainter] 统一做径向避让绘制。
|
||||
class _ArcChip {
|
||||
const _ArcChip(this.r, this.deg, this.text, this.color);
|
||||
|
||||
/// 期望的标签半径(像素)。
|
||||
final double r;
|
||||
/// 期望的标签角度(度,0° = 12 点钟、顺时针)。
|
||||
final double deg;
|
||||
/// 标签文本(如 `A1→A2 SS+0.20 s`)。
|
||||
final String text;
|
||||
/// 文本颜色(按依赖类型区分)。
|
||||
final Color color;
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/// 流程图绘制器:把时序图渲染为纵向泳道流程图(只读视图)。
|
||||
///
|
||||
/// 视觉体系与条形 / 圆周视图一致:泳道背景用环带色、依赖用 FS 绿 / SS 琥珀、
|
||||
/// 关键路径加粗带光晕、选中节点高亮描边。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
|
||||
/// 流程图 [CustomPainter] 实现。
|
||||
class FlowchartPainter extends CustomPainter {
|
||||
/// 构造。
|
||||
const FlowchartPainter({
|
||||
required this.project,
|
||||
required this.tokens,
|
||||
required this.criticalActions,
|
||||
required this.criticalDeps,
|
||||
required this.selectedIds,
|
||||
this.selectedDep,
|
||||
});
|
||||
|
||||
/// 项目数据。
|
||||
final Project project;
|
||||
/// 主题令牌。
|
||||
final Tokens tokens;
|
||||
/// 关键路径动作 id。
|
||||
final Set<String> criticalActions;
|
||||
/// 关键路径依赖(`from->to`)。
|
||||
final Set<String> criticalDeps;
|
||||
/// 选中动作 id。
|
||||
final Set<String> selectedIds;
|
||||
|
||||
/// 当前选中的依赖连线键(`from->to`);非空时该走线以强调色高亮。
|
||||
final String? selectedDep;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final FlowLayout layout = FlowLayout(
|
||||
project,
|
||||
criticalActions: criticalActions,
|
||||
criticalDeps: criticalDeps,
|
||||
);
|
||||
if (layout.nodes.isEmpty) return;
|
||||
_phaseRail(canvas, layout);
|
||||
_lanes(canvas, layout);
|
||||
_edges(canvas, layout);
|
||||
_nodes(canvas, layout);
|
||||
}
|
||||
|
||||
/// 绘制左侧相位阶段栏:把相位色带「竖起来」——窄竖带 + 旋转 90° 的分区名,
|
||||
/// 纵向与流程行严格对齐;重叠的分区台阶式向右错位(每级 20px)。
|
||||
void _phaseRail(Canvas canvas, FlowLayout layout) {
|
||||
if (layout.spans.isEmpty) return;
|
||||
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
|
||||
for (final FlowPhaseSpan s in layout.spans) {
|
||||
// 上下边界对齐到动作行边缘(统一 6px 内缩)。
|
||||
final double top = FlowLayout.marginY + s.rankTop * rowPitch - 6;
|
||||
final double bottom =
|
||||
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6;
|
||||
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep;
|
||||
final Rect r = Rect.fromLTRB(left, top, left + FlowLayout.railW, bottom);
|
||||
final RRect rr = RRect.fromRectAndRadius(r, const Radius.circular(9));
|
||||
// 视觉语言与条形视图的相位色带一致(强调色低透明度 + 细描边)。
|
||||
canvas.drawRRect(rr, Paint()..color = tokens.accent.withValues(alpha: 0.10));
|
||||
canvas.drawRRect(
|
||||
rr,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = tokens.accent.withValues(alpha: 0.45),
|
||||
);
|
||||
// 分区名:旋转 90° 竖排(从下往上读),居中于竖带。
|
||||
final TextPainter tp = _tp(s.zone.name, 10.5, tokens.sub, FontWeight.w700);
|
||||
canvas.save();
|
||||
canvas.translate(r.center.dx, r.center.dy);
|
||||
canvas.rotate(-math.pi / 2);
|
||||
tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2));
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制泳道背景带与标题(泳道 = 轨道;多槽位泳道按槽位数加宽带)。
|
||||
void _lanes(Canvas canvas, FlowLayout layout) {
|
||||
final double top = layout.bounds.top + 20;
|
||||
final double bottom = layout.bounds.bottom - 20;
|
||||
for (int i = 0; i < layout.lanes.length; i++) {
|
||||
final double left = layout.laneStartX(i) - 26;
|
||||
final double right = layout.laneStartX(i) + layout.laneWidth(i) + 26;
|
||||
final Rect band = Rect.fromLTRB(left, top, right, bottom);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(band, const Radius.circular(14)),
|
||||
Paint()..color = (i.isEven ? tokens.ringA : tokens.ringB).withValues(alpha: 0.55),
|
||||
);
|
||||
_text(canvas, '轨道 L${i + 1}', Offset((left + right) / 2, top + 16),
|
||||
color: tokens.sub, size: 11, weight: FontWeight.w700, align: TextAlign.center);
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制连线:FS 实线、SS 虚线(带偏移时间标注)、关键路径加粗光晕。
|
||||
///
|
||||
/// 走线由 [FlowLayout.routes] 统一计算(与 SVG / drawio 导出共用同一几何)。
|
||||
void _edges(Canvas canvas, FlowLayout layout) {
|
||||
for (final FlowEdgeRoute r in layout.routes) {
|
||||
final FlowEdge e = r.edge;
|
||||
final Color col = e.type == null
|
||||
? tokens.sub
|
||||
: (e.type == DepType.fs ? tokens.fs : tokens.ss);
|
||||
// 选中的依赖连线以强调色加粗高亮(拖拽调整走线时可见)。
|
||||
final bool sel = selectedDep == r.key;
|
||||
final Color draw = sel ? tokens.accent : col;
|
||||
final Path p = Path()..moveTo(r.points.first.dx, r.points.first.dy);
|
||||
for (int i = 1; i < r.points.length; i++) {
|
||||
p.lineTo(r.points[i].dx, r.points[i].dy);
|
||||
}
|
||||
if (e.critical) {
|
||||
canvas.drawPath(
|
||||
p,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 5
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = col.withValues(alpha: 0.18),
|
||||
);
|
||||
}
|
||||
final Paint line = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = sel ? 2.4 : (e.critical ? 1.8 : 1.2)
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = sel ? draw : draw.withValues(alpha: e.type == null ? 0.7 : 0.95);
|
||||
if (r.dashed) {
|
||||
_dashPath(canvas, p, line);
|
||||
} else {
|
||||
canvas.drawPath(p, line);
|
||||
}
|
||||
_arrow(canvas, r.tip, r.dir, draw);
|
||||
// FS / SS+偏移 标签
|
||||
if (e.type != null) {
|
||||
final String text = switch (e.type!) {
|
||||
DepType.fs => 'FS',
|
||||
DepType.ss => e.offset == 0
|
||||
? 'SS'
|
||||
: 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}',
|
||||
DepType.ff => 'FF',
|
||||
DepType.sf => 'SF',
|
||||
};
|
||||
_chip(canvas, r.labelAt, text, draw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 绘制节点:动作 = 圆角矩形(标题 + 时长/工位),开始 / 结束 = 胶囊。
|
||||
void _nodes(Canvas canvas, FlowLayout layout) {
|
||||
for (final FlowNode n in layout.nodes) {
|
||||
final bool sel = n.action != null && selectedIds.contains(n.id);
|
||||
final bool crit = n.action != null && criticalActions.contains(n.id);
|
||||
if (n.isStart || n.isEnd) {
|
||||
final RRect rr = RRect.fromRectAndRadius(n.rect, Radius.circular(n.rect.height / 2));
|
||||
canvas.drawRRect(rr, Paint()..color = tokens.panel2);
|
||||
canvas.drawRRect(
|
||||
rr,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2
|
||||
..color = tokens.accent,
|
||||
);
|
||||
_text(canvas, n.title, n.rect.center,
|
||||
color: tokens.accent, size: 13, weight: FontWeight.w700, align: TextAlign.center);
|
||||
continue;
|
||||
}
|
||||
final Color c = Color(n.action!.color);
|
||||
final RRect rr = RRect.fromRectAndRadius(n.rect, const Radius.circular(10));
|
||||
canvas.drawRRect(
|
||||
rr.shift(const Offset(1.5, 2)),
|
||||
Paint()..color = tokens.shadow.withValues(alpha: tokens.shadowOp),
|
||||
);
|
||||
canvas.drawRRect(rr, Paint()..color = c.withValues(alpha: 0.92));
|
||||
canvas.drawRRect(
|
||||
rr,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = sel ? 1.8 : 1
|
||||
..color = sel ? tokens.accent : tokens.selOutline.withValues(alpha: 0.25),
|
||||
);
|
||||
if (crit) {
|
||||
canvas.drawRRect(
|
||||
rr,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = tokens.crit,
|
||||
);
|
||||
}
|
||||
_text(canvas, n.title, Offset(n.rect.center.dx, n.rect.top + 21),
|
||||
color: tokens.arcText, size: 12, weight: FontWeight.w700, align: TextAlign.center);
|
||||
_text(canvas, n.subtitle, Offset(n.rect.center.dx, n.rect.top + 41),
|
||||
color: tokens.arcText.withValues(alpha: 0.85), size: 10, align: TextAlign.center);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按虚线绘制路径(SS 依赖)。
|
||||
void _dashPath(Canvas canvas, Path path, Paint paint, {double dash = 6, double gap = 4}) {
|
||||
for (final ui.PathMetric metric in path.computeMetrics()) {
|
||||
double dist = 0;
|
||||
while (dist < metric.length) {
|
||||
final double end = math.min(dist + dash, metric.length);
|
||||
canvas.drawPath(metric.extractPath(dist, end), paint);
|
||||
dist = end + gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。
|
||||
void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) {
|
||||
const double s = 7;
|
||||
final Offset b = tip - dir * s;
|
||||
final Offset n = Offset(-dir.dy, dir.dx) * s * 0.5;
|
||||
final Path p = Path()
|
||||
..moveTo(tip.dx, tip.dy)
|
||||
..lineTo(b.dx + n.dx, b.dy + n.dy)
|
||||
..lineTo(b.dx - n.dx, b.dy - n.dy)
|
||||
..close();
|
||||
canvas.drawPath(p, Paint()..color = col);
|
||||
}
|
||||
|
||||
/// 绘制 FS / SS 标签胶囊(与条形视图风格一致,字号略小)。
|
||||
void _chip(Canvas canvas, Offset center, String text, Color col) {
|
||||
final TextPainter tp = _tp(text, 8.5, col, FontWeight.w600);
|
||||
final double w = tp.width + 12;
|
||||
const double h = 14;
|
||||
final Rect r = Rect.fromCenter(center: center, width: w, height: h);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(5)),
|
||||
Paint()..color = tokens.chip,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(r, const Radius.circular(5)),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = col,
|
||||
);
|
||||
tp.paint(canvas, Offset(r.left + 6, r.center.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 构造并布局一个 [TextPainter](与其它视图一致的字体设置)。
|
||||
TextPainter _tp(String s, double size, Color color, FontWeight weight,
|
||||
{TextAlign align = TextAlign.left}) {
|
||||
return TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(
|
||||
color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'),
|
||||
),
|
||||
textDirection: ui.TextDirection.ltr,
|
||||
textAlign: align,
|
||||
)..layout();
|
||||
}
|
||||
|
||||
/// 便捷文本绘制(按 [align] 相对 [at] 对齐,垂直居中)。
|
||||
void _text(Canvas canvas, String s, Offset at,
|
||||
{required Color color,
|
||||
double size = 12,
|
||||
FontWeight weight = FontWeight.normal,
|
||||
TextAlign align = TextAlign.left}) {
|
||||
final TextPainter tp = _tp(s, size, color, weight, align: align);
|
||||
double dx = at.dx;
|
||||
if (align == TextAlign.center) dx -= tp.width / 2;
|
||||
if (align == TextAlign.right) dx -= tp.width;
|
||||
tp.paint(canvas, Offset(dx, at.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
/// 视图数据实时联动,始终重绘。
|
||||
@override
|
||||
bool shouldRepaint(covariant FlowchartPainter old) => true;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/// 时序图设计模块:PLC 流程节拍 / 相位角、条形 / 圆周 / 流程图三视图。
|
||||
///
|
||||
/// 模块入口:`lib/modules/sequence/`。新增模块请参考本文件与
|
||||
/// `lib/modules/README.md`,然后在 `lib/modules/registry.dart` 注册。
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/modules/module.dart';
|
||||
import 'package:sequence_diagram/modules/sequence/ui/sequence_ui.dart';
|
||||
import 'package:sequence_diagram/state/app_controller.dart';
|
||||
|
||||
/// 时序图模块单例。
|
||||
const SequenceModule sequenceModule = SequenceModule();
|
||||
|
||||
/// 时序图设计模块。
|
||||
class SequenceModule extends EdcModule {
|
||||
/// 构造模块。
|
||||
const SequenceModule();
|
||||
|
||||
/// 稳定 id。
|
||||
static const String moduleId = 'sequence';
|
||||
|
||||
@override
|
||||
String get id => moduleId;
|
||||
@override
|
||||
String get name => '时序图';
|
||||
@override
|
||||
String get shortName => '时序图';
|
||||
@override
|
||||
IconData get icon => Icons.waterfall_chart;
|
||||
@override
|
||||
int get accent => 0xFF4CC9F0;
|
||||
@override
|
||||
String get suffix => '.seq.json';
|
||||
@override
|
||||
bool get available => true;
|
||||
@override
|
||||
String get defaultName => '未命名-时序图';
|
||||
@override
|
||||
String get blurb => 'PLC 节拍 · 三视图';
|
||||
|
||||
@override
|
||||
void newDocument(AppController controller) {
|
||||
controller.newProject();
|
||||
}
|
||||
|
||||
@override
|
||||
void loadDocument(AppController controller, String source, {String? path}) {
|
||||
controller.loadProject(Project.decode(source), path: path);
|
||||
}
|
||||
|
||||
@override
|
||||
String encodeDocument(AppController controller) =>
|
||||
controller.project.encode(includeArch: false);
|
||||
|
||||
@override
|
||||
String documentName(AppController controller) => controller.project.name;
|
||||
|
||||
@override
|
||||
String? filePath(AppController controller) => controller.filePath;
|
||||
|
||||
@override
|
||||
bool isDirty(AppController controller) => controller.dirty;
|
||||
|
||||
@override
|
||||
Future<void> saveTo(AppController controller, String path) =>
|
||||
controller.saveAs(path);
|
||||
|
||||
@override
|
||||
Future<void> markSaved(AppController controller, String displayPath) =>
|
||||
controller.markSaved(displayPath);
|
||||
|
||||
@override
|
||||
bool isReadOnly(AppController controller) =>
|
||||
controller.project.viewState.mode == ViewMode.flow;
|
||||
|
||||
@override
|
||||
Map<ShortcutActivator, VoidCallback> buildShortcuts(ModuleUiContext ui) {
|
||||
return <ShortcutActivator, VoidCallback>{
|
||||
const SingleActivator(LogicalKeyboardKey.delete): () {
|
||||
if (!isReadOnly(ui.controller) && ui.controller.selectedId != null) {
|
||||
ui.controller.deleteAction(ui.controller.selectedId!);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildWorkspace(ModuleUiContext ui) => SequenceUi(ui).buildWorkspace();
|
||||
|
||||
@override
|
||||
Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) =>
|
||||
SequenceUi(ui).buildLeftPanel(ui.tokens, floating: floating);
|
||||
|
||||
@override
|
||||
Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) =>
|
||||
SequenceUi(ui).buildRightPanel(ui.tokens, floating: floating);
|
||||
|
||||
@override
|
||||
List<Widget> buildToolbarCenter(ModuleUiContext ui, {required bool compact}) =>
|
||||
SequenceUi(ui).buildToolbarCenter(ui.tokens, compact: compact);
|
||||
|
||||
@override
|
||||
List<Widget> buildToolbarRight(ModuleUiContext ui) =>
|
||||
SequenceUi(ui).buildToolbarRight(ui.tokens, compact: ui.compact);
|
||||
|
||||
@override
|
||||
Widget buildStatusBar(ModuleUiContext ui) =>
|
||||
SequenceUi(ui).buildStatusBar(ui.tokens);
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
/// AI 生成时序图对话框。
|
||||
///
|
||||
/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)、推理强度
|
||||
/// (高 / 最高)与生成方式(新建工程 / 在当前工程上修改)→ 在较大的自然语言
|
||||
/// 输入框中描述工艺流程或修改要求 → 点击「生成」。
|
||||
///
|
||||
/// 生成过程为**流式**:实时显示已用时、思考与输出字符数,可随时取消;
|
||||
/// 输出无法解析时自动让模型修复重试(最多两次)。
|
||||
///
|
||||
/// 安全:API Key 仅保存在内存(静态字段,便于本次会话内复用),
|
||||
/// 不写入工程文件,也不会被日志输出。
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/ai/ai_client.dart';
|
||||
import 'package:sequence_diagram/state/app_controller.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'package:sequence_diagram/ui/dialogs.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 = '';
|
||||
|
||||
/// 示例描述:与输入框灰色占位一致,可一键填入后直接编辑。
|
||||
static const String _examplePrompt =
|
||||
'一条装配线,循环 2.4 秒。上料后定位夹紧,夹紧完成再伺服下压 0.6 秒;'
|
||||
'下压完成后并行进行超声波焊接与视觉检测;检测完成分选下料,最后清洁吹气。'
|
||||
'共 3 个工位,请给出动作、相位与依赖关系。';
|
||||
|
||||
late final TextEditingController _key;
|
||||
late final TextEditingController _prompt;
|
||||
|
||||
String _model = kAiModels.first.id;
|
||||
String _effort = 'high';
|
||||
bool _obscure = true;
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
|
||||
/// 生成方式:`new` = 新建工程(整图生成);`modify` = 在当前工程上修改。
|
||||
String _mode = 'new';
|
||||
|
||||
/// 当前生成用的取消令牌(每次生成重建)。
|
||||
AiCancelToken? _token;
|
||||
/// 生成计时器(每秒刷新已用时)。
|
||||
Timer? _ticker;
|
||||
/// 已用时(秒)。
|
||||
int _secs = 0;
|
||||
/// 已接收的思考字符数(推理模型)。
|
||||
int _thinkChars = 0;
|
||||
/// 已接收的 JSON 输出字符数。
|
||||
int _outChars = 0;
|
||||
/// 当前第几次尝试(>0 表示正在自动修复上一次的输出)。
|
||||
int _attempt = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_key = TextEditingController(text: _sessionKey);
|
||||
_prompt = TextEditingController();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ticker?.cancel();
|
||||
_key.dispose();
|
||||
_prompt.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _generate() async {
|
||||
final AiCancelToken token = AiCancelToken();
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
_secs = 0;
|
||||
_thinkChars = 0;
|
||||
_outChars = 0;
|
||||
_attempt = 0;
|
||||
_token = token;
|
||||
});
|
||||
_ticker = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) setState(() => _secs++);
|
||||
});
|
||||
try {
|
||||
_sessionKey = _key.text.trim();
|
||||
final AiResult r = await AiClient.generate(
|
||||
prompt: _prompt.text,
|
||||
settings: AiSettings(apiKey: _sessionKey, model: _model, effort: _effort),
|
||||
base: _mode == 'modify' ? widget.controller.project : null,
|
||||
cancelToken: token,
|
||||
onProgress: (AiProgress p) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_thinkChars = p.reasoningChars;
|
||||
_outChars = p.contentChars;
|
||||
_attempt = p.attempt;
|
||||
});
|
||||
},
|
||||
);
|
||||
widget.controller.loadProject(r.project, dirty: true);
|
||||
final String extra = r.warnings.isEmpty ? '' : '(${r.warnings.join('、')})';
|
||||
widget.controller
|
||||
.setStatus('AI 已生成时序图(${r.project.actions.length} 个动作)$extra');
|
||||
if (mounted) Navigator.pop(context);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = '$e');
|
||||
} finally {
|
||||
_ticker?.cancel();
|
||||
_ticker = null;
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消正在进行的生成(中断 HTTP 请求)。
|
||||
void _cancel() {
|
||||
_token?.cancel();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Tokens t = context.tok;
|
||||
return Dialog(
|
||||
backgroundColor: t.dialog,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
|
||||
child: scaledDialogBox(
|
||||
context,
|
||||
880,
|
||||
620,
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
// 标题
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.auto_awesome, size: 21, color: t.accent2),
|
||||
const SizedBox(width: 8),
|
||||
Text('AI 生成时序图', style: TextStyle(color: t.text, fontSize: 17, fontWeight: FontWeight.w700)),
|
||||
const Spacer(),
|
||||
Text('自然语言 → 时序图', style: TextStyle(color: t.dim, fontSize: 11.5)),
|
||||
],
|
||||
),
|
||||
const Divider(height: 22),
|
||||
|
||||
// API Key
|
||||
Text('DeepSeek API Key', style: TextStyle(color: t.sub, fontSize: 12.5)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: _key,
|
||||
obscureText: _obscure,
|
||||
style: TextStyle(color: t.text, fontSize: 12.5),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
hintText: 'sk-...',
|
||||
hintStyle: TextStyle(color: t.dim, fontSize: 12.5),
|
||||
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: 12.5)),
|
||||
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: 12.5),
|
||||
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: 12.5)),
|
||||
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),
|
||||
|
||||
// 生成方式:新建整图 / 在当前工程上修改(增量)。
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Text('生成方式', style: TextStyle(color: t.sub, fontSize: 12.5)),
|
||||
const SizedBox(width: 12),
|
||||
SizedBox(width: 106, child: _modeChip(t, '新建工程', 'new')),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(width: 128, child: _modeChip(t, '修改当前工程', 'modify')),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_mode == 'modify'
|
||||
? '在现有工程上增删改,未涉及部分保持不变'
|
||||
: '重新生成整张时序图(替换当前工程)',
|
||||
style: TextStyle(color: t.dim, fontSize: 11),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
|
||||
// 自然语言输入(大输入框)
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Text('用自然语言描述工艺流程', style: TextStyle(color: t.sub, fontSize: 12.5)),
|
||||
const Spacer(),
|
||||
// 一键把灰色示例填入输入框,便于直接修改后生成。
|
||||
TextButton.icon(
|
||||
onPressed: _busy
|
||||
? null
|
||||
: () => setState(() => _prompt.text = _examplePrompt),
|
||||
icon: const Icon(Icons.edit_note, size: 17),
|
||||
label: const Text('编辑示例', style: TextStyle(fontSize: 12)),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: t.accent,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
minimumSize: const Size(0, 28),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
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: 12.5, height: 1.6),
|
||||
decoration: InputDecoration.collapsed(
|
||||
hintText: '例如:$_examplePrompt',
|
||||
hintStyle: TextStyle(color: t.dim, fontSize: 12.5, height: 1.6),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_error != null) ...<Widget>[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: _error == '已取消' ? t.panel2 : t.danger.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: _error == '已取消' ? t.line2 : t.danger.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: Text(_error!,
|
||||
style: TextStyle(
|
||||
color: _error == '已取消' ? t.sub : t.danger,
|
||||
fontSize: 12,
|
||||
height: 1.5)),
|
||||
),
|
||||
],
|
||||
if (_busy) ...<Widget>[
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel2,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
SizedBox(
|
||||
width: 13,
|
||||
height: 13,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: t.accent),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_attempt > 0
|
||||
? '格式有误,正在自动修复(第 ${_attempt + 1} 次尝试)· 已用时 $_secs 秒'
|
||||
: '生成中… 已用时 $_secs 秒',
|
||||
style: TextStyle(color: t.sub, fontSize: 12),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
_thinkChars > 0 || _outChars > 0
|
||||
? '思考 $_thinkChars 字 · 输出 $_outChars 字'
|
||||
: '等待模型响应…',
|
||||
style: TextStyle(color: t.dim, fontSize: 11),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
child: LinearProgressIndicator(
|
||||
minHeight: 4,
|
||||
color: t.accent2,
|
||||
backgroundColor: t.line2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 14),
|
||||
|
||||
// 操作按钮:生成 ↔ 取消生成(流式过程中可随时中断)。
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
'API Key 仅保存在本机内存,不写入工程文件。',
|
||||
style: TextStyle(color: t.dim, fontSize: 11),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (_busy) _cancel();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text('取消'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_busy
|
||||
? FilledButton.icon(
|
||||
onPressed: _cancel,
|
||||
icon: const Icon(Icons.stop_circle_outlined, size: 16),
|
||||
label: const Text('取消生成'),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: t.danger,
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
|
||||
),
|
||||
)
|
||||
: FilledButton.icon(
|
||||
onPressed: _generate,
|
||||
icon: const Icon(Icons.auto_awesome, size: 16),
|
||||
label: const Text('生成'),
|
||||
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: 12.5)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 生成方式分段按钮(新建工程 / 修改当前工程);生成中不可切换。
|
||||
Widget _modeChip(Tokens t, String label, String value) {
|
||||
final bool active = _mode == value;
|
||||
return InkWell(
|
||||
onTap: _busy ? null : () => setState(() => _mode = value),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
height: 34,
|
||||
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: 12)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
// 画布浮层:绘制在交互画布之上的固定信息面板,对应设计稿中的
|
||||
// 标题、图例、统计、实时预览与编辑工具等元素。
|
||||
//
|
||||
// 架构位置:属于纯展示层,叠加在 CanvasView 之上,通过 AppController
|
||||
// 读取项目数据;所有浮层均使用 IgnorePointer 或自身交互包裹,避免
|
||||
// 遮挡画布手势。本文件通过 LayoutBuilder 依据窗口尺寸做响应式断点,
|
||||
// 决定各面板是否显示。
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/modules/sequence/layout/layout.dart';
|
||||
import 'package:sequence_diagram/model/models.dart';
|
||||
import 'package:sequence_diagram/model/units.dart';
|
||||
import 'package:sequence_diagram/state/app_controller.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'package:sequence_diagram/ui/dialogs.dart';
|
||||
|
||||
/// 条形缩略预览的固定绘制区高度:卡片尺寸不随动作数量变化,
|
||||
/// 动作越多只会在内部压缩行距、把色条画得更细。
|
||||
const double _kMiniBarHeight = 84;
|
||||
|
||||
/// 画布浮层容器:按响应式断点组合并定位各信息面板。
|
||||
class CanvasOverlays extends StatelessWidget {
|
||||
/// 创建浮层容器,[controller] 为全局应用控制器。
|
||||
///
|
||||
/// [leftInset]/[rightInset]:侧栏收起后画布两侧的“把手”宽度,
|
||||
/// 浮层据此内缩,避免被把手遮挡。
|
||||
const CanvasOverlays({
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.leftInset = 0,
|
||||
this.rightInset = 0,
|
||||
this.showTitle = true,
|
||||
this.showPanels = true,
|
||||
});
|
||||
|
||||
/// 全局应用控制器,提供项目数据与编辑动作。
|
||||
final AppController controller;
|
||||
|
||||
/// 左侧把手占用的宽度(0 表示无把手)。
|
||||
final double leftInset;
|
||||
|
||||
/// 右侧把手占用的宽度(0 表示无把手)。
|
||||
final double rightInset;
|
||||
|
||||
/// 是否显示顶部标题(导出 PNG 时把标题纳入导出边界)。
|
||||
final bool showTitle;
|
||||
|
||||
/// 是否显示其余面板(图例 / 统计 / 工具 / 预览 / 浮动工具条)。
|
||||
///
|
||||
/// 这些属于**编辑辅助元素,不参与导出**。
|
||||
final bool showPanels;
|
||||
|
||||
/// 控制器快捷访问器。
|
||||
AppController get c => controller;
|
||||
|
||||
/// 使用 [LayoutBuilder] 获取可用尺寸,计算响应式断点后,
|
||||
/// 通过 [Stack] + [Positioned] 摆放各浮层面板。
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Tokens t = context.tok;
|
||||
final ViewMode mode = c.project.viewState.mode;
|
||||
final bool circular = mode == ViewMode.circular;
|
||||
final bool flow = mode == ViewMode.flow;
|
||||
return LayoutBuilder(
|
||||
builder: (BuildContext context, BoxConstraints constraints) {
|
||||
final double w = constraints.maxWidth;
|
||||
final double h = constraints.maxHeight;
|
||||
// ---- 响应式断点:不同尺寸下显示不同的浮层组合 ----
|
||||
// 左右边距:在基础留白上叠加侧栏把手的宽度,避免被把手遮挡。
|
||||
final double left = 18 + leftInset;
|
||||
final double right = 18 + rightInset;
|
||||
// 圆周视图左侧图例列:需要较宽较高的窗口。
|
||||
final bool showLeftColumn = circular && w >= 1180 && h >= 760;
|
||||
// 条形视图统计卡片:中等尺寸以上显示。
|
||||
final bool showStats = !circular && w >= 820 && h >= 700;
|
||||
// 编辑工具条:门槛最低,几乎始终显示。
|
||||
final bool showTools = w >= 700;
|
||||
// 预览卡片(已缩小):门槛放低,钉住侧栏后仍可见。
|
||||
final bool showPreview = w >= 720 && h >= 560;
|
||||
// 浮层整体使用 Stack 叠加,各面板按断点条件选择性插入。
|
||||
return Stack(
|
||||
children: <Widget>[
|
||||
// 顶部标题与副标题,横跨整个画布宽度,不拦截手势。
|
||||
if (showTitle)
|
||||
Positioned(
|
||||
left: left,
|
||||
top: 12,
|
||||
right: right,
|
||||
child: IgnorePointer(child: _Title(t: t, mode: mode)),
|
||||
),
|
||||
// 圆周视图左侧信息列:图例 + 选中卡片 + 依赖图例。
|
||||
if (showPanels && showLeftColumn)
|
||||
Positioned(
|
||||
left: left,
|
||||
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 (showPanels && !circular && !flow && (showStats || showTools))
|
||||
Positioned(
|
||||
left: left,
|
||||
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 (showPanels && showPreview && !flow)
|
||||
Positioned(
|
||||
right: right,
|
||||
bottom: 12,
|
||||
child: circular
|
||||
? _BarPreviewCard(t: t, c: c)
|
||||
: _CircularPreviewCard(t: t, c: c),
|
||||
),
|
||||
// 圆周视图右上角浮动工具栏(与条形视图同一套工具与按钮尺寸)。
|
||||
if (showPanels && circular)
|
||||
Positioned(
|
||||
right: right,
|
||||
top: 70,
|
||||
child: _EditTools(t: t, c: c, vertical: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 通用卡片容器:统一浮层的背景、圆角与边框样式。
|
||||
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.mode});
|
||||
|
||||
/// 主题令牌。
|
||||
final Tokens t;
|
||||
/// 当前视图模式。
|
||||
final ViewMode mode;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final String title = switch (mode) {
|
||||
ViewMode.bar => '条形时序视图',
|
||||
ViewMode.circular => '圆周时序视图',
|
||||
ViewMode.flow => '流程图视图',
|
||||
};
|
||||
// 括号说明:仅保留线型图例(流程图不重复时序视图的说明)。
|
||||
final String suffix = switch (mode) {
|
||||
ViewMode.bar => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
|
||||
ViewMode.circular => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
|
||||
ViewMode.flow => '',
|
||||
};
|
||||
return Text.rich(
|
||||
TextSpan(children: <InlineSpan>[
|
||||
TextSpan(
|
||||
text: title,
|
||||
style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
if (suffix.isNotEmpty)
|
||||
TextSpan(text: ' $suffix', style: TextStyle(color: t.dim, fontSize: 11)),
|
||||
]),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 圆周视图左侧图例:逐条列出动作的层号、相位区间与时长。
|
||||
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}'
|
||||
'${c.project.slotsOf(a.layer) > 1 ? ' · 槽 ${effectiveSlot(c.project, a) + 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, glow: true), '关键路径(线条加粗光晕)'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 图例中的示例线段:可组合实线/虚线、箭头与关键路径光晕。
|
||||
class _SampleLine extends StatelessWidget {
|
||||
const _SampleLine({required this.color, required this.dash, required this.arrow, this.glow = false});
|
||||
|
||||
/// 线条颜色。
|
||||
final Color color;
|
||||
/// 是否绘制为虚线。
|
||||
final bool dash;
|
||||
/// 是否绘制箭头。
|
||||
final bool arrow;
|
||||
/// 是否为关键路径样式(线条加粗光晕)。
|
||||
final bool glow;
|
||||
|
||||
/// 用 [_SamplePainter] 绘制示例线段。
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: 16,
|
||||
child: CustomPaint(painter: _SamplePainter(color, dash, arrow, glow)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 示例线段绘制器:按参数绘制实/虚线、箭头与关键路径光晕。
|
||||
class _SamplePainter extends CustomPainter {
|
||||
_SamplePainter(this.color, this.dash, this.arrow, this.glow);
|
||||
|
||||
/// 线条颜色。
|
||||
final Color color;
|
||||
/// 是否绘制为虚线。
|
||||
final bool dash;
|
||||
/// 是否绘制箭头。
|
||||
final bool arrow;
|
||||
/// 是否为关键路径样式(线条加粗光晕)。
|
||||
final bool glow;
|
||||
|
||||
/// 绘制示例线段本体、箭头及可选光晕。
|
||||
@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 (glow) {
|
||||
canvas.drawLine(
|
||||
Offset(0, y),
|
||||
Offset(size.width - 10, y),
|
||||
Paint()
|
||||
..color = color.withValues(alpha: 0.2)
|
||||
..strokeWidth = 7
|
||||
..strokeCap = StrokeCap.round,
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 示例线段始终重绘(开销极小)。
|
||||
@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 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)],
|
||||
];
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// 编辑工具栏(条形 / 圆周视图共用):
|
||||
/// 添加 / 编辑 / 复制 / 删除 / 层+ / 层− / 对齐。
|
||||
///
|
||||
/// - [vertical] 为真时纵向排列(圆周视图右上角),否则横向排列(条形视图左下角);
|
||||
/// - 按钮尺寸统一为原「编辑工具」条的 60%(约 40×34px),单手可点且尽量不遮挡画布。
|
||||
class _EditTools extends StatelessWidget {
|
||||
const _EditTools({required this.t, required this.c, this.vertical = false});
|
||||
|
||||
/// 主题令牌。
|
||||
final Tokens t;
|
||||
/// 全局应用控制器。
|
||||
final AppController c;
|
||||
/// 是否纵向排列(圆周视图用)。
|
||||
final bool vertical;
|
||||
|
||||
/// 按钮宽度(像素)——原 66 的 60%。
|
||||
static const double _bw = 40;
|
||||
/// 按钮高度(像素)——原 56 的 60%。
|
||||
static const double _bh = 34;
|
||||
/// 按钮间距(像素)。
|
||||
static const double _gap = 5;
|
||||
|
||||
/// 渲染工具栏;横向 ↔ 纵向由 [vertical] 决定。
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final List<Widget> buttons = <Widget>[
|
||||
_tool(Icons.add, '添加', t.ok, t.onAccent, () => c.addAction(startAngle: 0)),
|
||||
_tool(Icons.edit, '编辑', t.accent, t.onAccent, () {
|
||||
final Action? a = c.selected;
|
||||
if (a != null) showDialog<void>(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a));
|
||||
}),
|
||||
_tool(Icons.copy, '复制', t.panel, t.sub, c.duplicateSelected, border: t.line2),
|
||||
_tool(Icons.delete_outline, '删除', t.panel, t.sub,
|
||||
() => c.selectedId != null ? c.deleteAction(c.selectedId!) : null, border: t.line2),
|
||||
_tool(Icons.keyboard_arrow_up, '层+', t.panel, t.sub,
|
||||
() => c.selectedId != null ? c.changeLayer(c.selectedId!, 1) : null, border: t.line2),
|
||||
_tool(Icons.keyboard_arrow_down, '层−', t.panel, t.sub,
|
||||
() => c.selectedId != null ? c.changeLayer(c.selectedId!, -1) : null, border: t.line2),
|
||||
_tool(Icons.align_horizontal_left, '对齐', t.panel, t.sub, c.alignPhase, border: t.line2),
|
||||
];
|
||||
|
||||
final List<Widget> spaced = <Widget>[];
|
||||
for (int i = 0; i < buttons.length; i++) {
|
||||
if (i > 0) {
|
||||
spaced.add(SizedBox(width: vertical ? 0 : _gap, height: vertical ? _gap : 0));
|
||||
}
|
||||
spaced.add(buttons[i]);
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(5),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel.withValues(alpha: 0.96),
|
||||
borderRadius: BorderRadius.circular(vertical ? 12 : 10),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: vertical
|
||||
? Column(mainAxisSize: MainAxisSize.min, children: spaced)
|
||||
: Row(mainAxisSize: MainAxisSize.min, children: spaced),
|
||||
);
|
||||
}
|
||||
|
||||
/// 渲染单个工具按钮(图标 + 文字)。
|
||||
Widget _tool(IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: _bw,
|
||||
height: _bh,
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: border ?? bg),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: <Widget>[
|
||||
Icon(icon, size: 12, color: fg),
|
||||
const SizedBox(height: 1),
|
||||
Text(label,
|
||||
style: TextStyle(color: fg, fontSize: 8.5, fontWeight: FontWeight.w600, height: 1.0)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 条形节拍缩略预览卡(在圆周视图右下角显示);点击切换到条形视图。
|
||||
class _BarPreviewCard extends StatelessWidget {
|
||||
const _BarPreviewCard({required this.t, required this.c});
|
||||
|
||||
/// 主题令牌。
|
||||
final Tokens t;
|
||||
/// 全局应用控制器(用于切换视图)。
|
||||
final AppController c;
|
||||
|
||||
/// 渲染紧凑的条形缩略预览,整卡可点击切换视图。
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Project project = c.project;
|
||||
return InkWell(
|
||||
onTap: () => c.setViewMode(ViewMode.bar),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: _Card(
|
||||
t: t,
|
||||
width: 150,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.bar_chart, size: 13, color: t.accent),
|
||||
const SizedBox(width: 5),
|
||||
Text('条形预览', style: TextStyle(color: t.sub, fontSize: 10.5, fontWeight: FontWeight.w600)),
|
||||
const Spacer(),
|
||||
Icon(Icons.chevron_right, size: 14, color: t.dim),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
// 预览区固定高度(与动作数量无关):动作再多也不会撑大预览卡,
|
||||
// 只会在内部压缩行距 / 缩小线条(见 _MiniBarPainter)。
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: _kMiniBarHeight,
|
||||
child: CustomPaint(
|
||||
size: Size.infinite,
|
||||
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 int n = project.actions.length;
|
||||
final double w = size.width - 4;
|
||||
// 行高按可用高度自适应,保证小预览里也排得下。
|
||||
final double pitch = n == 0 ? 12 : math.min(12, (size.height - 16) / n);
|
||||
// 缩略图里的动作条是一条细线(约 2px);动作越多行距越紧、线越细,
|
||||
// 下限 0.5px,保证固定高度的预览区内不重叠、不溢出。
|
||||
final double rh = math.min(2.0, math.max(pitch * 0.6, 0.5));
|
||||
for (int i = 0; i < n; i++) {
|
||||
final Action a = project.actions[i];
|
||||
final double y = i * pitch + (pitch - rh) / 2;
|
||||
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),
|
||||
Radius.circular(rh / 2),
|
||||
);
|
||||
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), Radius.circular(rh / 2)),
|
||||
Paint()..color = Color(a.color).withValues(alpha: t.tailOp),
|
||||
);
|
||||
}
|
||||
}
|
||||
final double baseY = n * pitch + 3;
|
||||
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: 9)),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
tp.paint(canvas, Offset(2, baseY + 2));
|
||||
final TextPainter tp2 = TextPainter(
|
||||
text: TextSpan(text: tfmt(project.cycle.durationMs, project.units), style: TextStyle(color: t.dim, fontSize: 9)),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
tp2.paint(canvas, Offset(size.width - 2 - tp2.width, baseY + 2));
|
||||
}
|
||||
|
||||
/// 预览始终重绘(数据实时联动)。
|
||||
@override
|
||||
bool shouldRepaint(covariant _MiniBarPainter old) => true;
|
||||
}
|
||||
|
||||
/// 圆周节拍缩略预览卡(在条形视图右下角显示);点击切换到圆周视图。
|
||||
class _CircularPreviewCard extends StatelessWidget {
|
||||
const _CircularPreviewCard({required this.t, required this.c});
|
||||
|
||||
/// 主题令牌。
|
||||
final Tokens t;
|
||||
/// 全局应用控制器(用于切换视图)。
|
||||
final AppController c;
|
||||
|
||||
/// 渲染紧凑的圆周缩略预览,整卡可点击切换视图。
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Project project = c.project;
|
||||
return InkWell(
|
||||
onTap: () => c.setViewMode(ViewMode.circular),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: _Card(
|
||||
t: t,
|
||||
width: 150,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.donut_large, size: 13, color: t.accent),
|
||||
const SizedBox(width: 5),
|
||||
Text('圆周预览', style: TextStyle(color: t.sub, fontSize: 10.5, fontWeight: FontWeight.w600)),
|
||||
const Spacer(),
|
||||
Icon(Icons.chevron_right, size: 14, color: t.dim),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 112,
|
||||
child: CustomPaint(
|
||||
size: Size.infinite,
|
||||
painter: _MiniCircularPainter(project, t),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 圆周缩略预览绘制器:每层一环,绘制同心圆与动作圆弧。
|
||||
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;
|
||||
// 自适应半径:把圆环铺满预览框(顶部为方向箭头预留约 26px)。
|
||||
final double maxR = math.max(math.min(size.width, size.height) / 2 - 24, 24);
|
||||
final double r0 = n <= 1 ? maxR * 0.6 : maxR * 0.34;
|
||||
final double pitch = n <= 1 ? 0 : (maxR - r0) / (n - 1);
|
||||
// 缩略图里的环与动作弧是一条细线;层数越多环距越紧、线宽随之收细,
|
||||
// 避免在固定大小的预览框里叠成一团。
|
||||
final double pw = math.min(2.0, math.max(pitch <= 0 ? 2.0 : pitch * 0.7, 0.5));
|
||||
canvas.drawCircle(c, r0 + (n - 1) * pitch + pw / 2, 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 / 2;
|
||||
final Path arrow = Path()
|
||||
..moveTo(c.dx, c.dy - tip - 6)
|
||||
..lineTo(c.dx - 7, c.dy - tip - 18)
|
||||
..lineTo(c.dx + 7, c.dy - tip - 18)
|
||||
..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;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user