Files
EasyDesignCollection/lib/state/app_controller.dart
T

896 lines
32 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:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart';
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 = project ?? Project.demo(),
_dirty = project == null;
/// 当前项目数据(唯一可变引用,替换时整体赋值)。
Project _project;
/// 当前主题亮度(默认浅色 / 白底)。
Brightness _brightness = Brightness.light;
/// 是否已获得有效授权(有效时才允许导出 SVG / PNG)。
bool _licensed = false;
/// 是否已授权。
bool get licensed => _licensed;
/// 设置授权状态并刷新(启动时校验 / 重新读取 .lic 后调用)。
void setLicensed(bool value) {
if (_licensed == value) return;
_licensed = value;
notifyListeners();
}
2026-09-18 16:50:12 +08:00
/// 当前项目对应的文件路径;null 表示尚未保存。
String? _filePath;
/// 是否有未保存修改。
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 = '就绪';
/// 最近一次保存时间。
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() {
_autosaveTimer?.cancel();
super.dispose();
}
/// 自动保存当前项目(内部方法,异常静默忽略以避免打断编辑)。
Future<void> _autosave() async {
try {
await Storage.instance.writeAutosave(
_project,
projectPath: _filePath,
clean: !_dirty,
);
} catch (_) {}
}
/// 退出前将自动保存标记为“干净”,表示已正常关闭无需恢复。
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 = next;
_dirty = true;
if (status != null) _status = status;
_recomputeCritical();
notifyListeners();
}
/// 撤销:弹出 [_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();
}
/// 新建项目:清空历史,构造一个含两个工位、两个动作(动作 1 / 动作 2)的初始项目。
///
/// 副作用:重置文件路径、置脏、更新状态并重算关键路径。
void newProject() {
_undo.clear();
_redo.clear();
_project = Project(
name: '未命名节拍',
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 = '新建项目';
_recomputeCritical();
notifyListeners();
}
/// 载入一个项目(打开文件或恢复自动保存时使用)。
///
/// 参数 [p]:项目数据;[path]:来源文件路径;[dirty]:载入后是否标记为脏
/// (如自动恢复场景)。副作用:清空撤销/重做栈、重算关键路径并刷新。
void loadProject(Project p, {String? path, bool dirty = false}) {
_undo.clear();
_redo.clear();
_project = p;
_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;
}
/// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。
static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last;
/// 切换视图模式并更新状态栏文本。
void setViewMode(ViewMode mode) {
_project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode));
_status = mode == ViewMode.bar ? '条形节拍视图' : '圆周节拍视图';
notifyListeners();
}
/// 选中指定动作([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 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();
}
/// 适应窗口:按当前视图内容计算缩放与平移,使其完整可见。
///
/// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放,
/// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。
/// - 条形视图:布局本身按视口高度自适应,直接回到 `zoom = 1`。
void fitView() {
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.circular) {
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);
final double contentW = l.plotRight + 60;
final double contentH = l.yFor(l.ordered.length) + 40;
z = math.min(vp.width / contentW, vp.height / contentH).clamp(0.25, 1.0);
px = 0;
py = 0;
}
_project = _project.copyWith(
viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py),
);
_status = '适应窗口';
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 int row = _project.actions.length;
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: row,
);
_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: _project.actions.length,
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
///
/// 泳道可容纳多个动作;仅当目标泳道内存在**时间重叠**的动作时才拒绝,
/// 并给出状态提示(与音频轨道“不能重叠”的语义一致)。
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;
final bool overlap = _project.actions.any((Action o) =>
o.id != id &&
o.layer == lane &&
angleRangesOverlap(moving.startAngle, moving.endAngle, o.startAngle, o.endAngle));
if (overlap) {
_status = '轨道 L${lane + 1} 在该时间段已有动作,无法放入';
notifyListeners();
return;
2026-09-18 16:50:12 +08:00
}
updateAction(id, (Action x) => x.copyWith(layer: lane, row: lane),
status: '移至轨道 L${lane + 1}');
}
/// 目标泳道 [lane] 是否能容纳动作 [id](不与其内动作时间重叠)。
bool canPlaceInLane(String id, int lane) {
final Action? a = _project.actionById(id);
if (a == null) return false;
return !_project.actions.any((Action o) =>
o.id != id &&
o.layer == lane &&
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',
);
}
/// 计算关键路径并更新 [_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;
}
}