Files
EasyDesignCollection/lib/ui/dialogs.dart
T
admin 50d2303951 fix(android): 保存/导出写入系统公共 Documents(可见),不再落到应用私有 data 目录
- 原生通道 seqstudio/docs:Android 10+ 走 MediaStore 写入 Documents/SequenceDiagram(免权限、商店合规);Android 9- 直接写公共目录(WRITE_EXTERNAL_STORAGE 限 maxSdk=28)

- 安卓保存/打开/导出改用「Documents 对话框」:保存输入文件名(自动补全后缀),打开列出 Documents 中的 .seq.json 点选

- 控制器新增 markSaved(外部通道保存后标记干净);重新构建签名 APK
2026-10-06 22:34:16 +08:00

2065 lines
84 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 对话框集合:集中定义应用内的所有弹窗流程。
//
// 架构位置:属于 UI 层,向上被 AppShell / CanvasOverlays 等调用,
// 向下通过 AppController 读写项目状态、通过 dart:io 访问文件系统。
// 包含:
// · 通用消息提示(showMessage);
// · .seq.json 文件浏览/保存对话框(FileBrowserDialog / pickFile);
// · 动作编辑、依赖编辑、工艺参数设置、帮助中心等业务对话框。
import 'dart:io';
import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../license/license_service.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../persistence/android_docs.dart';
import '../persistence/storage.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
// ===================== 对话框等比缩放 =====================
/// 计算对话框的等比缩放系数。
///
/// 以 **1920×1080** 为基准:更大的窗口按比例放大(最多 1.75×),
/// 更小的窗口**不缩小**(返回 1.0),此时宁可显示不全也不要把字缩到看不清。
double dialogScale(BuildContext context) {
final Size s = MediaQuery.sizeOf(context);
if (s.width <= 0 || s.height <= 0) return 1;
final double k = math.min(s.width / 1920, s.height / 1080);
return k.clamp(1.0, 1.75);
}
/// 按 [dialogScale] 等比缩放固定尺寸的对话框内容(**含背景与文字**)。
///
/// 关键:用「放大后的 SizedBox 包裹 + [FittedBox]」而不是单纯 [Transform.scale]。
/// 前者同时放大**布局尺寸与绘制**,因此对话框背景与文字始终同尺寸、不会溢出;
/// 后者只放大绘制、背景不变,导致 100% 显示比例的大屏上文字超出背景边缘。
Widget scaledDialogBox(BuildContext context, double width, double height, Widget child) {
final double k = dialogScale(context);
if (k <= 1.0001) return SizedBox(width: width, height: height, child: child);
return SizedBox(
width: width * k,
height: height * k,
child: FittedBox(
fit: BoxFit.fill,
child: SizedBox(width: width, height: height, child: child),
),
);
}
// ===================== 通用提示 =====================
/// 弹出一个仅含“确定”按钮的简单消息对话框。
Future<void> showMessage(BuildContext context, String title, String message) {
return showDialog<void>(
context: context,
builder: (BuildContext ctx) => AlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('确定')),
],
),
);
}
// ===================== 文件浏览 / 保存对话框 =====================
/// 文件浏览对话框:用于打开或另存为文件(工程 `.seq.json`、导出 `.svg` / `.png`)。
///
/// [saveMode] 为 true 时进入保存流程,否则为打开流程;[suffix] 决定文件过滤
/// 与保存时自动补全的后缀;[defaultName] 为保存模式的默认文件名。
class FileBrowserDialog extends StatefulWidget {
const FileBrowserDialog({
super.key,
required this.saveMode,
this.initialPath,
this.defaultName,
this.suffix = '.seq.json',
});
/// 是否为保存模式(true = 另存为,false = 打开)。
final bool saveMode;
/// 初始目录或初始文件路径。
final String? initialPath;
/// 保存模式的默认文件名(如 `装配线节拍.svg`)。
final String? defaultName;
/// 文件后缀:过滤目录列表并自动补全用户输入(如 `.svg` / `.png` / `.seq.json`)。
final String suffix;
/// 创建文件浏览对话框对应的状态对象。
@override
State<FileBrowserDialog> createState() => _FileBrowserDialogState();
}
/// 文件浏览对话框状态:维护当前目录、文件名输入与目录项列表。
class _FileBrowserDialogState extends State<FileBrowserDialog> {
/// 当前浏览的目录。
late Directory _dir;
/// 文件名输入控制器。
late TextEditingController _name;
/// 当前目录下的条目(子目录 + 匹配后缀的文件)。
List<FileSystemEntity> _entries = <FileSystemEntity>[];
/// 读取目录失败时的错误信息。
String? _error;
/// 解析初始路径 / 上次目录 / 桌面,初始化文件名并刷新目录列表。
@override
void initState() {
super.initState();
final String base = widget.defaultName ??
(widget.initialPath != null && widget.initialPath!.isNotEmpty
? widget.initialPath!.split(RegExp(r'[\\/]')).last
: '节拍方案${widget.suffix}');
_name = TextEditingController(text: base);
_bootstrap();
}
/// 异步确定起始目录:优先初始路径 → 上次使用的目录 → 桌面 → 用户目录。
Future<void> _bootstrap() async {
String start = '';
if (widget.initialPath != null && widget.initialPath!.isNotEmpty) {
final File f = File(widget.initialPath!);
start = await f.exists() ? f.parent.path : widget.initialPath!;
}
if (start.isEmpty || !Directory(start).existsSync()) {
start = await _readLastDir();
}
if (start.isEmpty || !Directory(start).existsSync()) {
final Directory? desktop = _desktop();
if (desktop != null) {
start = desktop.path;
} else {
start = Platform.environment['USERPROFILE'] ??
(Platform.isAndroid || Platform.isIOS
? Directory.systemTemp.path
: Directory.current.path);
}
}
_dir = Directory(start);
if (!_dir.existsSync()) _dir = Directory.current;
if (mounted) _refresh();
}
/// 上次使用目录的持久化文件路径(位于应用数据目录,跨会话记忆)。
File get _lastDirFile => File(
'${Storage.instance.appDir.path}${Platform.pathSeparator}last_dir.txt');
/// 读取上次使用的目录;不存在或不可用时返回空串。
Future<String> _readLastDir() async {
try {
final File f = _lastDirFile;
if (await f.exists()) {
final String s = (await f.readAsString()).trim();
if (s.isNotEmpty && Directory(s).existsSync()) return s;
}
} catch (_) {}
return '';
}
/// 记住本次使用的目录,便于下次直接定位。
Future<void> _writeLastDir(String path) async {
try {
final File f = _lastDirFile;
await f.parent.create(recursive: true);
await f.writeAsString(path, flush: true);
} catch (_) {}
}
/// 规范化文件名:替换其它已知后缀并补全目标后缀。
String _ensureSuffix(String raw) {
String n = raw.trim();
if (n.isEmpty) return n;
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
for (final String k in known) {
if (n.toLowerCase().endsWith(k)) {
if (k == widget.suffix) return n;
n = n.substring(0, n.length - k.length);
break;
}
}
return '$n${widget.suffix}';
}
/// 重新读取当前目录:仅保留子目录与匹配后缀的文件,
/// 目录排在文件之前并按名称不区分大小写排序。
void _refresh() {
try {
final List<FileSystemEntity> all = _dir.listSync();
_entries = all.where((FileSystemEntity e) {
if (e is Directory) return true;
return e.path.toLowerCase().endsWith(widget.suffix.toLowerCase());
}).toList()
..sort((FileSystemEntity a, FileSystemEntity b) {
final bool ad = a is Directory;
final bool bd = b is Directory;
if (ad != bd) return ad ? -1 : 1;
return a.path.toLowerCase().compareTo(b.path.toLowerCase());
});
_error = null;
} catch (e) {
_error = '无法读取目录:$e';
_entries = <FileSystemEntity>[];
}
setState(() {});
}
/// 解析桌面目录:优先 OneDrive 桌面,其次 `%USERPROFILE%\Desktop`。
///
/// 返回存在的目录;都不存在时返回 null(按钮不产生跳转)。
Directory? _desktop() {
final String? home = Platform.environment['USERPROFILE'];
final String? oneDrive = Platform.environment['OneDrive'];
final String sep = Platform.pathSeparator;
final List<String> candidates = <String>[
if (oneDrive != null && oneDrive.isNotEmpty) '$oneDrive${sep}Desktop',
if (home != null && home.isNotEmpty) '$home${sep}Desktop',
if (home != null && home.isNotEmpty) '$home${sep}OneDrive${sep}Desktop',
];
for (final String p in candidates) {
try {
if (Directory(p).existsSync()) return Directory(p);
} catch (_) {}
}
return null;
}
/// 枚举 Windows 盘符(A–Z)中当前存在的根目录。
List<String> _drives() {
final List<String> out = <String>[];
for (int i = 65; i <= 90; i++) {
final String p = '${String.fromCharCode(i)}:\\';
try {
if (Directory(p).existsSync()) out.add(p);
} catch (_) {}
}
return out;
}
/// 渲染文件浏览器:路径栏、盘符快捷入口、条目列表与文件名输入。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
final List<String> drives = _drives();
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
760,
560,
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(widget.saveMode ? '保存 ${widget.suffix} 文件' : '打开 ${widget.suffix} 文件',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)),
const SizedBox(height: 10),
Row(
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line2),
),
child: Text(_dir.path, style: TextStyle(color: t.sub, fontSize: 11)),
),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: () {
final Directory p = _dir.parent;
if (p.path != _dir.path) {
_dir = p;
_refresh();
}
},
child: const Text('上一级'),
),
],
),
const SizedBox(height: 8),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: <Widget>[
// 桌面快捷入口:仅在桌面平台显示(移动平台无“桌面”概念)。
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS)
Padding(
padding: const EdgeInsets.only(right: 6),
child: ActionChip(
avatar: Icon(Icons.desktop_windows_outlined, size: 15, color: t.accent),
label: const Text('桌面'),
onPressed: () {
final Directory? d = _desktop();
if (d != null) {
_dir = d;
_refresh();
}
},
),
),
...drives.map((String d) {
return Padding(
padding: const EdgeInsets.only(right: 6),
child: ActionChip(
label: Text(d),
onPressed: () {
_dir = Directory(d);
_refresh();
},
),
);
}),
],
),
),
const Divider(),
Expanded(
child: _error != null
? Center(child: Text(_error!, style: TextStyle(color: t.danger)))
: ListView.builder(
itemCount: _entries.length,
itemBuilder: (BuildContext ctx, int i) {
final FileSystemEntity e = _entries[i];
final bool isDir = e is Directory;
final String name = e.path.split(RegExp(r'[\\/]')).last;
return ListTile(
dense: true,
leading: Icon(isDir ? Icons.folder : Icons.description,
color: isDir ? t.accent : t.sub, size: 20),
title: Text(name, style: TextStyle(color: t.text, fontSize: 11)),
onTap: () {
if (isDir) {
_dir = Directory(e.path);
_refresh();
} else {
setState(() => _name.text = name);
}
},
);
},
),
),
const Divider(),
Row(
children: <Widget>[
Text('文件名(${widget.suffix})', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 10),
Expanded(
child: TextField(
controller: _name,
style: TextStyle(color: t.text, fontSize: 11),
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: t.panel2,
hintText: '名称${widget.suffix}',
hintStyle: TextStyle(color: t.dim, fontSize: 11),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
const SizedBox(width: 8),
FilledButton(
onPressed: () {
// 规范化文件名:空名忽略;替换其它已知后缀并补全目标后缀。
final String name = _ensureSuffix(_name.text);
if (name.isEmpty) return;
final String sep = Platform.pathSeparator;
final String path = '${_dir.path}$sep$name';
// 记住本次使用的目录,下次直接定位。
_writeLastDir(_dir.path);
Navigator.pop(context, path);
},
child: Text(widget.saveMode ? '保存' : '打开'),
),
],
),
],
),
),
),
);
}
}
/// 打开文件选择对话框并返回所选路径。
///
/// [save] 决定保存或打开模式;[suffix] 决定文件过滤与自动补全的后缀
/// (`.seq.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。
Future<String?> pickFile(
BuildContext context, {
required bool save,
String? initialPath,
String? defaultName,
String suffix = '.seq.json',
}) {
return showDialog<String>(
context: context,
builder: (BuildContext ctx) => FileBrowserDialog(
saveMode: save,
initialPath: initialPath,
defaultName: defaultName,
suffix: suffix,
),
);
}
// ===================== 安卓公共 Documents 文件对话框 =====================
/// 安卓版文件对话框:保存到 / 打开自公共 `Documents/SequenceDiagram`。
///
/// - 保存模式:输入文件名(自动补全后缀),确认后由调用方经 [AndroidDocs] 写入;
/// - 打开模式:列出 Documents 目录中匹配后缀的文件,点选返回文件名。
/// 返回值为文件名;取消返回 null。
class AndroidFileDialog extends StatefulWidget {
const AndroidFileDialog({
super.key,
required this.saveMode,
required this.defaultName,
required this.suffix,
});
/// 保存(true)或打开(false)。
final bool saveMode;
/// 保存模式的默认文件名。
final String defaultName;
/// 文件后缀(过滤与自动补全)。
final String suffix;
@override
State<AndroidFileDialog> createState() => _AndroidFileDialogState();
}
class _AndroidFileDialogState extends State<AndroidFileDialog> {
late TextEditingController _name;
List<Map<String, dynamic>> _files = <Map<String, dynamic>>[];
bool _loading = false;
String? _error;
@override
void initState() {
super.initState();
_name = TextEditingController(text: widget.defaultName);
if (!widget.saveMode) _load();
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
/// 列出 Documents 目录中的匹配文件(新在前)。
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
try {
final List<Map<String, dynamic>> all = await AndroidDocs.listFiles();
final String sfx = widget.suffix.toLowerCase();
final List<Map<String, dynamic>> matched = all
.where((Map<String, dynamic> f) => (f['name'] as String? ?? '').toLowerCase().endsWith(sfx))
.toList();
if (mounted) setState(() => _files = matched);
} catch (e) {
if (mounted) setState(() => _error = '无法读取 Documents 目录:$e');
} finally {
if (mounted) setState(() => _loading = false);
}
}
/// 替换其它已知后缀并补全目标后缀。
String _ensureSuffix(String raw) {
String n = raw.trim();
if (n.isEmpty) return n;
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
for (final String k in known) {
if (n.toLowerCase().endsWith(k)) {
if (k == widget.suffix) return n;
n = n.substring(0, n.length - k.length);
break;
}
}
return '$n${widget.suffix}';
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: Text(widget.saveMode ? '保存到 Documents' : '从 Documents 打开'),
content: SizedBox(
width: 420,
child: widget.saveMode
? Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('文件将保存到平板存储的 ${AndroidDocs.displayDir}/',
style: TextStyle(color: t.dim, fontSize: 11)),
const SizedBox(height: 10),
TextField(
controller: _name,
autofocus: true,
style: TextStyle(color: t.text, fontSize: 12.5),
decoration: InputDecoration(
isDense: true,
labelText: '文件名(${widget.suffix})',
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
],
)
: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (_loading)
const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
)
else if (_error != null)
Padding(
padding: const EdgeInsets.all(10),
child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11.5)),
)
else if (_files.isEmpty)
Padding(
padding: const EdgeInsets.all(14),
child: Text('Documents 目录中暂无 ${widget.suffix} 文件',
style: TextStyle(color: t.dim, fontSize: 11.5)),
)
else
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: _files.length,
itemBuilder: (BuildContext ctx, int i) {
final Map<String, dynamic> f = _files[i];
final String name = f['name'] as String? ?? '';
return ListTile(
dense: true,
leading: Icon(Icons.description, size: 20, color: t.sub),
title: Text(name, style: TextStyle(color: t.text, fontSize: 12)),
onTap: () => Navigator.pop(context, name),
);
},
),
),
],
),
),
actions: widget.saveMode
? <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () {
final String name = _ensureSuffix(_name.text);
if (name.isEmpty) return;
Navigator.pop(context, name);
},
child: const Text('保存'),
),
]
: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
if (!_loading && _error == null)
TextButton.icon(
onPressed: _load,
icon: const Icon(Icons.refresh, size: 16),
label: const Text('刷新'),
),
],
);
}
}
// ===================== 动作编辑对话框 =====================
/// 动作编辑对话框:修改选中动作的名称、驱动、工位、相位与颜色。
class ActionEditorDialog extends StatefulWidget {
const ActionEditorDialog({super.key, required this.controller, required this.action});
/// 全局应用控制器。
final AppController controller;
/// 待编辑的动作。
final Action action;
/// 创建动作编辑对话框对应的状态对象。
@override
State<ActionEditorDialog> createState() => _ActionEditorDialogState();
}
/// 动作编辑对话框状态:用文本控制器暂存各字段,确认时一次性写回。
class _ActionEditorDialogState extends State<ActionEditorDialog> {
/// 动作名称输入。
late TextEditingController _name;
/// 驱动 / 执行器输入。
late TextEditingController _driver;
/// 起始相位输入。
late TextEditingController _start;
/// 持续相位输入。
late TextEditingController _duration;
/// 起始时刻输入(按当前时间单位,与角度双向换算)。
late TextEditingController _startTime;
/// 持续时长输入(按当前时间单位)。
late TextEditingController _durationTime;
/// 防止角度↔时间联动时递归触发。
bool _syncing = false;
/// 当前选择的工位 id。
late String _station;
/// 当前选择的颜色值。
late int _color;
/// 用待编辑动作的现有值初始化各输入控件,并建立角度↔时间联动。
@override
void initState() {
super.initState();
final Action a = widget.action;
final UnitSettings u = widget.controller.project.units;
final double cycle = widget.controller.project.cycle.durationMs;
_name = TextEditingController(text: a.name);
_driver = TextEditingController(text: a.driver);
_start = TextEditingController(text: a.startAngle.toStringAsFixed(1));
_duration = TextEditingController(text: a.durationAngle.toStringAsFixed(1));
_startTime = TextEditingController(text: _fmtMs(a.startAngle / 360 * cycle, u));
_durationTime = TextEditingController(text: _fmtMs(a.durationAngle / 360 * cycle, u));
_station = a.stationId;
_color = a.color;
// 角度 → 时间
_start.addListener(() {
if (_syncing) return;
final double? v = double.tryParse(_start.text);
if (v == null) return;
_syncing = true;
_startTime.text = _fmtMs(v / 360 * cycle, u);
_syncing = false;
});
_duration.addListener(() {
if (_syncing) return;
final double? v = double.tryParse(_duration.text);
if (v == null) return;
_syncing = true;
_durationTime.text = _fmtMs(v / 360 * cycle, u);
_syncing = false;
});
// 时间 → 角度
_startTime.addListener(() {
if (_syncing) return;
final double? ms = parseDuration(_startTime.text, u);
if (ms == null) return;
_syncing = true;
_start.text = (ms / cycle * 360).toStringAsFixed(1);
_syncing = false;
});
_durationTime.addListener(() {
if (_syncing) return;
final double? ms = parseDuration(_durationTime.text, u);
if (ms == null) return;
_syncing = true;
_duration.text = (ms / cycle * 360).toStringAsFixed(1);
_syncing = false;
});
}
/// 按当前时间单位格式化毫秒值。
String _fmtMs(double ms, UnitSettings u) {
final int dec = u.precision >= 0 ? u.precision : kTimeDec[u.timeUnit]!;
return timeValue(ms, u.timeUnit).toStringAsFixed(dec);
}
/// 释放全部文本控制器。
@override
void dispose() {
_name.dispose();
_driver.dispose();
_start.dispose();
_duration.dispose();
_startTime.dispose();
_durationTime.dispose();
super.dispose();
}
/// 渲染动作编辑表单:名称、驱动、工位、相位与调色板。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
final Project p = widget.controller.project;
return AlertDialog(
backgroundColor: t.dialog,
title: Text('编辑 ${widget.action.id}'),
content: SizedBox(
width: 460,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: _name,
decoration: const InputDecoration(labelText: '动作名称'),
),
const SizedBox(height: 8),
TextField(
controller: _driver,
decoration: const InputDecoration(labelText: '驱动 / 执行器'),
),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
initialValue: _station,
decoration: const InputDecoration(labelText: '工位'),
items: p.stations
.map((Station s) => DropdownMenuItem<String>(value: s.id, child: Text('${s.id} ${s.name}')))
.toList(),
onChanged: (String? v) => setState(() => _station = v ?? _station),
),
const SizedBox(height: 8),
Row(
children: <Widget>[
Expanded(
child: TextField(
controller: _start,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: '起始相位 (°)'),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _duration,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: '持续相位 (°)'),
),
),
],
),
const SizedBox(height: 8),
// 按时间输入:与角度实时双向换算(单位随工艺参数设置)。
Row(
children: <Widget>[
Expanded(
child: TextField(
controller: _startTime,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: '起始时刻 (${timeUnitLabel(p.units.timeUnit)})'),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _durationTime,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: '持续时长 (${timeUnitLabel(p.units.timeUnit)})'),
),
),
],
),
const SizedBox(height: 4),
Align(
alignment: Alignment.centerLeft,
child: Text(
'角度与时间可互相换算:1 圈 = ${tfmt(p.cycle.durationMs, p.units)} = 360°',
style: TextStyle(color: t.dim, fontSize: 11),
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
children: kActionPalette.map((int col) {
return GestureDetector(
onTap: () => setState(() => _color = col),
child: Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: Color(col),
borderRadius: BorderRadius.circular(7),
border: Border.all(
color: _color == col ? t.selOutline : Colors.transparent,
width: 2,
),
),
),
);
}).toList(),
),
],
),
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () {
// 解析相位输入;解析失败则保留原值,并将相位限制在合法区间。
final double? s = double.tryParse(_start.text);
final double? d = double.tryParse(_duration.text);
widget.controller.updateAction(
widget.action.id,
(Action a) => a.copyWith(
name: _name.text.trim().isEmpty ? a.name : _name.text.trim(),
driver: _driver.text.trim(),
stationId: _station,
color: _color,
startAngle: (s ?? a.startAngle).clamp(0, 360),
durationAngle: (d ?? a.durationAngle).clamp(5, 360),
),
status: '编辑 ${widget.action.id}',
);
Navigator.pop(context);
},
child: const Text('确定'),
),
],
);
}
}
// ===================== 依赖编辑对话框 =====================
/// 依赖编辑对话框:为指定动作添加一条前置依赖。
class DependencyEditorDialog extends StatefulWidget {
const DependencyEditorDialog({super.key, required this.controller, required this.action});
/// 全局应用控制器。
final AppController controller;
/// 目标动作(依赖的“后置”端)。
final Action action;
/// 创建依赖编辑对话框对应的状态对象。
@override
State<DependencyEditorDialog> createState() => _DependencyEditorDialogState();
}
/// 依赖编辑对话框状态:维护前置动作、依赖类型与偏移角。
class _DependencyEditorDialogState extends State<DependencyEditorDialog> {
/// 选择的前置动作 id。
String? _from;
/// 依赖类型,默认 FS(完成-启动)。
DepType _type = DepType.fs;
/// 偏移角输入控制器。
final TextEditingController _offset = TextEditingController(text: '0');
/// 渲染依赖表单:前置动作、依赖类型与偏移角。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
final List<Action> others =
widget.controller.project.actions.where((Action a) => a.id != widget.action.id).toList();
return AlertDialog(
backgroundColor: t.dialog,
title: Text('为 ${widget.action.id} 添加前置依赖'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
DropdownButtonFormField<String>(
initialValue: _from,
decoration: const InputDecoration(labelText: '前置动作'),
items: others
.map((Action a) => DropdownMenuItem<String>(value: a.id, child: Text('${a.id} ${a.name}')))
.toList(),
onChanged: (String? v) => setState(() => _from = v),
),
const SizedBox(height: 8),
DropdownButtonFormField<DepType>(
initialValue: _type,
decoration: const InputDecoration(labelText: '依赖类型'),
items: const <DropdownMenuItem<DepType>>[
DropdownMenuItem<DepType>(value: DepType.fs, child: Text('FS 完成-启动(严格顺序)')),
DropdownMenuItem<DepType>(value: DepType.ss, child: Text('SS 起始-起始(并行重叠)')),
DropdownMenuItem<DepType>(value: DepType.ff, child: Text('FF 完成-完成')),
DropdownMenuItem<DepType>(value: DepType.sf, child: Text('SF 起始-完成')),
],
onChanged: (DepType? v) => setState(() => _type = v ?? _type),
),
const SizedBox(height: 8),
TextField(
controller: _offset,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: '偏移角 offset (°)'),
),
],
),
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () {
// 未选择前置动作时不提交。
if (_from == null) return;
widget.controller.addDependency(
_from!,
widget.action.id,
_type,
double.tryParse(_offset.text) ?? 0,
);
Navigator.pop(context);
},
child: const Text('添加'),
),
],
);
}
}
// ===================== 工艺参数设置对话框 =====================
/// 工艺参数对话框:设置项目名称、时间/相位单位、显示精度、
/// 循环时长、换算表与编辑辅助选项。
class SettingsDialog extends StatefulWidget {
const SettingsDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
/// 创建工艺参数对话框对应的状态对象。
@override
State<SettingsDialog> createState() => _SettingsDialogState();
}
/// 工艺参数对话框状态:以副本形式编辑单位设置,点击“应用”后统一提交。
class _SettingsDialogState extends State<SettingsDialog> {
/// 正在编辑的单位设置副本。
late UnitSettings _u;
/// 循环时长输入控制器。
late TextEditingController _cycle;
/// 项目名称输入控制器。
late TextEditingController _name;
/// 用当前项目的单位与名称初始化编辑副本。
@override
void initState() {
super.initState();
_u = widget.controller.project.units;
_cycle = TextEditingController(
text: timeValue(widget.controller.project.cycle.durationMs, _u.timeUnit)
.toStringAsFixed(_u.timeUnit == TimeUnit.ms ? 0 : 3),
);
_name = TextEditingController(text: widget.controller.project.name);
}
/// 渲染工艺参数表单:项目名、单位、精度、循环、换算表与编辑辅助。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
final double cycleMs = widget.controller.project.cycle.durationMs;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
860,
620,
Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text('工艺参数', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: t.text)),
const SizedBox(width: 14),
Text('单位与精度 / 循环与相位 / 编辑辅助',
style: TextStyle(fontSize: 11, color: t.dim)),
],
),
const Divider(height: 24),
Expanded(
child: ListView(
children: <Widget>[
Text('项目名称', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
TextField(
controller: _name,
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
const SizedBox(height: 18),
// 时间单位:ms / s / min,附精度示例。
Text('时间单位', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Row(
children: TimeUnit.values.map((TimeUnit u) {
final bool active = _u.timeUnit == u;
return Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 8),
child: _card(
t,
active: active,
title: timeUnitLabel(u),
subtitle: _timeHint(u),
example: '1° = ${tfmtAuto(cycleMs / 360)}',
onTap: () => setState(() => _u = _u.copyWith(timeUnit: u)),
),
),
);
}).toList(),
),
const SizedBox(height: 18),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('相位单位', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Row(
children: <Widget>[
Expanded(
child: _card(
t,
active: _u.phaseUnit == PhaseUnit.deg,
title: '° 角度',
subtitle: '0 – 360°',
example: '105.0°',
onTap: () => setState(() => _u = _u.copyWith(phaseUnit: PhaseUnit.deg)),
),
),
const SizedBox(width: 8),
Expanded(
child: _card(
t,
active: _u.phaseUnit == PhaseUnit.percent,
title: '% 百分比',
subtitle: '0 – 100%',
example: '29.17%',
onTap: () => setState(() => _u = _u.copyWith(phaseUnit: PhaseUnit.percent)),
),
),
],
),
],
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('显示精度', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Wrap(
spacing: 6,
children: <int>[-1, 0, 1, 2, 3, 4].map((int p) {
final bool active = _u.precision == p;
return ChoiceChip(
label: Text(p == -1 ? '自动' : '$p'),
selected: active,
onSelected: (_) => setState(() => _u = _u.copyWith(precision: p)),
);
}).toList(),
),
const SizedBox(height: 8),
Text(
'${tfmt(2400, _u)} · ${pfmt(105, _u)} · 0.700 s',
style: TextStyle(color: t.accent, fontSize: 11),
),
],
),
),
],
),
const SizedBox(height: 18),
// 循环与相位:循环时长可编辑,起点与方向为固定展示(顺时针)。
Text('循环与相位', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Row(
children: <Widget>[
Expanded(
child: TextField(
controller: _cycle,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: '循环时长(1 圈,${timeUnitLabel(_u.timeUnit)})',
isDense: true,
border: const OutlineInputBorder(),
),
),
),
const SizedBox(width: 10),
Expanded(
child: TextField(
controller: TextEditingController(text: '0.0 (12 点钟)'),
enabled: false,
decoration: const InputDecoration(
labelText: '起始相位 / 起点',
isDense: true,
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 10),
// 旋转方向:固定为顺时针(圆周视图约定)。
Expanded(
child: TextField(
controller: TextEditingController(text: '顺时针 CW'),
enabled: false,
decoration: const InputDecoration(
labelText: '旋转方向',
isDense: true,
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 18),
// 时间 / 相位换算表:以 90° 为步长展示对应关系。
Text('时间 / 相位 换算', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 6),
Table(
border: TableBorder.all(color: t.line),
children: <TableRow>[
_row(t, <String>['相位角', '时间', '百分比', '说明'], header: true),
for (final List<String> r in <List<String>>[
<String>['0°', tfmt(0, _u), '0.00%', '循环起点(12 点钟)'],
<String>['90°', tfmt(cycleMs / 4, _u), '25.00%', '四分之一圈'],
<String>['180°', tfmt(cycleMs / 2, _u), '50.00%', '半圈'],
<String>['270°', tfmt(cycleMs * 3 / 4, _u), '75.00%', '四分之三圈'],
<String>['360°', tfmt(cycleMs, _u), '100.00%', '循环终点'],
])
_row(t, r),
],
),
const SizedBox(height: 18),
// 编辑辅助:吸附步长与网格/跨圈等开关。
Text('编辑辅助', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Row(
children: <Widget>[
Text('角度吸附', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 8),
for (final double s in <double>[1, 5, 15])
Padding(
padding: const EdgeInsets.only(right: 6),
child: ChoiceChip(
label: Text('${s.toStringAsFixed(0)}°'),
selected: _u.snapAngle == s,
onSelected: (_) => setState(() => _u = _u.copyWith(snapAngle: s)),
),
),
const SizedBox(width: 16),
Text('时间吸附', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 8),
for (final double s in <double>[0.01, 0.1, 1])
Padding(
padding: const EdgeInsets.only(right: 6),
child: ChoiceChip(
label: Text(s < 1 ? '${(s * 1000).toStringAsFixed(0)} ms' : '1 s'),
selected: _u.snapTime == s,
onSelected: (_) => setState(() => _u = _u.copyWith(snapTime: s)),
),
),
],
),
const SizedBox(height: 10),
Wrap(
spacing: 10,
children: <Widget>[
FilterChip(
label: const Text('显示网格'),
selected: _u.showGrid,
onSelected: (bool v) => setState(() => _u = _u.copyWith(showGrid: v)),
),
FilterChip(
label: const Text('吸附网格'),
selected: _u.snapGrid,
onSelected: (bool v) => setState(() => _u = _u.copyWith(snapGrid: v)),
),
FilterChip(
label: const Text('跨圈自动拆分'),
selected: _u.autoSplitWrap,
onSelected: (bool v) => setState(() => _u = _u.copyWith(autoSplitWrap: v)),
),
],
),
const SizedBox(height: 18),
// 相位分区:以独立对话框编辑,支持增删 / 改名 / 改起止角,允许重叠或留空。
Row(
children: <Widget>[
Text('相位分区', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 8),
Expanded(
child: Text('名称 / 起止角 / 数量均可编辑,可重叠',
style: TextStyle(color: t.dim, fontSize: 10)),
),
OutlinedButton.icon(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => PhaseZoneDialog(controller: widget.controller),
),
icon: const Icon(Icons.edit, size: 15),
label: Text('编辑…(${widget.controller.project.phaseZones.length})',
style: const TextStyle(fontSize: 11)),
),
],
),
],
),
),
const Divider(height: 24),
Row(
children: <Widget>[
TextButton(
onPressed: () => setState(() => _u = const UnitSettings()),
child: const Text('恢复默认'),
),
const Spacer(),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
const SizedBox(width: 8),
FilledButton(
onPressed: () {
// 将输入的循环时长按当前时间单位换算为毫秒后统一提交。
final double? cv = double.tryParse(_cycle.text);
final double ms = cv == null ? cycleMs : cv * kTimeDiv[_u.timeUnit]!;
final AppController c = widget.controller;
c.setUnits(_u, status: '工艺参数已应用');
c.setCycleDuration(ms);
if (_name.text.trim().isNotEmpty && _name.text.trim() != c.project.name) {
c.setProjectName(_name.text.trim());
}
Navigator.pop(context);
},
child: const Text('应用'),
),
],
),
],
),
),
),
);
}
/// 构建换算表的一行;[header] 为 true 时使用表头样式。
TableRow _row(Tokens t, List<String> cells, {bool header = false}) {
return TableRow(
children: cells.map((String s) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
child: Text(
s,
style: TextStyle(
color: header ? t.dim : (s.endsWith('°') ? t.accent : t.sub),
fontSize: 11,
fontWeight: header ? FontWeight.w600 : FontWeight.normal,
),
),
);
}).toList(),
);
}
/// 返回各时间单位对应的使用场景提示。
String _timeHint(TimeUnit u) {
switch (u) {
case TimeUnit.ms:
return '高速动作 · 伺服点位';
case TimeUnit.s:
return '装配 / 压装(推荐)';
case TimeUnit.min:
return '热处理 · 长周期';
}
}
/// 渲染一个可点选的设置卡片(标题、副标题与示例)。
Widget _card(
Tokens t, {
required bool active,
required String title,
required String subtitle,
required String example,
required VoidCallback onTap,
}) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.12) : t.panel2,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: active ? t.accent : t.line, width: active ? 1.5 : 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(active ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 15, color: active ? t.accent : t.dim),
const SizedBox(width: 6),
Text(title, style: TextStyle(color: active ? t.text : t.sub, fontWeight: FontWeight.w600, fontSize: 12)),
],
),
const SizedBox(height: 6),
Text(subtitle, style: TextStyle(color: t.dim, fontSize: 10)),
const SizedBox(height: 4),
Text(example, style: TextStyle(color: active ? t.accent : t.dim, fontSize: 10)),
],
),
),
);
}
}
// ===================== 相位分区编辑器 =====================
/// 相位分区编辑器:增删分区、修改名称与起止角。
///
/// 设计要点:
/// - 数量不限,允许区间相互重叠,也允许结束角大于 360° 表示跨圈;
/// - 每行独立的输入控制器,行增删时通过 [_ZoneRow] 的 State 维持输入;
/// - 点击「确定」时一次性提交给 [AppController.setPhaseZones]。
class PhaseZoneDialog extends StatefulWidget {
const PhaseZoneDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
@override
State<PhaseZoneDialog> createState() => _PhaseZoneDialogState();
}
class _PhaseZoneDialogState extends State<PhaseZoneDialog> {
late List<PhaseZone> _zones;
@override
void initState() {
super.initState();
_zones = List<PhaseZone>.of(widget.controller.project.phaseZones);
}
void _add() {
setState(() {
_zones.add(const PhaseZone(name: '新分区', startAngle: 0, endAngle: 30));
});
}
void _remove(int i) {
setState(() => _zones.removeAt(i));
}
void _update(int i, PhaseZone z) {
setState(() => _zones[i] = z);
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
620,
560,
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.view_week_outlined, size: 18, color: t.accent),
const SizedBox(width: 8),
Text('相位分区', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)),
const SizedBox(width: 10),
Expanded(
child: Text('名称 / 起止角 / 数量均可编辑;允许区间重叠,结束角 > 360° 表示跨圈',
style: TextStyle(fontSize: 10, color: t.dim)),
),
],
),
const Divider(height: 20),
Expanded(
child: _zones.isEmpty
? Center(child: Text('暂无分区,点击下方「添加分区」', style: TextStyle(color: t.dim, fontSize: 11)))
: ListView.builder(
itemCount: _zones.length,
itemBuilder: (BuildContext ctx, int i) {
return _ZoneRow(
key: ValueKey<int>(i),
t: t,
zone: _zones[i],
onChanged: (PhaseZone z) => _update(i, z),
onDelete: () => _remove(i),
);
},
),
),
const Divider(height: 20),
Row(
children: <Widget>[
OutlinedButton.icon(
onPressed: _add,
icon: const Icon(Icons.add, size: 16),
label: const Text('添加分区'),
),
const SizedBox(width: 8),
TextButton(
onPressed: () => setState(() => _zones = List<PhaseZone>.of(PhaseZone.defaults)),
child: const Text('恢复默认'),
),
const Spacer(),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
const SizedBox(width: 8),
FilledButton(
onPressed: () {
widget.controller.setPhaseZones(_zones, status: '相位分区已更新');
Navigator.pop(context);
},
child: const Text('确定'),
),
],
),
],
),
),
),
);
}
}
/// 相位分区编辑器中的单行:名称、起始角、结束角与删除按钮。
class _ZoneRow extends StatefulWidget {
const _ZoneRow({super.key, required this.t, required this.zone, required this.onChanged, required this.onDelete});
final Tokens t;
final PhaseZone zone;
final ValueChanged<PhaseZone> onChanged;
final VoidCallback onDelete;
@override
State<_ZoneRow> createState() => _ZoneRowState();
}
class _ZoneRowState extends State<_ZoneRow> {
late final TextEditingController _name;
late final TextEditingController _start;
late final TextEditingController _end;
@override
void initState() {
super.initState();
_name = TextEditingController(text: widget.zone.name);
_start = TextEditingController(text: _fmt(widget.zone.startAngle));
_end = TextEditingController(text: _fmt(widget.zone.endAngle));
}
@override
void dispose() {
_name.dispose();
_start.dispose();
_end.dispose();
super.dispose();
}
static String _fmt(double v) => v == v.roundToDouble() ? v.toStringAsFixed(0) : v.toString();
void _emit() {
widget.onChanged(PhaseZone(
name: _name.text.trim().isEmpty ? '相位分区' : _name.text.trim(),
startAngle: double.tryParse(_start.text.trim()) ?? widget.zone.startAngle,
endAngle: double.tryParse(_end.text.trim()) ?? widget.zone.endAngle,
));
}
@override
Widget build(BuildContext context) {
final Tokens t = widget.t;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: _field(t, _name, '名称', (String _) => _emit()),
),
const SizedBox(width: 8),
SizedBox(
width: 90,
child: _field(t, _start, '起始°', (String _) => _emit()),
),
const SizedBox(width: 6),
Text('–', style: TextStyle(color: t.dim)),
const SizedBox(width: 6),
SizedBox(
width: 90,
child: _field(t, _end, '结束°', (String _) => _emit()),
),
IconButton(
onPressed: widget.onDelete,
icon: Icon(Icons.delete_outline, size: 17, color: t.danger),
splashRadius: 16,
tooltip: '删除分区',
),
],
),
);
}
Widget _field(Tokens t, TextEditingController c, String hint, ValueChanged<String> onChanged) {
return TextField(
controller: c,
onChanged: onChanged,
style: TextStyle(color: t.text, fontSize: 11),
decoration: InputDecoration(
isDense: true,
hintText: hint,
hintStyle: TextStyle(color: t.dim, fontSize: 11),
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
);
}
}
// ===================== 工位管理对话框 =====================
/// 工位管理对话框:增删工位、改名称与颜色、调整顺序。
///
/// 一个流程可能包含多个工位;删除工位后,其原动作会自动改挂到第一个工位。
class StationDialog extends StatefulWidget {
const StationDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
@override
State<StationDialog> createState() => _StationDialogState();
}
class _StationDialogState extends State<StationDialog> {
late List<Station> _stations;
@override
void initState() {
super.initState();
_stations = List<Station>.of(widget.controller.project.stations);
}
/// 生成不冲突的新工位 id(ST{n})。
String _nextId() {
final Set<String> used = _stations.map((Station s) => s.id).toSet();
int n = _stations.length + 1;
while (used.contains('ST$n')) {
n++;
}
return 'ST$n';
}
void _add() {
setState(() {
_stations.add(Station(
id: _nextId(),
name: '工位 ${_stations.length + 1}',
order: _stations.length,
color: kActionPalette[_stations.length % kActionPalette.length],
));
});
}
void _remove(int i) {
if (_stations.length <= 1) return;
setState(() => _stations.removeAt(i));
}
void _move(int i, int delta) {
final int j = i + delta;
if (j < 0 || j >= _stations.length) return;
setState(() {
final Station s = _stations.removeAt(i);
_stations.insert(j, s);
});
}
void _save() {
// 归一化 order 为列表顺序,保证条形视图按此排序。
final List<Station> out = <Station>[
for (int i = 0; i < _stations.length; i++) _stations[i].copyWith(order: i),
];
widget.controller.setStations(out, status: '工位已更新(${out.length} 个)');
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
640,
560,
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.precision_manufacturing_outlined, size: 18, color: t.accent),
const SizedBox(width: 8),
Text('工位管理', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)),
const SizedBox(width: 10),
Expanded(
child: Text('可增删工位、改名称与颜色、调整顺序;删除工位后其动作自动改挂到第一个工位',
style: TextStyle(fontSize: 10, color: t.dim)),
),
],
),
const Divider(height: 20),
Expanded(
child: ListView.builder(
itemCount: _stations.length,
itemBuilder: (BuildContext ctx, int i) {
return _StationRow(
key: ValueKey<String>(_stations[i].id),
t: t,
station: _stations[i],
first: i == 0,
last: i == _stations.length - 1,
canDelete: _stations.length > 1,
onChanged: (Station s) => setState(() => _stations[i] = s),
onMoveUp: () => _move(i, -1),
onMoveDown: () => _move(i, 1),
onDelete: () => _remove(i),
);
},
),
),
const Divider(height: 20),
Row(
children: <Widget>[
OutlinedButton.icon(
onPressed: _add,
icon: const Icon(Icons.add, size: 16),
label: const Text('添加工位'),
),
const SizedBox(width: 10),
Text('共 ${_stations.length} 个工位', style: TextStyle(color: t.dim, fontSize: 11)),
const Spacer(),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
const SizedBox(width: 8),
FilledButton(onPressed: _save, child: const Text('确定')),
],
),
],
),
),
),
);
}
}
/// 工位管理中的单行:颜色、id、名称、排序与删除。
class _StationRow extends StatefulWidget {
const _StationRow({
super.key,
required this.t,
required this.station,
required this.first,
required this.last,
required this.canDelete,
required this.onChanged,
required this.onMoveUp,
required this.onMoveDown,
required this.onDelete,
});
final Tokens t;
final Station station;
final bool first;
final bool last;
final bool canDelete;
final ValueChanged<Station> onChanged;
final VoidCallback onMoveUp;
final VoidCallback onMoveDown;
final VoidCallback onDelete;
@override
State<_StationRow> createState() => _StationRowState();
}
class _StationRowState extends State<_StationRow> {
late final TextEditingController _name;
@override
void initState() {
super.initState();
_name = TextEditingController(text: widget.station.name);
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Tokens t = widget.t;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: <Widget>[
// 颜色:点击弹出调色板。
PopupMenuButton<int>(
tooltip: '选择颜色',
onSelected: (int c) => widget.onChanged(widget.station.copyWith(color: c)),
itemBuilder: (BuildContext ctx) => kActionPalette
.map((int c) => PopupMenuItem<int>(
value: c,
height: 36,
child: Row(
children: <Widget>[
Container(
width: 18,
height: 18,
decoration: BoxDecoration(color: Color(c), borderRadius: BorderRadius.circular(5)),
),
const SizedBox(width: 8),
Text('#${c.toRadixString(16).padLeft(8, '0').substring(2).toUpperCase()}',
style: TextStyle(color: t.text, fontSize: 11)),
],
),
))
.toList(),
child: Container(
width: 30,
height: 30,
decoration: BoxDecoration(
color: Color(widget.station.color),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line2),
),
),
),
const SizedBox(width: 8),
Container(
width: 44,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line),
),
child: Text(widget.station.id, style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _name,
onChanged: (String v) => widget.onChanged(
widget.station.copyWith(name: v.trim().isEmpty ? widget.station.name : v.trim())),
style: TextStyle(color: t.text, fontSize: 11.5),
decoration: InputDecoration(
isDense: true,
hintText: '工位名称',
hintStyle: TextStyle(color: t.dim, fontSize: 11),
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
),
IconButton(
onPressed: widget.first ? null : widget.onMoveUp,
icon: const Icon(Icons.keyboard_arrow_up, size: 18),
splashRadius: 15,
tooltip: '上移',
),
IconButton(
onPressed: widget.last ? null : widget.onMoveDown,
icon: const Icon(Icons.keyboard_arrow_down, size: 18),
splashRadius: 15,
tooltip: '下移',
),
IconButton(
onPressed: widget.canDelete ? widget.onDelete : null,
icon: Icon(Icons.delete_outline, size: 17, color: widget.canDelete ? t.danger : t.dim),
splashRadius: 16,
tooltip: widget.canDelete ? '删除工位' : '至少保留一个工位',
),
],
),
);
}
}
// ===================== 帮助中心对话框 =====================
/// 帮助中心对话框:以四个标签页展示快速开始、快捷键、
/// 双视图说明以及单位与导出等信息。
class HelpDialog extends StatelessWidget {
const HelpDialog({super.key});
/// 渲染帮助中心:标签栏 + 各标签页的内容列表。
@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(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.help_outline, color: t.accent),
const SizedBox(width: 8),
Text('帮助中心', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: t.text)),
],
),
const Divider(height: 22),
Expanded(
child: DefaultTabController(
length: 6,
child: Column(
children: <Widget>[
const TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(text: '开始与动作'),
Tab(text: '时间与依赖'),
Tab(text: '相位分区与视图'),
Tab(text: 'AI 与导出'),
Tab(text: '界面与快捷键'),
Tab(text: '关于'),
],
),
Expanded(
child: TabBarView(
children: <Widget>[
// 目标:完成方案的搭建与动作的增删改。
_section(t, <List<String>>[
<String>['我要新建方案', '顶部「新建」创建空白节拍;「打开」载入 .seq.json。'],
<String>['我要先看看示例', '首次启动载入 2 个动作的示例节拍,可直接修改。'],
<String>['我要新增动作', '双击画布空白处在点击相位新增;或左侧「新建」在 0° 新增(默认最外层)。'],
<String>['我要删除动作', '选中后:左侧「删除」/ 行内删除图标 / Delete 键 / 右键菜单;至少保留一个动作 / 泳道。'],
<String>['我要改动作属性', '双击画布色块(条形块 / 圆弧)或左侧动作行 → 打开动作编辑对话框;也可选中后点左侧行内编辑图标。'],
<String>['我要复制 / 对齐', '画布左下角「编辑工具」→「复制」/「对齐」;圆周视图右侧浮动工具条同款。'],
<String>['我要编辑工位', '左侧「动作和执行编辑」→「编辑工位」:可增删工位、改名称与颜色、上下调整顺序;删除工位后其动作自动改挂到第一个工位。'],
<String>['一条泳道放多个动作', '泳道/轨道=一个执行器:上下拖拽(条形)或 Shift+径向拖拽(圆周)换道;不重叠即可共存,标题合并显示(/ 分隔,≤2 行)。'],
]),
// 目标:调整时间轴与动作间的先后 / 并行关系。
_section(t, <List<String>>[
<String>['我要改时间轴长度', '左侧「时序创建和编辑」→「编辑时序与节拍参数」,或按 F2 →「循环与相位」→ 循环时长 → 应用。'],
<String>['我要调相位 / 时长', '拖动动作块平移相位;拖条形右端改持续角;圆周视图拖弧两端改起止角;右侧滑杆可精调。'],
<String>['我要让动作跨循环', '使「起始角 + 持续角 > 360°」,会自动拆分并以半透明虚线渲染尾段。'],
<String>['我要加前置依赖(输入)', '右侧「前置依赖 · 输入」→「添加前置依赖」;或右键动作 →「添加依赖」。'],
<String>['一个动作多输入', '可重复添加多条前置依赖,逐条列出、逐条可删。'],
<String>['一个动作多输出', '在「输出依赖 · 结果」查看本动作指向的后续动作,并可逐条删除。'],
<String>['FS / SS 是什么', 'FS 绿色实线=完成后启动;SS 琥珀虚线=可提前启动(并行重叠,带 +n°)。'],
]),
// 目标:编辑相位分区并控制画布显示。
_section(t, <List<String>>[
<String>['相位分区是什么', '把一个循环按角度分成的命名工艺阶段(默认上料/夹紧/加工/检测/下料),条形图顶部标注带即它。'],
<String>['我要编辑相位分区', '左侧「动作和执行编辑」→「编辑相位分区」;或 F2 →「相位分区」→「编辑…」。增删分区、改名称与起止角;可重叠、可留空、>360° 表示跨圈。'],
<String>['我要隐藏相位分区', '左侧「显示选项」取消勾选「相位分区标注」。'],
<String>['刻度怎么读', '条形视图:分区带与刻度线之间上排为相位、下排为等价时间;圆周视图:每 30° 的度数外侧标注等价时间。'],
<String>['我要切换视图', '顶部「条形节拍 / 圆周节拍」分段开关,两种视图共享同一份数据;标题分别为「条形时序视图」「圆周时序视图」。'],
<String>['我要缩放 / 平移', 'Ctrl+滚轮 以光标为锚点缩放;普通滚轮或拖拽空白平移。'],
<String>['我要完整显示', '顶部「适应视图」:自动按内容(含刻度、箭头、跨圈标注)计算缩放与居中,编辑后也不会被裁切。'],
<String>['我要开关标注', '左侧「显示选项」逐项开关双刻度、依赖箭头、圆环背景、层标注、跨循环高亮等。'],
]),
// 目标:用 AI 生成,并导出成果。
_section(t, <List<String>>[
<String>['我要 AI 生成', '顶部「AI 生成」→ 填 DeepSeek API Key → 选模型(Flash / Pro)→ 选强度(高 / 最高)→ 用自然语言描述 → 生成。'],
<String>['生成效果不好', '描述里写清:循环时长、工位数、各动作时长、哪些顺序(完成后启动)、哪些并行。'],
<String>['我要看节拍统计', '画布左下角「节拍统计」按钮 → 弹窗查看循环周期、动作数、关键路径、最大并行度、相位覆盖率与瓶颈工位(仅展示可从项目数据推导的指标)。'],
<String>['我要导出 SVG', '顶部「导出 SVG」:矢量、分层、带语义 id 与 data-*,可直接进工艺卡 / MES。'],
<String>['我要导出 PNG', '顶部「导出 PNG」:按 2 倍像素比导出当前画布为位图。'],
<String>['我要保存 / 恢复', '「保存」写入 .seq.json 并生成 .bak;每 5 秒自动快照,异常退出后启动可恢复。'],
]),
// 目标:调整界面与使用快捷键。
_section(t, <List<String>>[
<String>['我要隐藏 / 显示侧栏', '工具栏右侧两个侧栏按钮,分别控制左、右侧栏。'],
<String>['我要钉住侧栏', '侧栏标题右侧图钉:钉住=固定占位;取消钉住=悬浮,鼠标移开自动收起。'],
<String>['边缘把手', '侧栏收起后画布边缘有细把手:悬停临时展开,点击固定显示。'],
<String>['拖拽 / 缩放', '左键拖拽平移相位;拖端点改时长;Shift+拖拽改层;Ctrl+滚轮缩放。'],
<String>['双击编辑', '双击画布色块(条形块 / 圆弧)或左侧动作行 → 打开动作编辑对话框。'],
<String>['右键动作', '菜单:添加依赖 / 改层 / 复制 / 删除。'],
<String>['撤销 / 保存', 'Ctrl+Z / Ctrl+Y 撤销重做;Ctrl+S 保存;Ctrl+O / Ctrl+N 打开 / 新建。'],
<String>['帮助入口', '顶部工具栏右侧「?」或 F1 打开帮助中心;画布编辑工具条不重复放置帮助按钮。'],
<String>['导出入口', '导出 SVG / PNG 统一放在顶部工具栏右侧,避免多处重复。'],
<String>['其它', 'F2 编辑时序与节拍参数(含单位与相位分区);F3 切换深/浅主题;Delete 删除选中动作。'],
]),
// 关于:设计人、版本、版权、授权信息与本机 MAC。
_about(context, t),
],
),
),
],
),
),
),
Align(
alignment: Alignment.centerRight,
child: FilledButton(onPressed: () => Navigator.pop(context), child: const Text('关闭')),
),
],
),
),
),
);
}
/// 用系统默认程序打开网址(官网导航)。
Future<void> _openUrl(String url) async {
try {
await Process.run('rundll32', <String>['url.dll,FileProtocolHandler', url]);
} catch (_) {
try {
await Process.run('cmd', <String>['/c', 'start', '', url], runInShell: true);
} catch (_) {}
}
}
/// 「关于」页:软件信息 + 授权状态 + 本机 MAC + 授权指南 + 官网入口。
Widget _about(BuildContext context, Tokens t) {
final LicenseInfo info = LicenseService.instance.info;
final String lic = info.valid
? '已授权(${info.filePath?.split(RegExp(r'[\\/]')).last ?? '.lic'})'
: '未授权';
Widget row(String k, String v, {Color? vc}) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: 120,
child: Text(k, style: TextStyle(color: t.accent, fontWeight: FontWeight.w600, fontSize: 12.5)),
),
Expanded(
child: SelectableText(v, style: TextStyle(color: vc ?? t.sub, fontSize: 12.5, height: 1.5)),
),
],
),
);
Widget guideLine(String s) =>
Text(s, style: TextStyle(color: t.sub, fontSize: 11.5, height: 1.7));
return ListView(
padding: const EdgeInsets.only(top: 14),
children: <Widget>[
row('软件名称', '时序图设计器 · Sequence Diagram Studio'),
row('设计人', '呆头鹅'),
row('版本', 'V1.1.1'),
row('授权状态', lic, vc: info.valid ? t.ok : t.danger),
// 注意:绝不能展示「期望授权串」——它等同于 .lic 内容,公开即可被绕过授权。
row('本机 MAC', info.mac ?? '读取失败'),
row('版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'),
row('用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'),
const SizedBox(height: 6),
// 官网入口(点击图标导航到 sincos.cc)。
Row(
children: <Widget>[
InkWell(
onTap: () => _openUrl('https://sincos.cc'),
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(6),
child: Icon(Icons.public, size: 20, color: t.accent),
),
),
const SizedBox(width: 4),
Text('官网:', style: TextStyle(color: t.dim, fontSize: 12)),
InkWell(
onTap: () => _openUrl('https://sincos.cc'),
child: Text('sincos.cc',
style: TextStyle(color: t.accent, fontSize: 12.5, decoration: TextDecoration.underline)),
),
],
),
const SizedBox(height: 10),
// 授权指南(替代原来的邮件申请按钮)。
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: t.info,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: t.line),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.menu_book_outlined, size: 16, color: t.accent),
const SizedBox(width: 6),
Text('授权指南', style: TextStyle(color: t.accent, fontSize: 12.5, fontWeight: FontWeight.w600)),
],
),
const SizedBox(height: 8),
guideLine('1. 复制上方「本机 MAC」。'),
guideLine('2. 访问官网 sincos.cc,或把 MAC 发送到邮箱 liuyu65@126.com 申请授权。'),
guideLine('3. 收到 .lic 文件后,放入软件目录下的 license 文件夹,重启软件即可导出 SVG / PNG。'),
],
),
),
],
);
}
/// 渲染帮助中的一个条目列表,每行左侧为标题、右侧为说明。
Widget _section(Tokens t, List<List<String>> rows) {
return ListView(
padding: const EdgeInsets.only(top: 14),
children: rows.map((List<String> r) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: 150,
child: Text(r[0], style: TextStyle(color: t.accent, fontWeight: FontWeight.w600, fontSize: 12)),
),
Expanded(
child: Text(r[1], style: TextStyle(color: t.sub, fontSize: 11, height: 1.5)),
),
],
),
);
}).toList(),
);
}
}