Files
EasyDesignCollection/lib/state/app_controller.dart
T

2420 lines
87 KiB
Dart
Raw Normal View History

2026-09-18 16:50:12 +08:00
/// 应用状态控制器:连接模型层、持久化层与 UI 的中枢。
///
/// 作为 [ChangeNotifier],它持有当前 [Project]、撤销/重做栈、脏标记、自动保存
/// 定时器与关键路径缓存;所有修改项目的方法最终都会经由 [_mutate] 或显式
/// [notifyListeners] 触发界面刷新。
///
/// 架构位置:UI 只读取本控制器暴露的状态并调用其方法,不直接修改模型;
/// 持久化通过 [Storage] 单例完成;关键路径由 [_recomputeCritical] 计算。
library;
import 'dart:async';
import 'dart:convert';
import 'dart:io' show File, Platform;
2026-09-18 16:50:12 +08:00
import 'dart:math' as math;
import 'dart:typed_data';
2026-09-18 16:50:12 +08:00
import 'package:flutter/material.dart' hide Action;
import '../arch/arch_models.dart';
import '../arch/arch_samples.dart';
import '../persistence/android_docs.dart';
import '../sketch/sketch_models.dart';
import '../sketch/sketch_solver.dart';
import '../version.dart';
import '../layout/dep_routes.dart';
2026-09-18 16:50:12 +08:00
import '../layout/layout.dart';
import '../layout/flow_layout.dart';
2026-09-18 16:50:12 +08:00
import '../model/models.dart';
import '../model/units.dart';
import '../persistence/storage.dart';
/// 全局应用控制器(继承 [ChangeNotifier])。
class AppController extends ChangeNotifier {
/// 构造控制器。
///
/// 参数 [project]:初始项目;为 null 时使用 [Project.demo] 并标记为已修改
/// (因为演示数据尚未保存到文件)。
AppController({Project? project})
: _project = _syncLaneFloor(project ?? Project.demo()),
2026-09-18 16:50:12 +08:00
_dirty = project == null;
/// 当前项目数据(唯一可变引用,替换时整体赋值)。
Project _project;
/// 当前主题亮度(默认浅色 / 白底)。
Brightness _brightness = Brightness.light;
/// 当前顶层设计模块(时序图 / 架构图);仅运行时状态,不随文件保存。
AppMode _appMode = AppMode.sequence;
/// 架构图当前工具。
ArchTool _archTool = ArchTool.select;
/// 架构图画笔颜色(新图形默认色)。
int _archColor = kArchPalette[0];
/// 架构图连线默认走线方式(直线 / 正交折线)。
ArchRoute _archRoute = ArchRoute.straight;
/// 架构图网格吸附开关相关的运行时设置。
/// 正交模式(F8):移动约束到水平 / 垂直主轴。
bool _archOrtho = false;
/// 极轴追踪(F10):移动方向吸附到设定角度的整数倍。
bool _archPolar = false;
/// 极轴角度(度,默认 15)。
double _archPolarDeg = 15;
/// 四边标尺显示开关(默认开,Adobe 风格)。
bool _archRulers = true;
/// 架构图当前选中元素 id 列表(运行时状态,支持多选)。
List<String> _archSelIds = const <String>[];
/// 是否处于参数化草图模式。
bool _sketchMode = false;
/// 草图当前工具。
SketchTool _sketchTool = SketchTool.select;
/// 草图选中 id(点 / 实体 / 尺寸混选)。
List<String> _sketchSelIds = const <String>[];
/// 草图待执行的约束命令(Creo 风格:先选命令,再点对象执行;null = 无)。
SketchConsType? _sketchPendingCons;
/// 草图待执行的尺寸命令(null = 无)。
SketchDimType? _sketchPendingDim;
/// 命令模式下已拾取的对象 id(点 / 实体)。
List<String> _sketchPendingIds = const <String>[];
/// 新标注尺寸后待编辑的尺寸 id(视图弹出数值编辑框用)。
String? _sketchDimToEdit;
/// 架构图画布视口尺寸(由画布回填,不触发通知)。
Size _archViewport = Size.zero;
/// 「识别演示」令牌:递增一次,架构图画布收到后播放识别动画。
int _archPlayToken = 0;
/// 是否已获得有效授权(有效时才允许导出 SVG / PNG / drawio)。
///
/// 1.3.4 起授权校验临时冻结([kLicenseRequired] = false):始终视为已授权,
/// 待功能丰富后再恢复校验。
bool _licensed = false;
/// 是否已授权(授权冻结期间恒为 true)。
bool get licensed => !kLicenseRequired || _licensed;
/// 设置授权状态并刷新(启动时校验 / 重新读取 .lic 后调用)。
void setLicensed(bool value) {
if (_licensed == value) return;
_licensed = value;
notifyListeners();
}
2026-09-18 16:50:12 +08:00
/// 当前项目对应的文件路径;null 表示尚未保存。
String? _filePath;
/// 架构图文档的独立文件路径(`*.arch.json`);null 表示尚未保存。
String? _archFilePath;
/// 当前模块对应的文件路径(标题 / 状态显示用)。
String? get currentFilePath =>
_appMode == AppMode.architecture ? _archFilePath : _filePath;
/// 架构图文档文件路径。
String? get archFilePath => _archFilePath;
2026-09-18 16:50:12 +08:00
/// 是否有未保存修改。
bool _dirty;
/// 画布视口尺寸(由 [CanvasView] 在布局阶段回填)。
///
/// 用于把「缩放锚点」定位到视口中心、以及 [fitView] 计算适配比例;
/// 属于纯测量值,变更时**不**触发 [notifyListeners],避免重建循环。
Size _viewport = Size.zero;
/// 当前画布视口尺寸(逻辑像素)。
Size get viewport => _viewport;
/// 由画布回填视口尺寸(不通知监听者)。
void setViewport(Size s) {
_viewport = s;
}
/// 撤销栈(保存历史项目快照,最多 200 条)。
final List<Project> _undo = <Project>[];
/// 重做栈。
final List<Project> _redo = <Project>[];
/// 周期自动保存定时器。
Timer? _autosaveTimer;
/// 状态栏文本。
String _status = '就绪';
/// 控制器是否已释放([dispose] 之后置真,用于拦截迟到的回调)。
bool _disposed = false;
2026-09-18 16:50:12 +08:00
/// 最近一次保存时间。
DateTime? _lastSavedAt;
/// 关键路径上的动作 id 集合。
Set<String> _criticalActions = <String>{};
/// 关键路径上的依赖边集合(形如 `from->to`)。
Set<String> _criticalDeps = <String>{};
/// 当前项目。
Project get project => _project;
/// 当前主题亮度。
Brightness get brightness => _brightness;
/// 当前文件路径。
String? get filePath => _filePath;
/// 是否存在未保存修改。
bool get dirty => _dirty;
/// 是否可撤销。
bool get canUndo => _undo.isNotEmpty;
/// 是否可重做。
bool get canRedo => _redo.isNotEmpty;
/// 状态栏文本。
String get status => _status;
/// 最近保存时间。
DateTime? get lastSavedAt => _lastSavedAt;
/// 关键路径动作集合(只读)。
Set<String> get criticalActions => _criticalActions;
/// 关键路径依赖集合(只读)。
Set<String> get criticalDeps => _criticalDeps;
/// 当前选中动作 id 列表(支持 Ctrl 多选)。
List<String> get selectedIds => _project.viewState.selectedIds;
/// 主选中动作 id(列表首项)。
String? get selectedId => _project.viewState.selectedId;
/// 判断动作 [id] 是否被选中。
bool isSelected(String id) => _project.viewState.isSelected(id);
/// 主选中动作对象;无选中时为 null。
Action? get selected => _project.actionById(selectedId);
/// 当前选中的动作对象列表。
List<Action> get selectedActions =>
_project.viewState.selectedIds.map(_project.actionById).whereType<Action>().toList();
/// 启动控制器:先计算关键路径,再启动每 5 秒一次的自动保存。
void start() {
_recomputeCritical();
_autosaveTimer = Timer.periodic(const Duration(seconds: 5), (_) => _autosave());
}
/// 释放资源:取消自动保存定时器并调用父类 dispose。
@override
void dispose() {
_disposed = true;
2026-09-18 16:50:12 +08:00
_autosaveTimer?.cancel();
super.dispose();
}
/// 自动保存当前项目(内部方法,异常静默忽略以避免打断编辑)。
///
/// 同时承担两件事:
/// 1. 崩溃恢复快照(每 5 秒写入 Storage,与文档文件无关);
/// 2. 文档自动保存(按 [Project.autoSaveMinutes] 的间隔把文档写回文件)。
2026-09-18 16:50:12 +08:00
Future<void> _autosave() async {
try {
await Storage.instance.writeAutosave(
_project,
projectPath: _filePath,
clean: !_dirty,
);
} catch (_) {}
await _autoSaveDocument();
}
/// 文档自动保存:启用、已保存过路径且有未保存修改时,按间隔写回文件。
///
/// - 间隔 = [Project.autoSaveMinutes](默认 10 分钟,1–240);
/// - 以 [_lastSavedAt] 为基准:任何一次手动 / 自动保存都会重置计时;
/// - 时序图写 `*.seq.json`(不含架构图部分);架构图写 `*.arch.json`;
/// 安卓写入公共 Documents,桌面写文件并同步 `.bak` 备份。
Future<void> _autoSaveDocument() async {
final String? path =
_appMode == AppMode.architecture ? _archFilePath : _filePath;
if (!_project.autoSaveEnabled || !_dirty || path == null) return;
final DateTime now = DateTime.now();
// 从未保存过时间戳(如刚打开文件):以“现在”为基准,等满一个间隔再自动保存。
if (_lastSavedAt == null) {
_lastSavedAt = now;
return;
}
final int minutes =
_project.autoSaveMinutes < 1 ? 1 : (_project.autoSaveMinutes > 240 ? 240 : _project.autoSaveMinutes);
if (now.difference(_lastSavedAt!).inSeconds < minutes * 60) return;
_lastSavedAt = now;
try {
if (_appMode == AppMode.architecture) {
final String json = _project.arch.encode();
if (AndroidDocs.isAvailable) {
await AndroidDocs.saveFile(
_baseName(path),
Uint8List.fromList(utf8.encode(json)),
mime: 'application/json',
);
} else {
await Storage.instance.backupExisting(path);
await File(path).writeAsString(json, flush: true);
}
} else if (AndroidDocs.isAvailable) {
await AndroidDocs.saveFile(
_baseName(path),
Uint8List.fromList(utf8.encode(_project.encode(includeArch: false))),
mime: 'application/json',
);
} else {
await Storage.instance.saveProject(path, _project);
}
_dirty = false;
_status = '已自动保存 ${_baseName(path)}';
} catch (_) {
_status = '自动保存失败(可手动 Ctrl+S 重试)';
}
notifyListeners();
}
/// 设置自动保存(开关与间隔分钟;间隔钳制到 1–240)。
void setAutoSave({bool? enabled, int? minutes}) {
final bool e = enabled ?? _project.autoSaveEnabled;
final int m = (minutes ?? _project.autoSaveMinutes).clamp(1, 240);
if (e == _project.autoSaveEnabled && m == _project.autoSaveMinutes) return;
_project = _project.copyWith(autoSaveEnabled: e, autoSaveMinutes: m);
_dirty = true;
_status = e ? '自动保存:每 $m 分钟' : '自动保存:已关闭';
notifyListeners();
2026-09-18 16:50:12 +08:00
}
/// 退出前将自动保存标记为“干净”,表示已正常关闭无需恢复。
Future<void> markCleanOnExit() async {
try {
await Storage.instance.writeAutosave(
_project,
projectPath: _filePath,
clean: true,
);
} catch (_) {}
}
/// 更新状态栏文本并刷新界面。
void setStatus(String s) {
_status = s;
notifyListeners();
}
/// 以 [next] 替换当前项目并记录一次可撤销的历史。
///
/// 副作用:压入 [_undo](超出 200 条丢弃最旧)、清空 [_redo]、置脏标记、
/// 可选更新 [status]、重算关键路径并通知监听者。
void _mutate(Project next, {String? status}) {
_undo.add(_project);
if (_undo.length > 200) _undo.removeAt(0);
_redo.clear();
_project = _syncLaneFloor(next);
2026-09-18 16:50:12 +08:00
_dirty = true;
if (status != null) _status = status;
_recomputeCritical();
notifyListeners();
}
/// 维护「保留空泳道」的保底泳道数 [Project.minLaneCount]:
/// - 开启时只增不减(动作被全部移走的泳道保留、序号不变);
/// - 关闭时收缩为当前实际使用的层数(空泳道自动移除)。
static Project _syncLaneFloor(Project p) {
int maxLayer = -1;
for (final Action a in p.actions) {
if (a.layer > maxLayer) maxLayer = a.layer;
}
final int want = p.keepEmptyLanes
? (p.minLaneCount > maxLayer + 1 ? p.minLaneCount : maxLayer + 1)
: maxLayer + 1;
if (want < 0 || want == p.minLaneCount) return p;
return p.copyWith(minLaneCount: want);
}
2026-09-18 16:50:12 +08:00
/// 撤销:弹出 [_undo] 顶部的快照并压入 [_redo],重算关键路径后刷新。
void undo() {
if (_undo.isEmpty) return;
_redo.add(_project);
_project = _undo.removeLast();
_dirty = true;
_status = '撤销';
_recomputeCritical();
notifyListeners();
}
/// 重做:与 [undo] 对称,从 [_redo] 恢复快照。
void redo() {
if (_redo.isEmpty) return;
_undo.add(_project);
_project = _redo.removeLast();
_dirty = true;
_status = '重做';
_recomputeCritical();
notifyListeners();
}
/// 在深色/浅色主题之间切换并刷新界面。
void toggleTheme() {
_brightness = _brightness == Brightness.dark ? Brightness.light : Brightness.dark;
notifyListeners();
}
/// 直接设置主题亮度(软件设置用)。
void setTheme(Brightness b) {
if (_brightness == b) return;
_brightness = b;
notifyListeners();
}
// ============ 设计合集(模块切换)与架构图 ============
/// 当前顶层设计模块(时序图 / 架构图)。
AppMode get appMode => _appMode;
/// 切换顶层设计模块并刷新界面(品牌菜单 / 首页调用)。
void setAppMode(AppMode m) {
if (_appMode == m) return;
_appMode = m;
_status = switch (m) {
AppMode.home => '首页',
AppMode.sequence => '时序图设计',
AppMode.architecture => '架构图设计 · 手绘识别',
};
notifyListeners();
}
/// 返回首页(空白启动工作台):关闭当前文档视图。
///
/// 语义上「首页 = 没有打开的文档」:清除脏标记与文件路径
/// (当前文档数据在进入新模块时会由新建文档替换)。
/// 外壳在离开「有未保存修改的文档」前负责弹窗确认。
void goHome() {
final bool changed = _appMode != AppMode.home ||
_dirty ||
_filePath != null ||
_archFilePath != null;
_appMode = AppMode.home;
_dirty = false;
_filePath = null;
_archFilePath = null;
_status = '首页';
if (changed) notifyListeners();
}
/// 架构图当前工具。
ArchTool get archTool => _archTool;
/// 切换架构图工具。
void setArchTool(ArchTool tool) {
if (_archTool == tool) return;
_archTool = tool;
_status = switch (tool) {
ArchTool.select => '工具:选择',
ArchTool.pen => '工具:手绘(松手自动识别)',
ArchTool.connect => '工具:连线(拖到图形自动吸附)',
ArchTool.eraser => '工具:橡皮(拖过图形 / 墨迹 / 连线即擦除)',
};
notifyListeners();
}
/// 手绘是否「松手自动识别」。
///
/// 关闭时:笔迹先保留为墨迹,点「识别」按钮统一确认识别——平板手写
/// 识别误判较多时的推荐模式(安卓默认关闭,桌面默认开启)。
bool _archAutoRecognize = !Platform.isAndroid;
/// 手绘是否松手自动识别。
bool get archAutoRecognize => _archAutoRecognize;
/// 切换手绘识别模式(自动 / 手动确认)。
void setArchAutoRecognize(bool on) {
if (_archAutoRecognize == on) return;
_archAutoRecognize = on;
_status = on
? '手绘:松手自动识别'
: '手绘:手动确认识别(画完点顶部「识别」按钮)';
notifyListeners();
}
/// 橡皮擦开始:压一次撤销快照(一次连续擦除 = 一步撤销)。
void beginArchErase() {
_undo.add(_project);
if (_undo.length > 200) _undo.removeAt(0);
_redo.clear();
}
/// 擦除对象(图形 / 墨迹 / 连线;不入撤销栈,由 [beginArchErase] 快照统一回退)。
///
/// 返回实际擦除数量;删除图形时吸附其上的连线一并移除。
int eraseArchIds(Set<String> ids) {
final Set<String> hit = <String>{
for (final String id in ids)
if (arch.shapeById(id) != null ||
arch.strokeById(id) != null ||
arch.connectorById(id) != null)
id,
};
if (hit.isEmpty) return 0;
_project = _project.copyWith(arch: arch.removeIds(hit));
_dirty = true;
notifyListeners();
return hit.length;
}
// ===================== 参数化草图 =====================
/// 是否处于参数化草图模式。
bool get sketchMode => _sketchMode;
/// 草图当前工具。
SketchTool get sketchTool => _sketchTool;
/// 草图选中 id。
List<String> get sketchSelIds => _sketchSelIds;
/// 当前草图文档。
SketchDoc get sketch => arch.sketch;
/// 进入 / 退出参数化草图模式。
void setSketchMode(bool on) {
if (_sketchMode == on) return;
_sketchMode = on;
_sketchTool = SketchTool.select;
_sketchSelIds = const <String>[];
_cancelSketchCommandInternal();
if (on) _archSelIds = const <String>[];
_status = on ? '参数化草图:约束 + 驱动尺寸(改尺寸即驱动几何)' : '架构图设计';
notifyListeners();
}
/// 切换草图工具。
void setSketchTool(SketchTool t) {
if (_sketchTool == t) return;
_sketchTool = t;
_sketchSelIds = const <String>[];
_cancelSketchCommandInternal();
_status = switch (t) {
SketchTool.select => '草图:选择 / 拖动(约束实时求解)',
SketchTool.line => '草图:直线(点两下;近轴自动水平 / 竖直)',
SketchTool.circle => '草图:圆(点圆心,再点半径点)',
SketchTool.arc => '草图:圆弧(圆心 → 起点 → 终点)',
SketchTool.rect => '草图:矩形(对角两点,自动水平 / 竖直)',
SketchTool.trim => '草图:修剪(点击线段删除该段)',
};
notifyListeners();
}
/// 替换草图选择。
void selectSketchIds(List<String> ids) {
if (_sameIds(ids, _sketchSelIds)) return;
_sketchSelIds = List<String>.of(ids);
notifyListeners();
}
/// 切换某个草图对象的选中状态(Shift 点选)。
void toggleSketchId(String id) {
final List<String> cur = List<String>.of(_sketchSelIds);
if (cur.contains(id)) {
cur.remove(id);
} else {
cur.add(id);
}
_sketchSelIds = cur;
notifyListeners();
}
// ---- 约束 / 尺寸命令流(Creo 风格:先点命令,再点对象执行) ----
/// 待执行的约束命令(null = 无)。
SketchConsType? get sketchPendingCons => _sketchPendingCons;
/// 待执行的尺寸命令(null = 无)。
SketchDimType? get sketchPendingDim => _sketchPendingDim;
/// 命令模式下已拾取的对象 id。
List<String> get sketchPendingIds => _sketchPendingIds;
/// 新标注尺寸后待编辑的尺寸 id(视图弹数值编辑框后调用
/// [clearSketchDimToEdit])。
String? get sketchDimToEdit => _sketchDimToEdit;
/// 清除「待编辑尺寸」标记(视图完成弹窗后调用)。
void clearSketchDimToEdit() {
_sketchDimToEdit = null;
}
/// 进入约束命令(再次点击同一命令 = 取消)。
void beginSketchConstraint(SketchConsType type) {
if (_sketchPendingCons == type &&
_sketchPendingDim == null &&
_sketchPendingIds.isEmpty) {
cancelSketchCommand();
return;
}
_sketchPendingCons = type;
_sketchPendingDim = null;
_sketchPendingIds = const <String>[];
_status = _consHint(type, 0);
notifyListeners();
}
/// 进入尺寸命令(再次点击同一命令 = 取消)。
void beginSketchDim(SketchDimType type) {
if (_sketchPendingDim == type &&
_sketchPendingCons == null &&
_sketchPendingIds.isEmpty) {
cancelSketchCommand();
return;
}
_sketchPendingDim = type;
_sketchPendingCons = null;
_sketchPendingIds = const <String>[];
_status = _dimHint(type, 0);
notifyListeners();
}
/// 取消当前草图命令(Esc / 面板「取消」)。
void cancelSketchCommand() {
if (_sketchPendingCons == null &&
_sketchPendingDim == null &&
_sketchPendingIds.isEmpty) {
return;
}
_cancelSketchCommandInternal();
_status = '草图:选择 / 拖动(约束实时求解)';
notifyListeners();
}
void _cancelSketchCommandInternal() {
_sketchPendingCons = null;
_sketchPendingDim = null;
_sketchPendingIds = const <String>[];
}
/// 命令模式点选(视图命中后调用;约束 / 尺寸命令共用)。
void sketchCommandPick(SketchHit hit) {
final SketchDoc d = arch.sketch;
if (_sketchPendingDim != null) {
_sketchDimPick(d, _sketchPendingDim!, hit);
return;
}
if (_sketchPendingCons != null) {
_sketchConsPick(d, _sketchPendingCons!, hit);
}
}
/// 约束命令点选:单选约束点一下;双对象约束依次点选;非法对象给出提示。
void _sketchConsPick(SketchDoc d, SketchConsType type, SketchHit hit) {
final String? pid = hit.pointId;
final String? eid = hit.entityId;
// 单选约束:一条直线即执行。
if (type == SketchConsType.horizontal || type == SketchConsType.vertical) {
final SketchEntity? e = d.entityById(eid);
if (e == null || e.kind != SketchKind.line) {
_status = _consHint(type, 0);
notifyListeners();
return;
}
_applyConstraint(type, e.id, '');
_status = '已加${sketchConsLabel(type)}约束 · ${_consHint(type, 0)}';
notifyListeners();
return;
}
// 点在实体上:点 / 实体任意顺序;同类再点 = 替换。
if (type == SketchConsType.pointOnEntity) {
if (pid == null && eid == null) {
_status = _consHint(type, _sketchPendingIds.length);
notifyListeners();
return;
}
final bool pickIsPoint = pid != null;
final List<String> picks = <String>[
for (final String id in _sketchPendingIds)
if ((d.pointById(id) != null) != pickIsPoint) id,
pid ?? eid!,
];
String? pointId;
String? entityId;
for (final String id in picks) {
if (d.pointById(id) != null) pointId = id;
if (d.entityById(id) != null) entityId = id;
}
if (pointId != null && entityId != null) {
_applyConstraint(SketchConsType.pointOnEntity, pointId, entityId);
_sketchPendingIds = const <String>[];
_status = '已加「点在线上」约束 · ${_consHint(type, 0)}';
} else {
_sketchPendingIds = picks;
_status = _consHint(type, picks.length);
}
notifyListeners();
return;
}
// 双对象约束:依次点选(再点同一对象 = 撤销该次拾取)。
if (eid == null) {
_status = _consHint(type, _sketchPendingIds.length);
notifyListeners();
return;
}
final List<String> picks = List<String>.of(_sketchPendingIds);
if (picks.contains(eid)) {
picks.remove(eid);
_sketchPendingIds = picks;
_status = _consHint(type, picks.length);
notifyListeners();
return;
}
picks.add(eid);
if (picks.length < 2) {
_sketchPendingIds = picks;
_status = _consHint(type, 1);
notifyListeners();
return;
}
if (!sketchCanConstrain(d, type, picks)) {
_status = '${sketchConsLabel(type)}:所选对象类型不符合';
_sketchPendingIds = const <String>[];
notifyListeners();
return;
}
_applyConstraint(type, picks[0], picks[1]);
_sketchPendingIds = const <String>[];
_status = '已加${sketchConsLabel(type)}约束 · ${_consHint(type, 0)}';
notifyListeners();
}
/// 尺寸命令点选:点够对象即自动标注(当前测量值),随后可改值驱动。
void _sketchDimPick(SketchDoc d, SketchDimType type, SketchHit hit) {
final String? pid = hit.pointId;
final String? eid = hit.entityId;
switch (type) {
case SketchDimType.length:
final SketchEntity? e = d.entityById(eid);
if (e == null || e.kind != SketchKind.line) {
_status = _dimHint(type, 0);
notifyListeners();
return;
}
_createDim(type, e.id, '');
case SketchDimType.radius:
final SketchEntity? e = d.entityById(eid);
if (e == null || e.kind == SketchKind.line) {
_status = _dimHint(type, 0);
notifyListeners();
return;
}
_createDim(type, e.id, '');
case SketchDimType.angle:
if (eid == null || d.entityById(eid)?.kind != SketchKind.line) {
_status = _dimHint(type, _sketchPendingIds.length);
notifyListeners();
return;
}
_dimTwoEntityPick(d, type, eid);
case SketchDimType.distance:
if (pid == null) {
_status = _dimHint(type, _sketchPendingIds.length);
notifyListeners();
return;
}
if (_sketchPendingIds.contains(pid)) {
_sketchPendingIds =
<String>[for (final String x in _sketchPendingIds) if (x != pid) x];
_status = _dimHint(type, _sketchPendingIds.length);
notifyListeners();
return;
}
final List<String> picks = <String>[..._sketchPendingIds, pid];
if (picks.length < 2) {
_sketchPendingIds = picks;
_status = _dimHint(type, 1);
notifyListeners();
return;
}
_sketchPendingIds = const <String>[];
_createDim(type, picks[0], picks[1]);
}
}
/// 角度尺寸:两条直线依次点选。
void _dimTwoEntityPick(SketchDoc d, SketchDimType type, String eid) {
final List<String> picks = List<String>.of(_sketchPendingIds);
if (picks.contains(eid)) {
picks.remove(eid);
_sketchPendingIds = picks;
_status = _dimHint(type, picks.length);
notifyListeners();
return;
}
picks.add(eid);
if (picks.length < 2) {
_sketchPendingIds = picks;
_status = _dimHint(type, 1);
notifyListeners();
return;
}
_sketchPendingIds = const <String>[];
_createDim(type, picks[0], picks[1]);
}
/// 应用约束(构建 + 求解 + 入撤销栈)。
void _applyConstraint(SketchConsType type, String a, String b) {
final SketchDoc d = arch.sketch;
final SketchConstraint k = SketchConstraint(
id: sketchNewId('K', d.allIds),
type: type,
a: a,
b: b,
);
final SketchSolveResult r = solveSketch(
d.copyWith(constraints: <SketchConstraint>[...d.constraints, k]),
);
changeSketch(
(_) => r.doc,
status: '添加约束:${sketchConsLabel(type)}'
'${r.converged ? '' : '(冲突:未完全满足)'}',
);
}
/// 创建驱动尺寸(当前测量值)并标记为「待编辑」(视图弹数值框)。
void _createDim(SketchDimType type, String a, String b) {
final SketchDoc d = arch.sketch;
final double value = sketchMeasure(d, type, a, b) ?? 10;
final SketchDim nd = SketchDim(
id: sketchNewId('D', d.allIds),
type: type,
value: value,
a: a,
b: b,
);
_sketchDimToEdit = nd.id;
final SketchSolveResult r = solveSketch(
d.copyWith(dims: <SketchDim>[...d.dims, nd]),
);
changeSketch(
(_) => r.doc,
status: '标注${sketchDimLabel(type)}:${sketchDimText(nd)}(输入数值可精确驱动)',
);
}
/// 约束命令的分步提示。
String _consHint(SketchConsType type, int picked) => switch (type) {
SketchConsType.horizontal => '水平约束:点击一条直线',
SketchConsType.vertical => '竖直约束:点击一条直线',
SketchConsType.parallel =>
picked == 0 ? '平行约束:点击第一条直线' : '平行约束:点击第二条直线',
SketchConsType.perpendicular =>
picked == 0 ? '垂直约束:点击第一条直线' : '垂直约束:点击第二条直线',
SketchConsType.equal =>
picked == 0 ? '相等约束:点击第一个对象' : '相等约束:点击第二个对象',
SketchConsType.concentric => picked == 0
? '同心约束:点击第一个圆 / 弧'
: '同心约束:点击第二个圆 / 弧',
SketchConsType.tangent => picked == 0
? '相切约束:点击第一个对象(线 / 圆)'
: '相切约束:点击第二个对象',
SketchConsType.pointOnEntity => picked == 0
? '点在线上:点击一个点(或先点目标线 / 圆)'
: '点在线上:再点击另一个目标(点 + 线 / 圆)',
};
/// 尺寸命令的分步提示。
String _dimHint(SketchDimType type, int picked) => switch (type) {
SketchDimType.length => '长度尺寸:点击一条直线',
SketchDimType.radius => '半径尺寸:点击圆或弧',
SketchDimType.angle =>
picked == 0 ? '角度尺寸:点击第一条直线' : '角度尺寸:点击第二条直线',
SketchDimType.distance =>
picked == 0 ? '距离尺寸:点击第一个点' : '距离尺寸:点击第二个点',
};
/// 变更草图文档(统一入口:撤销 / 脏标记 / 刷新)。
void changeSketch(
SketchDoc Function(SketchDoc doc) fn, {
String? status,
bool undo = true,
}) {
_changeArch(
arch.copyWith(sketch: fn(arch.sketch)),
status: status,
undo: undo,
);
}
/// 拖拽开始:压一次撤销快照(拖拽过程不再逐步入栈)。
void beginSketchUndo() {
_undo.add(_project);
if (_undo.length > 200) _undo.removeAt(0);
_redo.clear();
}
/// 拖拽中的实时求解(不入撤销栈)。
void dragSketch({
Map<String, Offset> points = const <String, Offset>{},
Map<String, double> radii = const <String, double>{},
}) {
if (points.isEmpty && radii.isEmpty) return;
final SketchSolveResult r = solveSketch(
arch.sketch,
dragPoints: points,
dragRadii: radii,
);
_project = _project.copyWith(arch: arch.copyWith(sketch: r.doc));
_dirty = true;
notifyListeners();
}
/// 全选草图对象(实体 + 尺寸)。
void selectAllSketch() {
selectSketchIds(<String>[
for (final SketchEntity e in arch.sketch.entities) e.id,
for (final SketchDim d in arch.sketch.dims) d.id,
]);
}
// ---- 识别后图形的尺寸编辑(不走约束求解器:直接缩放几何) ----
/// 修改图形尺寸(识别后图形 / 曲线 / 图元直接改值缩放)。
void setArchShapeDim(String id, ArchDimKind kind, double value) {
final ArchShape? s = arch.shapeById(id);
if (s == null || value <= 0) return;
updateArchShape(
archShapeApplyDim(s, kind, value),
status: '${s.text.isNotEmpty ? s.text : archShapeTypeLabel(s.type)}'
':${archDimKindLabel(kind)} → ${value.toStringAsFixed(1)} mm',
);
}
/// 切换画布尺寸标注(显示 / 隐藏;双击标签可改值)。
void toggleArchShapeDim(String id, ArchDimKind kind) {
final ArchShape? s = arch.shapeById(id);
if (s == null) return;
final Set<ArchDimKind> next = Set<ArchDimKind>.of(s.dims);
final bool removed = next.remove(kind);
if (!removed) next.add(kind);
updateArchShape(
s.copyWith(dims: next),
status: removed
? '已取消${archDimKindLabel(kind)}标注'
: '已标注${archDimKindLabel(kind)}(双击标签可改值)',
);
}
/// 删除选中的草图对象。
void deleteSketchSelection() {
if (_sketchSelIds.isEmpty) return;
final Set<String> ids = _sketchSelIds.toSet();
_sketchSelIds = const <String>[];
changeSketch((SketchDoc d) => d.removeAny(ids), status: '删除草图对象(${ids.length})');
}
/// 添加几何约束(引用从当前选择解析)并立即求解。
void addSketchConstraint(SketchConsType type) {
final SketchDoc d = arch.sketch;
if (!sketchCanConstrain(d, type, _sketchSelIds)) {
_status = '${sketchConsLabel(type)}:当前选择不满足(需选中 1–2 个对象)';
notifyListeners();
return;
}
final (String, String)? refs = sketchConsRefs(d, type, _sketchSelIds);
if (refs == null) return;
final SketchConstraint k = SketchConstraint(
id: sketchNewId('K', d.allIds),
type: type,
a: refs.$1,
b: refs.$2,
);
final SketchSolveResult r = solveSketch(
d.copyWith(constraints: <SketchConstraint>[...d.constraints, k]),
);
changeSketch(
(_) => r.doc,
status: '添加约束:${sketchConsLabel(type)}'
'${r.converged ? '' : '(冲突:未完全满足)'}',
);
}
/// 添加驱动尺寸(引用从当前选择解析)并立即求解。
void addSketchDim(SketchDimType type, double value) {
final SketchDoc d = arch.sketch;
if (!sketchCanDim(d, type, _sketchSelIds)) {
_status = '${sketchDimLabel(type)}尺寸:当前选择不满足';
notifyListeners();
return;
}
final (String, String)? refs = sketchDimRefs(d, type, _sketchSelIds);
if (refs == null) return;
final SketchDim nd = SketchDim(
id: sketchNewId('D', d.allIds),
type: type,
value: value,
a: refs.$1,
b: refs.$2,
);
final SketchSolveResult r = solveSketch(
d.copyWith(dims: <SketchDim>[...d.dims, nd]),
);
changeSketch(
(_) => r.doc,
status: '驱动尺寸:${sketchDimText(nd)}'
'${r.converged ? '' : '(冲突:未完全满足)'}',
);
}
/// 修改驱动尺寸数值(双击尺寸标签)并求解。
void setSketchDimValue(String id, double value) {
final SketchDim? d = arch.sketch.dimById(id);
if (d == null || value <= 0) return;
final SketchDoc next = arch.sketch.copyWith(
dims: <SketchDim>[
for (final SketchDim x in arch.sketch.dims)
x.id == id ? x.copyWith(value: value) : x,
],
);
final SketchSolveResult r = solveSketch(next);
changeSketch(
(_) => r.doc,
status: '驱动尺寸:${sketchDimText(d.copyWith(value: value))}'
'${r.converged ? '' : '(冲突:未完全满足)'}',
);
}
/// 架构图当前画笔颜色。
int get archColor => _archColor;
/// 设置架构图画笔颜色;若当前选中了图形,同时替换它们的颜色。
void setArchColor(int color) {
_archColor = color;
final Set<String> sel = _archSelIds.toSet();
final List<ArchShape> selShapes = <ArchShape>[
for (final ArchShape s in arch.shapes)
if (sel.contains(s.id)) s,
];
if (selShapes.isNotEmpty) {
ArchDoc next = arch;
for (final ArchShape s in selShapes) {
next = next.replaceShape(s.copyWith(
stroke: color,
fill: s.type == ArchShapeType.text ? 0 : archFillOf(color),
));
}
_changeArch(next, status: '已更新颜色');
return;
}
notifyListeners();
}
/// 架构图连线默认走线方式。
ArchRoute get archRoute => _archRoute;
/// 正交模式(F8)。
bool get archOrtho => _archOrtho;
/// 切换正交模式(移动约束到水平 / 垂直)。
void setArchOrtho(bool v) {
if (_archOrtho == v) return;
_archOrtho = v;
_status = v ? '正交:开(移动约束水平 / 垂直)' : '正交:关';
notifyListeners();
}
/// 极轴追踪(F10)。
bool get archPolar => _archPolar;
/// 切换极轴追踪。
void setArchPolar(bool v) {
if (_archPolar == v) return;
_archPolar = v;
_status = v ? '极轴:开(${_archPolarDeg.round()}° 倍数吸附)' : '极轴:关';
notifyListeners();
}
/// 极轴角度(度)。
double get archPolarDeg => _archPolarDeg;
/// 设置极轴角度(5–90°,常用 5 / 10 / 15 / 22.5 / 30 / 45 / 90)。
void setArchPolarDeg(double deg) {
final double v = deg.clamp(1, 90).toDouble();
if (v == _archPolarDeg) return;
_archPolarDeg = v;
_status = '极轴角度:${v == v.roundToDouble() ? v.round() : v}°';
notifyListeners();
}
/// 四边标尺显示开关。
bool get archRulers => _archRulers;
/// 切换四边标尺。
void setArchRulers(bool v) {
if (_archRulers == v) return;
_archRulers = v;
_status = v ? '标尺:显示' : '标尺:隐藏';
notifyListeners();
}
/// 设置连线默认走线方式(直线 / 正交折线)。
void setArchRoute(ArchRoute r) {
if (_archRoute == r) return;
_archRoute = r;
_status = r == ArchRoute.ortho ? '连线走线:正交折线' : '连线走线:直线';
notifyListeners();
}
/// 架构图当前选中元素 id 列表。
List<String> get archSelIds => _archSelIds;
/// 主选中元素 id(列表首项);空表示无选中。
String? get archSelId => _archSelIds.isEmpty ? null : _archSelIds.first;
/// 选中架构图元素(null 清空;[toggle] 为切换式多选)。
void selectArch(String? id, {bool toggle = false}) {
final List<String> cur = List<String>.of(_archSelIds);
if (id == null) {
cur.clear();
} else if (toggle) {
if (cur.contains(id)) {
cur.remove(id);
} else {
cur.add(id);
}
} else {
cur
..clear()
..add(id);
}
if (_sameIds(cur, _archSelIds)) return;
_archSelIds = cur;
notifyListeners();
}
/// 替换整个选中集合(框选 / 全选用)。
void selectArchIds(List<String> ids) {
if (_sameIds(ids, _archSelIds)) return;
_archSelIds = List<String>.of(ids);
notifyListeners();
}
/// 全选当前文档的所有元素。
void selectAllArch() {
selectArchIds(<String>[
for (final ArchShape s in arch.shapes) s.id,
for (final ArchConnector c in arch.connectors) c.id,
for (final ArchStroke s in arch.strokes) s.id,
]);
}
/// 判断两个 id 列表是否相同。
static bool _sameIds(List<String> a, List<String> b) {
if (identical(a, b)) return true;
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
/// 「识别演示」触发令牌(画布监听它启动动画)。
int get archPlayToken => _archPlayToken;
/// 架构图文档。
ArchDoc get arch => _project.arch;
/// 架构图画布视口尺寸(测量值,不触发通知)。
Size get archViewport => _archViewport;
/// 由架构图画布回填视口尺寸(不通知监听者)。
void setArchViewport(Size s) {
_archViewport = s;
}
/// 修改架构图文档的公共入口。
///
/// [undo] 为 true 时记录撤销历史(单次编辑);批量演示动画传 false,
/// 由外层「载入示例」记录一次整体历史(一次 Ctrl+Z 即可整体还原)。
void _changeArch(ArchDoc next, {String? status, bool undo = true}) {
if (undo) {
_mutate(_project.copyWith(arch: next), status: status);
return;
}
_project = _project.copyWith(arch: next);
_dirty = true;
if (status != null) _status = status;
notifyListeners();
}
/// 新增 / 覆盖一个架构图图形(未指定图层时归入当前活动图层)。
void addArchShape(ArchShape s, {bool undo = true}) {
final ArchShape item =
s.layerId.isEmpty ? s.copyWith(layerId: arch.activeLayer) : s;
_changeArch(
arch.replaceShape(item),
status: '新增${archShapeTypeLabel(item.type)}',
undo: undo,
);
}
/// 新增一段手绘墨迹(未指定图层时归入当前活动图层)。
void addArchStroke(ArchStroke s, {bool undo = true}) {
final ArchStroke item =
s.layerId.isEmpty ? s.copyWith(layerId: arch.activeLayer) : s;
_changeArch(
arch.copyWith(strokes: <ArchStroke>[...arch.strokes, item]),
status: '手绘墨迹(未识别)',
undo: undo,
);
}
/// 移除一段墨迹(识别演示转化完成后调用)。
void removeArchStroke(String id, {bool undo = false}) {
_changeArch(arch.removeIds(<String>{id}), undo: undo);
}
/// 新增一条连线(未指定图层时归入当前活动图层)。
void addArchConnector(ArchConnector c, {bool undo = true}) {
final ArchConnector item =
c.layerId.isEmpty ? c.copyWith(layerId: arch.activeLayer) : c;
_changeArch(
arch.copyWith(connectors: <ArchConnector>[...arch.connectors, item]),
status: '新增连线',
undo: undo,
);
}
/// 更新图形(移动 / 缩放 / 文字 / 颜色)。
void updateArchShape(ArchShape s, {String? status, bool undo = true}) {
_changeArch(arch.replaceShape(s), status: status ?? '更新图形', undo: undo);
}
/// 提交一次「墨迹 → 标准图形」转化(动画完成时调用)。
///
/// [removeIds] 用于两笔合并 / 圆柱拼接等场景:完成时把被合并的旧元素
/// 一并移除,且与新增图形合并为同一条撤销记录。
void commitArchConversion(
ArchShape shape, {
Set<String> removeIds = const <String>{},
bool undo = true,
}) {
final ArchShape item =
shape.layerId.isEmpty ? shape.copyWith(layerId: arch.activeLayer) : shape;
ArchDoc next = arch.replaceShape(item);
if (removeIds.isNotEmpty) {
next = next.removeIds(removeIds);
}
_changeArch(
next,
status: '识别为${archShapeTypeLabel(item.type)}',
undo: undo,
);
}
/// 删除当前选中的架构图元素(删除图形会连带删除其连线;支持多选)。
void removeArchSelection() {
if (_archSelIds.isEmpty) return;
final Set<String> ids = _archSelIds.toSet();
_archSelIds = const <String>[];
_changeArch(arch.removeIds(ids), status: '已删除 ${ids.length} 个对象');
}
/// 批量移动图形(多选拖拽;只记录一次撤销历史)。
void moveArchShapes(Map<String, Offset> deltas) {
if (deltas.isEmpty) return;
final List<ArchShape> shapes = <ArchShape>[
for (final ArchShape s in arch.shapes)
deltas.containsKey(s.id) ? s.translated(deltas[s.id]!) : s,
];
_changeArch(arch.copyWith(shapes: shapes), status: '移动');
}
/// 以函数式方式变换架构图文档(多步编辑合并为一次撤销记录)。
void transformArch(
ArchDoc Function(ArchDoc) fn, {
String? status,
bool undo = true,
}) {
_changeArch(fn(arch), status: status, undo: undo);
}
/// 更新一条连线(走线方式 / 颜色 / 标签)。
void updateArchConnector(ArchConnector c, {String? status}) {
final List<ArchConnector> next = <ArchConnector>[
for (final ArchConnector x in arch.connectors) x.id == c.id ? c : x,
];
_changeArch(arch.copyWith(connectors: next), status: status ?? '更新连线');
}
/// 设置网格(吸附开关 / 粒度;文档设置,不记录撤销)。
void setArchGrid({bool? snap, double? size}) {
final ArchDoc a = arch;
final bool s = snap ?? a.gridSnap;
final double g = (size ?? a.gridSize).clamp(4, 200).toDouble();
if (s == a.gridSnap && g == a.gridSize) return;
_changeArch(
a.copyWith(gridSnap: s, gridSize: g),
status: s ? '网格吸附:开(${g.round()} px)' : '网格吸附:关',
undo: false,
);
}
// ===================== 架构图图层(AutoCAD 风格) =====================
/// 设置当前活动图层(新建图形 / 墨迹 / 连线的归属;同时切换画笔色为该图层色)。
void setArchActiveLayer(String id) {
final ArchLayer l = arch.layerById(id);
if (arch.activeLayer == l.id) return;
_archColor = l.color;
_changeArch(
arch.copyWith(activeLayerId: l.id),
status: '活动图层:${l.name}',
undo: false,
);
}
/// 新建图层并设为活动图层。
void addArchLayer() {
int n = arch.layers.length + 1;
String id = 'LY$n';
final Set<String> used = arch.layers.map((ArchLayer l) => l.id).toSet();
while (used.contains(id)) {
n++;
id = 'LY$n';
}
final int color = kArchPalette[arch.layers.length % kArchPalette.length];
final ArchLayer l = ArchLayer(id: id, name: '图层 $n', color: color);
_archColor = color;
_changeArch(
arch.copyWith(
layers: <ArchLayer>[...arch.layers, l],
activeLayerId: id,
),
status: '新建图层「${l.name}」',
);
}
/// 更新图层(名称 / 颜色 / 可见 / 锁定)。
void updateArchLayer(ArchLayer l, {String? status}) {
final List<ArchLayer> next = <ArchLayer>[
for (final ArchLayer x in arch.layers) x.id == l.id ? l : x,
];
_changeArch(arch.copyWith(layers: next), status: status ?? '图层已更新');
}
/// 切换图层可见性(隐藏的图层不绘制、不可选、不可吸附)。
void toggleArchLayerVisible(String id) {
final ArchLayer l = arch.layerById(id);
updateArchLayer(l.copyWith(visible: !l.visible),
status: l.visible ? '图层「${l.name}」已隐藏' : '图层「${l.name}」已显示');
}
/// 切换图层锁定(锁定后可见但不可选 / 不可移动)。
void toggleArchLayerLocked(String id) {
final ArchLayer l = arch.layerById(id);
updateArchLayer(l.copyWith(locked: !l.locked),
status: l.locked ? '图层「${l.name}」已解锁' : '图层「${l.name}」已锁定');
}
// ===================== 对齐 / 均布(PPT 风格) =====================
/// 对齐 / 均布选中的图形(以选中范围为参照;均布至少 3 个)。
void alignArchSelection(ArchAlign mode) {
final List<ArchShape> sel = <ArchShape>[
for (final String id in _archSelIds)
if (arch.shapeById(id) != null) arch.shapeById(id)!,
];
final bool distribute =
mode == ArchAlign.distributeH || mode == ArchAlign.distributeV;
if (sel.length < (distribute ? 3 : 2)) {
setStatus(distribute ? '均布至少需要选中 3 个图形' : '对齐至少需要选中 2 个图形');
return;
}
// 参照范围 = 选中图形并集(线性图形按 bounds 参与)。
Rect u = sel.first.bounds;
for (final ArchShape s in sel) {
u = u.expandToInclude(s.bounds);
}
ArchShape applyTo(ArchShape s, Rect target) {
if (s.isLinear) {
return s.translated(target.topLeft - s.bounds.topLeft);
}
return s.copyWith(rect: target);
}
final Map<String, ArchShape> next = <String, ArchShape>{};
if (!distribute) {
for (final ArchShape s in sel) {
final Rect b = s.bounds;
final Rect r = switch (mode) {
ArchAlign.left =>
Rect.fromLTWH(u.left, b.top, b.width, b.height),
ArchAlign.hCenter => Rect.fromLTWH(
u.center.dx - b.width / 2, b.top, b.width, b.height),
ArchAlign.right =>
Rect.fromLTWH(u.right - b.width, b.top, b.width, b.height),
ArchAlign.top =>
Rect.fromLTWH(b.left, u.top, b.width, b.height),
ArchAlign.vCenter => Rect.fromLTWH(
b.left, u.center.dy - b.height / 2, b.width, b.height),
ArchAlign.bottom =>
Rect.fromLTWH(b.left, u.bottom - b.height, b.width, b.height),
_ => b,
};
next[s.id] = applyTo(s, r);
}
} else {
final bool horiz = mode == ArchAlign.distributeH;
final List<ArchShape> sorted = List<ArchShape>.of(sel)
..sort((ArchShape a, ArchShape b) => horiz
? a.bounds.center.dx.compareTo(b.bounds.center.dx)
: a.bounds.center.dy.compareTo(b.bounds.center.dy));
final double firstC = horiz
? sorted.first.bounds.center.dx
: sorted.first.bounds.center.dy;
final double lastC = horiz
? sorted.last.bounds.center.dx
: sorted.last.bounds.center.dy;
final double stepC = (lastC - firstC) / (sorted.length - 1);
for (int i = 0; i < sorted.length; i++) {
final ArchShape s = sorted[i];
final double c = firstC + stepC * i;
final Rect b = s.bounds;
final Rect r = horiz
? Rect.fromLTWH(c - b.width / 2, b.top, b.width, b.height)
: Rect.fromLTWH(b.left, c - b.height / 2, b.width, b.height);
next[s.id] = applyTo(s, r);
}
}
final String label = switch (mode) {
ArchAlign.left => '左对齐',
ArchAlign.hCenter => '横向居中',
ArchAlign.right => '右对齐',
ArchAlign.top => '顶对齐',
ArchAlign.vCenter => '纵向居中',
ArchAlign.bottom => '底对齐',
ArchAlign.distributeH => '横向均布',
ArchAlign.distributeV => '纵向均布',
};
_changeArch(
arch.copyWith(shapes: <ArchShape>[
for (final ArchShape s in arch.shapes) next[s.id] ?? s,
]),
status: '$label(${sel.length} 个图形)',
);
}
/// 删除图层(该图层对象移入第一个图层;仅剩一个图层时不允许删除)。
void removeArchLayer(String id) { if (arch.layers.length <= 1) {
setStatus('至少保留一个图层,无法删除');
return;
}
final List<ArchLayer> next =
arch.layers.where((ArchLayer l) => l.id != id).toList();
final String fallback = next.first.id;
final List<ArchShape> shapes = <ArchShape>[
for (final ArchShape s in arch.shapes)
s.layerId == id ? s.copyWith(layerId: fallback) : s,
];
final List<ArchStroke> strokes = <ArchStroke>[
for (final ArchStroke s in arch.strokes)
s.layerId == id ? s.copyWith(layerId: fallback) : s,
];
final List<ArchConnector> conns = <ArchConnector>[
for (final ArchConnector c in arch.connectors)
c.layerId == id ? c.copyWith(layerId: fallback) : c,
];
_changeArch(
arch.copyWith(
layers: next,
shapes: shapes,
strokes: strokes,
connectors: conns,
activeLayerId: arch.activeLayer == id ? fallback : arch.activeLayerId,
),
status: '已删除图层(对象移入首个图层)',
);
}
/// 调整图形层级([delta] > 0 上移一层)。
void moveArchZ(ArchShape s, int delta) {
final List<ArchShape> list = List<ArchShape>.of(arch.shapes);
final int i = list.indexWhere((ArchShape x) => x.id == s.id);
if (i < 0) return;
final int j = (i + delta).clamp(0, list.length - 1);
if (i == j) return;
final ArchShape x = list.removeAt(i);
list.insert(j, x);
_changeArch(arch.copyWith(shapes: list), status: '调整层级');
}
/// 载入示例场景(手绘稿 / 完成图),并适配视图。
void archLoadDemo(ArchDemoKind kind) {
final bool ink = kind == ArchDemoKind.ink;
_archSelIds = const <String>[];
_changeArch(
ink ? archDemoInkScene() : archDemoDoneScene(),
status: ink ? '已载入示例:手绘稿(点「识别演示」逐笔识别)' : '已载入示例:完成图',
);
archFit();
}
/// 载入手绘稿并触发「识别演示」(逐笔播放转化动画)。
void archPlayDemo() {
_archSelIds = const <String>[];
_archPlayToken++;
_changeArch(archDemoInkScene(), status: '识别演示:逐笔识别中…');
archFit();
}
/// 清空架构图。
void archClear() {
_archSelIds = const <String>[];
_changeArch(ArchDoc.empty, status: '已清空架构图');
_archSetViewDirect(zoom: 1, panX: 0, panY: 0);
}
/// 写入架构图视口(视图操作:不置脏、不记录历史)。
void archSetView({double? zoom, double? panX, double? panY}) {
_archSetViewDirect(zoom: zoom, panX: panX, panY: panY);
}
/// 视口写入实现。
void _archSetViewDirect({double? zoom, double? panX, double? panY}) {
final ArchDoc a = _project.arch;
_project = _project.copyWith(
arch: a.copyWith(
zoom: (zoom ?? a.zoom).clamp(0.15, 4.0).toDouble(),
panX: panX ?? a.panX,
panY: panY ?? a.panY,
),
);
notifyListeners();
}
/// 以 [focal](屏幕坐标)为锚点缩放架构图。
void archZoomAt(double factor, Offset focal) {
final ArchDoc a = _project.arch;
final double nz = (a.zoom * factor).clamp(0.15, 4.0).toDouble();
if ((nz - a.zoom).abs() < 0.0001) return;
final double k = nz / a.zoom;
_archSetViewDirect(
zoom: nz,
panX: focal.dx - (focal.dx - a.panX) * k,
panY: focal.dy - (focal.dy - a.panY) * k,
);
}
/// 缩放架构图(工具栏 ± 按钮,以视口中心为锚点)。
void archZoomBy(double factor) {
final Size vp = _archViewport;
final Offset focal =
vp.isEmpty ? const Offset(400, 300) : Offset(vp.width / 2, vp.height / 2);
archZoomAt(factor, focal);
}
/// 架构图「适应窗口」:按内容范围适配缩放并居中。
void archFit() {
final Size vp = _archViewport;
final Rect b = _project.arch.contentBounds();
final double bw = math.max(b.width, 80);
final double bh = math.max(b.height, 80);
if (vp.width <= 10 || vp.height <= 10) {
_archSetViewDirect(zoom: 1, panX: 0, panY: 0);
return;
}
final double z = math
.min(vp.width / (bw + 80), vp.height / (bh + 80))
.clamp(0.15, 2.5)
.toDouble();
_archSetViewDirect(
zoom: z,
panX: vp.width / 2 - b.center.dx * z,
panY: vp.height / 2 - b.center.dy * z,
);
}
2026-09-18 16:50:12 +08:00
/// 新建项目:清空历史,构造一个含两个工位、两个动作(动作 1 / 动作 2)的初始项目。
///
/// 副作用:重置文件路径、置脏、更新状态并重算关键路径。
void newProject() {
_undo.clear();
_redo.clear();
_project = Project(
name: '未命名设计',
2026-09-18 16:50:12 +08:00
cycle: const Cycle(durationMs: 2400),
stations: const <Station>[
Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0),
Station(id: 'ST2', name: '工位 2', order: 1, color: 0xFFFFD166),
],
actions: <Action>[
Action(id: 'A1', name: '动作 1', stationId: 'ST1', driver: '气缸 Y1', startAngle: 0, durationAngle: 70, layer: 0, row: 0, color: kActionPalette[0]),
Action(
id: 'A2',
name: '动作 2',
stationId: 'ST2',
driver: '气缸 Y2',
startAngle: 80,
durationAngle: 60,
layer: 1,
row: 1,
color: kActionPalette[1],
deps: const <Dependency>[Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)],
),
],
units: _project.units,
viewState: ViewState(mode: _project.viewState.mode, selectedIds: const <String>['A1']),
);
_filePath = null;
_dirty = true;
_status = '新建项目';
_project = _syncLaneFloor(_project);
2026-09-18 16:50:12 +08:00
_recomputeCritical();
notifyListeners();
}
/// 载入一个项目(打开文件或恢复自动保存时使用)。
///
/// 参数 [p]:项目数据;[path]:来源文件路径;[dirty]:载入后是否标记为脏
/// (如自动恢复场景)。副作用:清空撤销/重做栈、重算关键路径并刷新。
void loadProject(Project p, {String? path, bool dirty = false}) {
_undo.clear();
_redo.clear();
_project = _syncLaneFloor(p);
2026-09-18 16:50:12 +08:00
_filePath = path;
_dirty = dirty;
_status = path == null ? '已载入' : '已打开 ${_baseName(path)}';
_recomputeCritical();
notifyListeners();
}
/// 另存为:将当前项目写入 [path] 并更新文件路径、脏标记与保存时间。
Future<void> saveAs(String path) async {
await Storage.instance.saveProject(path, _project);
_filePath = path;
_dirty = false;
_lastSavedAt = DateTime.now();
_status = '已保存 ${_baseName(path)}';
notifyListeners();
}
/// 保存到当前路径;无路径时返回 false(需要调用方改用 [saveAs])。
Future<bool> save() async {
if (_filePath == null) return false;
await saveAs(_filePath!);
return true;
}
/// 通过外部通道(如安卓公共 Documents)保存成功后标记为已保存。
///
/// [displayPath] 仅用于展示与状态栏;自动保存快照标记为干净,
/// 不写 .bak 备份(外部存储不经过 dart:io)。
Future<void> markSaved(String displayPath) async {
_filePath = displayPath;
_dirty = false;
_lastSavedAt = DateTime.now();
_status = '已保存 ${_baseName(displayPath)}';
await Storage.instance.writeAutosave(_project, projectPath: null, clean: true);
notifyListeners();
}
2026-09-18 16:50:12 +08:00
/// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。
static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last;
/// 保存架构图文档到 [path](`*.arch.json`;桌面同步 `.bak` 备份)。
Future<void> saveArchAs(String path) async {
final String json = _project.arch.encode();
await Storage.instance.backupExisting(path);
final File target = File(path);
if (!await target.parent.exists()) {
await target.parent.create(recursive: true);
}
await target.writeAsString(json, flush: true);
_archFilePath = path;
_dirty = false;
_lastSavedAt = DateTime.now();
_status = '已保存 ${_baseName(path)}(含 .bak 备份)';
await Storage.instance.writeAutosave(_project, projectPath: _archFilePath, clean: true);
notifyListeners();
}
/// 通过外部通道(安卓公共 Documents)保存架构图成功后标记为已保存。
Future<void> markArchSaved(String displayPath) async {
_archFilePath = displayPath;
_dirty = false;
_lastSavedAt = DateTime.now();
_status = '已保存 ${_baseName(displayPath)}';
await Storage.instance.writeAutosave(_project, projectPath: null, clean: true);
notifyListeners();
}
/// 载入架构图文档(`*.arch.json`):只替换架构图部分,时序图保持不变。
void loadArchDoc(ArchDoc doc, {String? path, bool dirty = false}) {
_undo.clear();
_redo.clear();
_archSelIds = const <String>[];
_project = _project.copyWith(arch: doc);
_archFilePath = path;
_dirty = dirty;
_status = path == null ? '已载入架构图' : '已打开 ${_baseName(path)}';
notifyListeners();
}
/// 新建架构图文档(空画布 + 默认图层)。
void newArchProject() {
_undo.clear();
_redo.clear();
_archSelIds = const <String>[];
_project = _project.copyWith(arch: ArchDoc.empty);
_archFilePath = null;
_dirty = true;
_status = '新建架构图';
// 默认图纸 A0(1189×841 mm):按视口适配缩放并居中;视口未知时用稳妥默认值。
final Size vp = _archViewport;
if (vp.width > 10 && vp.height > 10) {
final double z = math
.min((vp.width - 90) / kArchPageSize.width,
(vp.height - 90) / kArchPageSize.height)
.clamp(0.15, 4.0)
.toDouble();
_archSetViewDirect(
zoom: z,
panX: (vp.width - kArchPageSize.width * z) / 2,
panY: (vp.height - kArchPageSize.height * z) / 2,
);
} else {
_archSetViewDirect(zoom: 0.62, panX: 40, panY: 40);
}
}
/// 切换视图模式(条形 / 圆周 / 流程图)并更新状态栏文本。
///
/// 三种视图共用同一套缩放 / 平移状态,切换后自动适配一次视图
/// (各视图坐标系与内容范围不同,避免出现「看不到内容」)。
2026-09-18 16:50:12 +08:00
void setViewMode(ViewMode mode) {
_project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode));
_status = switch (mode) {
ViewMode.bar => '条形节拍视图',
ViewMode.circular => '圆周节拍视图',
ViewMode.flow => '流程图视图(只读)',
};
2026-09-18 16:50:12 +08:00
notifyListeners();
// 每次切换视图都自动执行一次「适应窗口」:三个视图的内容范围不同,
// 不重置就会沿用上一个视图的缩放 / 平移,画面看起来就「跑了」。
fitView(silent: true);
// 再补一帧:画布可能因侧栏开合 / 窗口尺寸在同一批布局中变化,
// 等该帧结束后按最新视口再适配一次,确保切换后必定处于适配状态。
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_disposed || _project.viewState.mode != mode) return;
fitView(silent: true);
});
2026-09-18 16:50:12 +08:00
}
/// 选中指定动作([id] 为 null 表示清空选中)并刷新。
///
/// [toggle] 为 true 时(Ctrl/Shift 点击)在选中集合中切换该动作,
/// 从而实现多选;否则替换为单选。选中仅改变视图状态,不影响脏标记。
void select(String? id, {bool toggle = false}) {
final List<String> cur = List<String>.of(_project.viewState.selectedIds);
if (id == null) {
cur.clear();
} else if (toggle) {
if (cur.contains(id)) {
cur.remove(id);
} else {
cur.add(id);
}
} else {
cur
..clear()
..add(id);
}
_project = _project.copyWith(viewState: _project.viewState.copyWith(selectedIds: cur));
notifyListeners();
}
/// 直接设置缩放系数,自动钳制到 `[0.25, 4.0]`。
void setZoom(double z) {
final double v = z.clamp(0.25, 4.0);
_project = _project.copyWith(viewState: _project.viewState.copyWith(zoom: v));
notifyListeners();
}
/// 以视口坐标 [focal] 为锚点缩放,保证锚点下的内容不漂移。
///
/// 屏幕坐标与逻辑坐标关系为 `screen = logical × zoom + pan`;
/// 令锚点处的逻辑点保持不变,可解得新的平移量:
/// `pan' = focal − (focal − pan) × (zoom' / zoom)`。
void zoomAt(double factor, Offset focal) {
final ViewState v = _project.viewState;
final double nz = (v.zoom * factor).clamp(0.25, 4.0);
if ((nz - v.zoom).abs() < 0.0001) return;
final double k = nz / v.zoom;
final double px = focal.dx - (focal.dx - v.panX) * k;
final double py = focal.dy - (focal.dy - v.panY) * k;
_project = _project.copyWith(
viewState: v.copyWith(zoom: nz, panX: px, panY: py),
);
notifyListeners();
}
/// 以视口中心为锚点缩放(工具栏 ± 按钮使用)。
void zoomBy(double factor) {
final Size vp = _viewport;
final Offset focal = vp.isEmpty ? Offset.zero : Offset(vp.width / 2, vp.height / 2);
zoomAt(factor, focal);
}
/// 直接设置缩放与平移(双指捏合手势使用);缩放钳制到 [0.25, 4.0]。
///
/// 调用方按「捏合焦点锚定」自行计算 pan(见 CanvasView._onScaleUpdate),
/// 本方法只负责写入视图状态并通知。
void setViewTransform({double? zoom, double? panX, double? panY}) {
final ViewState v = _project.viewState;
_project = _project.copyWith(
viewState: v.copyWith(
zoom: (zoom ?? v.zoom).clamp(0.25, 4.0),
panX: panX ?? v.panX,
panY: panY ?? v.panY,
),
);
notifyListeners();
}
2026-09-18 16:50:12 +08:00
/// 按偏移量 [d] 平移视图。
void panBy(Offset d) {
_project = _project.copyWith(
viewState: _project.viewState.copyWith(
panX: _project.viewState.panX + d.dx,
panY: _project.viewState.panY + d.dy,
),
);
notifyListeners();
}
/// 复位视图:缩放归 1、平移归零(回到布局默认的居中状态)。
void resetView() {
_project = _project.copyWith(viewState: _project.viewState.copyWith(zoom: 1, panX: 0, panY: 0));
_status = '复位视图';
notifyListeners();
}
/// 设置「保留空泳道」策略:动作全部移走后,泳道保留(序号不变)还是自动移除。
///
/// 切换为开启时以当前使用中的泳道为保底,避免把历史收缩掉的泳道“补”出来。
void setKeepEmptyLanes(bool value) {
if (_project.keepEmptyLanes == value) return;
_project = _syncLaneFloor(_project.copyWith(keepEmptyLanes: value));
_dirty = true;
_status = value ? '已开启:保留空泳道' : '已关闭:空泳道自动移除';
notifyListeners();
}
2026-09-18 16:50:12 +08:00
/// 切换依赖连线的显示/隐藏。
void toggleDeps() {
_project = _project.copyWith(
viewState: _project.viewState.copyWith(showDeps: !_project.viewState.showDeps),
);
notifyListeners();
}
/// 批量设置视图显示开关;传入 null 的项保持原值。
void setViewFlag({
bool? showDeps,
bool? showRuler,
bool? showPhaseBands,
bool? showRingBg,
bool? showLayerLabels,
}) {
_project = _project.copyWith(
viewState: _project.viewState.copyWith(
showDeps: showDeps,
showRuler: showRuler,
showPhaseBands: showPhaseBands,
showRingBg: showRingBg,
showLayerLabels: showLayerLabels,
),
);
notifyListeners();
}
/// 适应窗口:按当前视图内容计算缩放与平移,使其完整可见。
///
/// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放,
/// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。
/// - 条形视图:布局本身按视口高度自适应,动作较多触发缩小时内容居中。
/// - 流程图:按节点内容范围适配并居中。
///
/// [silent] 为真时不改写状态栏文案(供视图切换时自动调用)。
void fitView({bool silent = false}) {
2026-09-18 16:50:12 +08:00
final Size vp = _viewport;
if (vp.width <= 0 || vp.height <= 0) {
resetView();
return;
}
double z = 1;
double px = 0;
double py = 0;
if (_project.viewState.mode == ViewMode.flow) {
// 流程图:按内容范围等比适配并居中;顶部只需为单行标题浮层留白。
final FlowLayout l = FlowLayout(
_project,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
);
final Rect b = l.nodes.isEmpty ? const Rect.fromLTWH(0, 0, 420, 300) : l.bounds;
const double topPad = 72;
const double bottomPad = 28;
final double availW = vp.width - 96;
final double availH = vp.height - topPad - bottomPad;
z = math.min(availW / b.width, availH / b.height).clamp(0.25, 1.5);
px = vp.width / 2 - b.center.dx * z;
py = topPad + availH / 2 - b.center.dy * z;
} else if (_project.viewState.mode == ViewMode.circular) {
2026-09-18 16:50:12 +08:00
final CircularLayout l = CircularLayout(_project, vp);
// 半径需覆盖:刻度文字(tickR + ~50)、顺时针箭头(rMax + ~70)、
// 12 点钟起点标记(tickR + ~70),再留 20px 余量,避免任何标注被裁掉。
final double contentR = math.max(l.tickR + 130, l.rMax + 120);
2026-09-18 16:50:12 +08:00
// 顶部为标题浮层预留约 60px,底部留 60px。
final double availW = vp.width - 40;
final double availH = vp.height - 120;
z = (math.min(availW, availH) / (contentR * 2)).clamp(0.25, 4.0);
final Offset center = l.center;
px = vp.width / 2 - center.dx * z;
py = vp.height / 2 - center.dy * z;
} else {
final BarLayout l = BarLayout(_project, vp);
// 内容逻辑范围:(0,0) → 右缘 + 60、最后一行底部 + 40。
2026-09-18 16:50:12 +08:00
final double contentW = l.plotRight + 60;
final double contentH = l.plotBottom + 40;
2026-09-18 16:50:12 +08:00
z = math.min(vp.width / contentW, vp.height / contentH).clamp(0.25, 1.0);
// 关键修复:内容被缩小时按内容范围居中显示;内容本来就能放下时保持默认位置。
// (此前固定 pan = 0,缩小的画面会被钉在左上角。)
px = z < 1 ? (vp.width - contentW * z) / 2 : 0;
py = z < 1 ? (vp.height - contentH * z) / 2 : 0;
2026-09-18 16:50:12 +08:00
}
_project = _project.copyWith(
viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py),
);
if (!silent) _status = '适应窗口';
2026-09-18 16:50:12 +08:00
notifyListeners();
}
/// 替换工位列表(名称 / 颜色 / 顺序 / 数量均可改)。
///
/// 若某个动作引用的工位被移除,则自动改挂到列表中的第一个工位,
/// 保证「动作 → 工位」引用始终有效。空列表会被忽略(至少保留一个工位)。
void setStations(List<Station> stations, {String? status}) {
if (stations.isEmpty) {
setStatus('至少保留一个工位,无法删除');
return;
}
final Set<String> ids = stations.map((Station s) => s.id).toSet();
final String fallback = stations.first.id;
final List<Action> actions = _project.actions
.map((Action a) => ids.contains(a.stationId) ? a : a.copyWith(stationId: fallback))
.toList();
_mutate(
_project.copyWith(stations: stations, actions: actions),
status: status ?? '工位已更新',
);
}
2026-09-18 16:50:12 +08:00
/// 替换相位分区列表(名称 / 起止角 / 数量均可改,允许区间重叠)。
void setPhaseZones(List<PhaseZone> zones, {String? status}) {
_project = _project.copyWith(phaseZones: zones);
_dirty = true;
_status = status ?? '相位分区已更新';
notifyListeners();
}
/// 更新项目名称并标记为脏。
void setProjectName(String name) {
_project = _project.copyWith(name: name);
_dirty = true;
_status = '项目名称已更新';
notifyListeners();
}
/// 替换单位设置并标记为脏;[status] 可自定义状态栏文本。
void setUnits(UnitSettings u, {String? status}) {
_project = _project.copyWith(units: u);
_dirty = true;
_status = status ?? '单位设置已更新';
notifyListeners();
}
/// 修改循环时长(毫秒)。
///
/// 参数 [keepAngle]:为 true 时保持各动作角度不变;为 false 时按
/// `旧时长 / 新时长` 缩放所有动作的起始角与持续角,从而保持其时间不变。
/// 副作用:通过 [_mutate] 记录历史并重算关键路径。
void setCycleDuration(double ms, {bool keepAngle = true}) {
// 计算角度缩放比例:keepAngle 时保持 1;否则按旧/新时长比例缩放。
double angleScale = 1;
if (!keepAngle && _project.cycle.durationMs > 0) {
angleScale = _project.cycle.durationMs / ms;
}
List<Action> actions = _project.actions;
if (angleScale != 1) {
actions = actions
.map((Action a) => a.copyWith(
startAngle: a.startAngle * angleScale,
durationAngle: a.durationAngle * angleScale,
))
.toList();
}
_mutate(_project.copyWith(cycle: _project.cycle.copyWith(durationMs: ms), actions: actions),
status: '循环时长 ${ms.toStringAsFixed(0)} ms');
}
/// 新增一个动作,并将其置于最外层。
///
/// 参数 [startAngle]:可选起始角(钳制到 `[0, 359]`,默认 0);
/// [stationId]:可选归属工位(默认第一个工位)。
/// 副作用:生成不冲突的 id、选中新动作、记录历史并重算关键路径。
void addAction({double? startAngle, String? stationId}) {
// 生成唯一 id:从 A{n} 起,若冲突则递增 guard 直到不重复。
final int n = _project.actions.length + 1;
String id = 'A$n';
int guard = n;
while (_project.actionById(id) != null) {
guard++;
id = 'A$guard';
}
final int layer = _project.maxLayer + 1;
final double start = (startAngle ?? 0).clamp(0, 359);
final Action a = Action(
id: id,
name: '动作 $n',
stationId: stationId ?? (_project.stations.isNotEmpty ? _project.stations.first.id : 'ST1'),
driver: '',
startAngle: start,
durationAngle: 45,
layer: layer,
color: kActionPalette[(_project.actions.length) % kActionPalette.length],
row: 0, // 新动作进入全新泳道(1 槽)的槽位 0
2026-09-18 16:50:12 +08:00
);
_mutate(
_project.copyWith(
actions: <Action>[..._project.actions, a],
viewState: _project.viewState.copyWith(selectedIds: <String>[a.id]),
),
status: '新增 $id(最外层 L${layer + 1})',
);
}
/// 删除指定动作,并清理其它动作中指向/来自它的依赖。
///
/// 若 [id] 不存在则直接返回(不产生历史记录)。副作用:若被删动作处于选中
/// 状态则清除选中,记录历史并重算关键路径。
void deleteAction(String id) {
// 至少保留一个动作 / 泳道:最后一个动作不可删除。
if (_project.actions.length <= 1) {
setStatus('至少保留一个动作 / 泳道,无法删除');
return;
}
2026-09-18 16:50:12 +08:00
// 过滤掉目标动作,并从其余动作的依赖中移除与目标相关的边。
final List<Action> actions = _project.actions
.where((Action a) => a.id != id)
.map((Action a) => a.copyWith(
deps: a.deps.where((Dependency d) => d.fromId != id && d.toId != id).toList(),
))
.toList();
if (actions.length == _project.actions.length) return;
_mutate(
_project.copyWith(
actions: actions,
viewState: _project.viewState.copyWith(
selectedIds: _project.viewState.selectedIds.where((String s) => s != id).toList(),
),
),
status: '删除 $id',
);
}
/// 复制当前选中的动作。
///
/// 副本起始角相对原动作 +10°(钳制到 `[0, 359]`)、置于最外层、且不继承依赖。
/// 副作用:选中新副本、记录历史并重算关键路径;无选中时不做任何事。
void duplicateSelected() {
final Action? src = selected;
if (src == null) return;
// 生成不冲突的新 id。
final int n = _project.actions.length + 1;
String id = 'A$n';
int guard = n;
while (_project.actionById(id) != null) {
guard++;
id = 'A$guard';
}
final Action a = src.copyWith(
id: id,
name: '${src.name} 副本',
startAngle: (src.startAngle + 10).clamp(0, 359),
layer: _project.maxLayer + 1,
row: 0,
2026-09-18 16:50:12 +08:00
deps: const <Dependency>[],
);
_mutate(
_project.copyWith(
actions: <Action>[..._project.actions, a],
viewState: _project.viewState.copyWith(selectedIds: <String>[a.id]),
),
status: '复制 $id',
);
}
/// 以函数式方式更新动作:对 id 匹配的动作应用 [fn],其余保持不变。
///
/// 参数 [id]:目标动作;[fn]:变换函数;[status]:可选状态栏文本。
/// 副作用:经 [_mutate] 记录历史、重算关键路径并刷新。
void updateAction(String id, Action Function(Action) fn, {String? status}) {
final List<Action> actions = _project.actions
.map((Action a) => a.id == id ? fn(a) : a)
.toList();
_mutate(_project.copyWith(actions: actions), status: status);
}
/// 按角度增量 [deltaAngle] 移动动作起点。
///
/// 参数 [snap]:是否按 [Cycle.snapDeg] 吸附。
/// 起点会被钳制到 `[0, 360 - durationAngle]`,保证动作不越界。
void moveAction(String id, double deltaAngle, {bool snap = true}) {
final Action? a = _project.actionById(id);
if (a == null) return;
final double step = snap ? _project.cycle.snapDeg : 0;
double ns = a.startAngle + deltaAngle;
ns = ns.clamp(0, 360 - a.durationAngle);
if (step > 0) ns = snapTo(ns, step);
updateAction(id, (Action x) => x.copyWith(startAngle: ns));
}
/// 直接设置动作起始角(可吸附)。
///
/// 起点钳制到 `[0, 360 - durationAngle]`,避免超出整圈。
void setActionStart(String id, double start, {bool snap = true}) {
final Action? a = _project.actionById(id);
if (a == null) return;
final double step = snap ? _project.cycle.snapDeg : 0;
double ns = start.clamp(0, 360 - a.durationAngle);
if (step > 0) ns = snapTo(ns, step);
updateAction(id, (Action x) => x.copyWith(startAngle: ns));
}
/// 设置动作持续角(可吸附)。
///
/// 持续角先钳制到 `[5, 360]`;若 `start + duration > 360` 则压缩为
/// `360 - start`,保证动作不跨出整圈。
void setActionDuration(String id, double duration, {bool snap = true}) {
final Action? a = _project.actionById(id);
if (a == null) return;
final double step = snap ? _project.cycle.snapDeg : 0;
double nd = duration.clamp(5, 360);
if (step > 0) nd = snapTo(nd, step);
if (a.startAngle + nd > 360) nd = 360 - a.startAngle;
updateAction(id, (Action x) => x.copyWith(durationAngle: nd));
}
/// 按增量 [delta] 调整动作层号,结果钳制到 `[0, 63]`;无变化时不记录历史。
void changeLayer(String id, int delta) {
final Action? a = _project.actionById(id);
if (a == null) return;
final int nl = (a.layer + delta).clamp(0, 63);
if (nl == a.layer) return;
updateAction(id, (Action x) => x.copyWith(layer: nl), status: '层 L${nl + 1}');
}
/// 直接设置动作层号(钳制到 `[0, 63]`)。
void setLayer(String id, int layer) {
final int nl = layer.clamp(0, 63);
updateAction(id, (Action x) => x.copyWith(layer: nl), status: '层 L${nl + 1}');
}
/// 将动作 [id] 移动到第 [targetLane] 条泳道 / 轨道(上下拖拽换道)。
2026-09-18 16:50:12 +08:00
///
/// 不再因「目标泳道在该时间段已有动作」而拒绝:换道是高频拖拽操作,一旦拒绝,
/// 动作会被“磁吸”回原泳道(表现为拖不动)。现允许放入并在状态栏提示时间重叠,
/// 由用户自行调整相位;[canPlaceInLane] 仍用于拖拽时的可视化提示。
/// 槽位保持原值(超出目标泳道槽位数时由布局钳制到末槽)。
void moveActionLane(String id, int targetLane) {
2026-09-18 16:50:12 +08:00
final Action? moving = _project.actionById(id);
if (moving == null) return;
final int lane = targetLane.clamp(0, 63);
if (lane == moving.layer) return;
updateAction(id, (Action x) => x.copyWith(layer: lane),
status: '移至轨道 L${lane + 1}');
}
/// 将动作 [id] 移动到([targetLane], [slot])——拖拽换道 / 换槽位。
///
/// 槽位钳制到目标泳道的槽位数范围;同槽时间重叠仅在状态栏提示,不阻止。
void moveActionTo(String id, int targetLane, int slot) {
final Action? moving = _project.actionById(id);
if (moving == null) return;
final int lane = targetLane.clamp(0, 63);
final int slots = _project.slotsOf(lane);
final int s = slot < 0 ? 0 : (slot >= slots ? slots - 1 : slot);
if (lane == moving.layer && s == _effectiveSlot(moving)) return;
final bool overlap = _project.actions.any((Action o) =>
o.id != id &&
o.layer == lane &&
_effectiveSlot(o) == s &&
angleRangesOverlap(moving.startAngle, moving.endAngle, o.startAngle, o.endAngle));
updateAction(id, (Action x) => x.copyWith(layer: lane, row: s),
status: overlap
? '移至 L${lane + 1} · 槽 ${s + 1}(有动作时间重叠)'
: '移至 L${lane + 1} · 槽 ${s + 1}');
}
/// 动作 [a] 在其泳道内的有效槽位(与布局层 [BarLayout.slotOf] 一致)。
int _effectiveSlot(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);
}
/// 设置泳道 [lane] 的槽位数(1–5)——「泳道加宽」:同一泳道可并列放置多个动作。
///
/// 缩窄时超出的动作不会被删除,其槽位在布局时钳制到末槽。
void setLaneSlots(int lane, int slots) {
final int n = slots.clamp(1, 5);
if (_project.slotsOf(lane) == n) return;
final Map<int, int> next = Map<int, int>.of(_project.laneSlots);
if (n <= 1) {
next.remove(lane);
} else {
next[lane] = n;
}
_mutate(
_project.copyWith(laneSlots: next),
status: n > 1 ? '泳道 L${lane + 1} 已加宽为 $n 槽(可并列 $n 个动作)' : '泳道 L${lane + 1} 恢复 1 槽',
);
}
/// 目标泳道 [lane](可选 [slot],默认取动作当前槽位)能否容纳动作 [id]。
bool canPlaceInLane(String id, int lane, {int? slot}) {
final Action? a = _project.actionById(id);
if (a == null) return false;
final int s = slot ?? _effectiveSlot(a);
return !_project.actions.any((Action o) =>
o.id != id &&
o.layer == lane &&
_effectiveSlot(o) == s &&
angleRangesOverlap(a.startAngle, a.endAngle, o.startAngle, o.endAngle));
2026-09-18 16:50:12 +08:00
}
/// 移动某个相位分区的一条边界(用于在条形图顶部直接拖拽分区)。
///
/// 参数 [index]:分区下标;[isStart]:true 改起始角,false 改结束角;
/// [angle]:目标角度(度)。结束角允许大于 360° 表示跨圈。
void movePhaseZoneBoundary(int index, bool isStart, double angle) {
if (index < 0 || index >= _project.phaseZones.length) return;
final PhaseZone z = _project.phaseZones[index];
final double a = angle.clamp(0, 400);
final PhaseZone nz = isStart ? z.copyWith(startAngle: a) : z.copyWith(endAngle: a);
final List<PhaseZone> zones = List<PhaseZone>.of(_project.phaseZones)..[index] = nz;
setPhaseZones(zones, status: '调整相位分区');
}
/// 对齐相位:把所有选中动作的起始角对齐到**主选中项**的起始角。
///
/// 支持 Ctrl 多选后一次对齐多个动作;只有一个选中时等价于对齐到自身(无变化),
/// 若主选中项起始角为 0 则等价于“对齐到 0°”。
void alignPhase() {
final List<String> ids = _project.viewState.selectedIds;
if (ids.isEmpty) return;
final Action? ref = _project.actionById(ids.first);
if (ref == null) return;
final double target = ref.startAngle;
final List<Action> actions = _project.actions.map((Action a) {
if (!ids.contains(a.id)) return a;
final double ns = target.clamp(0, 360 - a.durationAngle);
return a.copyWith(startAngle: ns);
}).toList();
_mutate(_project.copyWith(actions: actions), status: '对齐相位(${ids.length} 个动作)');
}
/// 添加/覆盖一条依赖:在 [toId] 上记录来自 [fromId] 的依赖。
///
/// 参数 [fromId]/[toId]:前驱/后继动作;[type]:依赖类型;[offset]:角度偏移。
/// 自依赖(fromId == toId)或后继不存在时忽略。若同一前驱已存在则先移除再添加。
void addDependency(String fromId, String toId, DepType type, double offset) {
if (fromId == toId) return;
final Action? to = _project.actionById(toId);
if (to == null) return;
updateAction(
toId,
(Action x) => x.copyWith(
deps: <Dependency>[
...x.deps.where((Dependency d) => d.fromId != fromId),
Dependency(fromId: fromId, toId: toId, type: type, offsetAngle: offset),
],
),
status: '添加依赖 $fromId→$toId',
);
}
/// 移除 [toId] 上来自 [fromId] 的依赖。
void removeDependency(String fromId, String toId) {
updateAction(
toId,
(Action x) => x.copyWith(
deps: x.deps.where((Dependency d) => d.fromId != fromId).toList(),
),
status: '删除依赖 $fromId→$toId',
);
}
/// 设置依赖走线的手动偏移(拖拽连线时调用;单位 px,限制 ±200)。
///
/// 条形 / 流程图为横向走线的纵向偏移(跨行走廊为水平偏移),
/// 圆周为绕行圆弧的半径偏移;传入 0 即恢复自动位置。
/// 拖动过程中可高频调用,撤销历史与其它拖拽编辑保持一致(每次压栈)。
void setDependencyOffset(String fromId, String toId, double value, {String? status}) {
final Action? to = _project.actionById(toId);
if (to == null) return;
if (!to.deps.any((Dependency d) => d.fromId == fromId)) return;
final double v = value.clamp(-kMaxRouteOffset, kMaxRouteOffset);
final List<Dependency> deps = to.deps
.map((Dependency d) => d.fromId == fromId ? d.copyWith(routeOffset: v) : d)
.toList();
updateAction(toId, (Action x) => x.copyWith(deps: deps), status: status);
}
/// 复位依赖走线的手动偏移(双击连线 / 右键菜单调用)。
void resetDependencyOffset(String fromId, String toId) {
setDependencyOffset(fromId, toId, 0, status: '已复位依赖走线 $fromId→$toId');
}
2026-09-18 16:50:12 +08:00
/// 计算关键路径并更新 [_criticalActions] / [_criticalDeps]。
///
/// 采用“最早开始时间(EST)+ 拓扑排序 + 反向回溯”的经典方法:
/// 1. 依据依赖边构建前驱计数(indeg)与后继邻接表(succ);
/// 2. Kahn 算法拓扑排序;若存在环导致排序不完整,则退化为原始顺序;
/// 3. 按拓扑序计算每个动作的最早开始时间,并记录贡献最大约束的前驱;
/// 4. 找出结束时间最晚的动作,沿 prev 反向回溯得到关键动作与关键依赖。
///
/// 副作用:替换 [_criticalActions] 与 [_criticalDeps];不触发通知。
void _recomputeCritical() {
// 步骤 0:建立 id -> Action 索引,便于 O(1) 查询。
final Map<String, Action> byId = <String, Action>{
for (final Action a in _project.actions) a.id: a,
};
final Map<String, double> earliest = <String, double>{};
final Map<String, String?> prev = <String, String?>{};
final List<String> order = _project.actions.map((Action a) => a.id).toList();
final Map<String, int> indeg = <String, int>{for (final String id in order) id: 0};
final Map<String, List<String>> succ = <String, List<String>>{};
// 步骤 1:遍历依赖边,统计入度并构建后继邻接表(忽略悬空引用)。
for (final Action a in _project.actions) {
for (final Dependency d in a.deps) {
if (byId.containsKey(d.fromId) && indeg.containsKey(a.id)) {
indeg[a.id] = indeg[a.id]! + 1;
succ.putIfAbsent(d.fromId, () => <String>[]).add(a.id);
}
}
}
// 步骤 2:Kahn 拓扑排序,从入度为 0 的节点开始。
final List<String> queue = order.where((String id) => indeg[id] == 0).toList();
for (final String id in order) {
earliest[id] = 0;
prev[id] = null;
}
final List<String> topo = <String>[];
while (queue.isNotEmpty) {
final String id = queue.removeAt(0);
topo.add(id);
for (final String s in succ[id] ?? <String>[]) {
indeg[s] = indeg[s]! - 1;
if (indeg[s] == 0) queue.add(s);
}
}
// 若排序结果不完整(存在环),退化为原始动作顺序,保证算法仍可推进。
if (topo.length != order.length) {
topo
..clear()
..addAll(order);
}
// 步骤 3:按拓扑序求最早开始时间,记录产生该时间的“关键前驱”。
for (final String id in topo) {
final Action a = byId[id]!;
double est = 0;
String? p;
for (final Dependency d in a.deps) {
final Action? pred = byId[d.fromId];
if (pred == null) continue;
final double predEnd = (earliest[pred.id] ?? 0) + pred.durationAngle;
double cand;
// 按依赖类型计算约束候选值:
// FS:前驱结束后开始(predEnd + offset)
// SS:前驱开始后开始(predStart + offset)
// FF:前驱结束后结束(predEnd + offset - 本动作时长)
// SF:前驱开始后结束(predStart + offset - 本动作时长)
switch (d.type) {
case DepType.fs:
cand = predEnd + d.offsetAngle;
break;
case DepType.ss:
cand = (earliest[pred.id] ?? 0) + d.offsetAngle;
break;
case DepType.ff:
cand = predEnd + d.offsetAngle - a.durationAngle;
break;
case DepType.sf:
cand = (earliest[pred.id] ?? 0) + d.offsetAngle - a.durationAngle;
break;
}
if (cand > est) {
est = cand;
p = pred.id;
}
}
earliest[id] = est;
prev[id] = p;
}
// 步骤 4a:找到结束时间最晚的动作作为关键路径终点。
String? last;
double bestEnd = -1;
for (final Action a in _project.actions) {
final double end = (earliest[a.id] ?? 0) + a.durationAngle;
if (end > bestEnd) {
bestEnd = end;
last = a.id;
}
}
// 步骤 4b:沿 prev 链反向回溯,收集关键动作与关键依赖边。
final Set<String> critA = <String>{};
final Set<String> critD = <String>{};
String? cur = last;
while (cur != null) {
critA.add(cur);
final String? p = prev[cur];
if (p != null) critD.add('$p->$cur');
cur = p;
}
_criticalActions = critA;
_criticalDeps = critD;
}
}