Files
EasyDesignCollection/lib/ui/dialogs.dart
T

2873 lines
117 KiB
Dart
Raw Permalink 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);
// · .edc.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 '../modules/module_registry.dart';
import '../persistence/android_docs.dart';
import '../persistence/storage.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
import '../update/update_service.dart';
import '../version.dart';
import 'app_logo.dart';
import 'update_dialog.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` / `.arch.json`、导出 `.svg` / `.png` / `.dxf`)。
///
/// [saveMode] 为 true 时进入保存流程,否则为打开流程;[suffix] 决定文件过滤
/// 与保存时自动补全的后缀;[defaultName] 为保存模式的默认文件名。
class FileBrowserDialog extends StatefulWidget {
const FileBrowserDialog({
super.key,
required this.saveMode,
this.initialPath,
this.defaultName,
this.suffix = '.edc.json',
});
/// 是否为保存模式(true = 另存为,false = 打开)。
final bool saveMode;
/// 初始目录或初始文件路径。
final String? initialPath;
/// 保存模式的默认文件名(如 `装配线节拍.svg`)。
final String? defaultName;
/// 文件后缀:过滤目录列表并自动补全用户输入(如 `.svg` / `.png` / `.edc.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>['.arch.json', '.edc.json', '.seq.json', '.json', '.svg', '.png', '.dxf'];
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;
final String p = e.path.toLowerCase();
// 设计文档同时兼容旧的 .edc.json / .seq.json;其它后缀按后缀精确过滤。
if (widget.suffix.toLowerCase().contains('json')) {
return p.endsWith('.edc.json') ||
p.endsWith('.seq.json') ||
p.endsWith('.arch.json') ||
p.endsWith('.json');
}
return p.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] 决定文件过滤与自动补全的后缀
/// (`.edc.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。
Future<String?> pickFile(
BuildContext context, {
required bool save,
String? initialPath,
String? defaultName,
String suffix = '.edc.json',
}) {
return showDialog<String>(
context: context,
builder: (BuildContext ctx) => FileBrowserDialog(
saveMode: save,
initialPath: initialPath,
defaultName: defaultName,
suffix: suffix,
),
);
}
// ===================== 安卓公共 Documents 文件对话框 =====================
/// 保存位置设置:选择基础目录(文档 / 下载 / 图片)与子文件夹名。
class SaveLocationDialog extends StatefulWidget {
const SaveLocationDialog({super.key});
@override
State<SaveLocationDialog> createState() => _SaveLocationDialogState();
}
class _SaveLocationDialogState extends State<SaveLocationDialog> {
late String _base;
late TextEditingController _folder;
static String zh(String b) => switch (b) {
'downloads' => '下载',
'pictures' => '图片',
_ => '文档',
};
@override
void initState() {
super.initState();
final Map<String, String> s = AndroidDocs.settings();
_base = s['base'] ?? 'documents';
_folder = TextEditingController(text: s['folder'] ?? AndroidDocs.defaultFolder);
}
@override
void dispose() {
_folder.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: const Text('保存位置'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('基础目录', style: TextStyle(color: t.sub, fontSize: 12)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: AndroidDocs.baseOptions.map((String b) {
return ChoiceChip(
label: Text(zh(b)),
selected: _base == b,
onSelected: (_) => setState(() => _base = b),
);
}).toList(),
),
const SizedBox(height: 14),
Text('子文件夹名称', style: TextStyle(color: t.sub, fontSize: 12)),
const SizedBox(height: 8),
TextField(
controller: _folder,
style: TextStyle(color: t.text, fontSize: 12.5),
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
const SizedBox(height: 10),
Text('保存、导出、打开都使用该目录;文件位于「文件管理」可见的公共目录。',
style: TextStyle(color: t.dim, fontSize: 11, height: 1.5)),
],
),
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () async {
await AndroidDocs.saveSettings(_base, _folder.text);
if (context.mounted) Navigator.pop(context);
},
child: const Text('确定'),
),
],
);
}
}
/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/EDC,兼容旧目录 SequenceDiagram)。
///
/// - 保存模式:显示当前保存位置(可点「更改位置」修改),输入文件名自动补全后缀;
/// - 打开模式:列出目录中匹配后缀的文件,点选返回文件名。
/// 返回值为文件名;取消返回 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();
}
/// 列出配置目录中的匹配文件(新在前)。
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 = '无法读取目录:$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>['.arch.json', '.edc.json', '.seq.json', '.json', '.svg', '.png', '.dxf'];
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}';
}
/// 「更改位置」按钮:打开保存位置设置,返回后刷新本对话框。
Future<void> _changeLocation() async {
await showDialog<void>(context: context, builder: (_) => const SaveLocationDialog());
if (!mounted) return;
setState(() {});
if (!widget.saveMode) _load();
}
/// 当前保存位置展示行。
Widget _locationRow(Tokens t) {
return Row(
children: <Widget>[
Icon(Icons.folder_outlined, size: 15, color: t.accent),
const SizedBox(width: 6),
Expanded(
child: Text('保存位置 / ${AndroidDocs.location()} /',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.dim, fontSize: 11)),
),
TextButton(
onPressed: _changeLocation,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 28),
),
child: const Text('更改位置', style: TextStyle(fontSize: 12)),
),
],
);
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: Text(widget.saveMode ? '保存到公共目录' : '从公共目录打开'),
content: SizedBox(
width: 460,
child: widget.saveMode
? Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_locationRow(t),
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>[
_locationRow(t),
const SizedBox(height: 6),
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('目录中暂无 ${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('添加'),
),
],
);
}
}
// ===================== 文档设置对话框 =====================
/// 泳道槽位菜单:把泳道加宽为 1–5 槽(同一泳道并列放置多个动作),或恢复 1 槽。
///
/// 入口:双击条形视图左侧泳道编号区 / 右键空白泳道 / 左侧栏「N 槽」徽标。
/// 加宽后同一泳道的动作按 `Action.row`(槽位)分成多条并排行,
/// 圆周视图与流程图同样按槽位分行 / 分环 / 分列。
Future<void> showLaneSlotMenu(
BuildContext context, AppController controller, Offset global, int lane) async {
final RenderBox box = context.findRenderObject()! as RenderBox;
final Offset pos = box.globalToLocal(global);
final int cur = controller.project.slotsOf(lane);
final String? result = await showMenu<String>(
context: context,
position: RelativeRect.fromLTRB(pos.dx, pos.dy, pos.dx, pos.dy),
items: <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
enabled: false,
height: 34,
child: Text('泳道槽位数(并列动作数)', style: TextStyle(fontSize: 11.5)),
),
for (int i = 1; i <= 5; i++)
PopupMenuItem<String>(
value: '$i',
child: Row(
children: <Widget>[
Text(i == cur ? '✓' : '', style: const TextStyle(fontSize: 12)),
const SizedBox(width: 6),
Text('$i 槽${i == cur ? '(当前)' : ''}'),
],
),
),
],
);
if (result != null) controller.setLaneSlots(lane, int.tryParse(result) ?? 1);
}
/// 文档设置对话框:设置项目名称、时间/相位单位、显示精度、
/// 循环时长、泳道策略、换算表与编辑辅助选项。
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),
// 泳道策略:动作全部移走后,泳道保留还是自动移除。
Text('泳道', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Wrap(
spacing: 10,
children: <Widget>[
FilterChip(
label: const Text('保留空泳道'),
selected: widget.controller.project.keepEmptyLanes,
onSelected: (bool v) {
widget.controller.setKeepEmptyLanes(v);
setState(() {});
},
),
],
),
const SizedBox(height: 6),
Text(
'开启:动作全部移走的泳道保留(条形行 / 圆周环 / 流程列,序号不变);关闭:空泳道自动移除、序号顺延。',
style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5),
),
const SizedBox(height: 18),
// 自动保存:定时把文档写回文件(需已手动保存过一次路径)。
Text('自动保存', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(height: 8),
Wrap(
spacing: 10,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
FilterChip(
label: const Text('启用自动保存'),
selected: widget.controller.project.autoSaveEnabled,
onSelected: (bool v) {
widget.controller.setAutoSave(enabled: v);
setState(() {});
},
),
for (final int m in <int>[1, 5, 10, 30])
ChoiceChip(
label: Text('$m 分钟'),
selected: widget.controller.project.autoSaveMinutes == m,
onSelected: (_) {
widget.controller.setAutoSave(minutes: m);
setState(() {});
},
),
],
),
const SizedBox(height: 6),
Text(
'默认每 10 分钟自动保存一次(可选 1 / 5 / 10 / 30 分钟);需先手动保存过一次(有文件路径)才生效,自动保存会同步更新 .bak 备份。',
style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5),
),
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 ? '删除工位' : '至少保留一个工位',
),
],
),
);
}
}
// ===================== 帮助中心对话框 =====================
/// 帮助中心对话框:以四个标签页展示快速开始、快捷键、
/// 双视图说明以及单位与导出等信息。
/// 软件设置:集中设置入口(外观 / 文档默认 / 架构图网格 / 更新)。
///
/// 从左上角「EDC|易得」菜单底部的「软件设置」打开;文档级的完整设置
/// (单位 / 循环 / 相位等)仍在「文档设置」(F2 / 左侧栏)里。
class SoftwareSettingsDialog extends StatefulWidget {
/// 构造软件设置对话框。
const SoftwareSettingsDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
/// 创建状态对象。
@override
State<SoftwareSettingsDialog> createState() => _SoftwareSettingsDialogState();
}
/// 软件设置对话框状态。
class _SoftwareSettingsDialogState extends State<SoftwareSettingsDialog> {
/// 控制器快捷访问。
AppController get c => widget.controller;
/// 检查更新:发现新版本直接弹更新对话框。
Future<void> _checkUpdate() async {
c.setStatus('正在检查更新…');
try {
final UpdateInfo? info = await UpdateService.check();
if (!mounted) return;
if (info == null) {
c.setStatus('已是最新版本(v$kAppVersion)');
await showMessage(context, '检查更新', '当前已是最新版本(v$kAppVersion)。');
return;
}
await showDialog<void>(
context: context,
// 点对话框外灰色区域不关闭(下载中防误触退出)。
barrierDismissible: false,
builder: (_) => UpdateDialog(controller: c, info: info),
);
} catch (e) {
if (mounted) await showMessage(context, '检查更新失败', '$e');
}
}
/// 渲染设置表单。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
680,
600,
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 Spacer(),
Text('v$kAppVersion', style: TextStyle(fontSize: 11, color: t.dim)),
],
),
const Divider(height: 24),
Expanded(
child: ListView(
children: <Widget>[
_section(t, '外观'),
Row(
children: <Widget>[
Expanded(
child: _optCard(
t,
active: c.brightness == Brightness.light,
title: '浅色主题',
subtitle: '白底 · 打印 / 工艺卡友好',
onTap: () => c.setTheme(Brightness.light),
),
),
const SizedBox(width: 10),
Expanded(
child: _optCard(
t,
active: c.brightness == Brightness.dark,
title: '深色主题',
subtitle: '暗光环境护眼',
onTap: () => c.setTheme(Brightness.dark),
),
),
],
),
const SizedBox(height: 18),
_section(t, '文档默认'),
_rowSwitch(
t,
'保留空泳道',
'动作全部移走的泳道保留(序号不变;关闭则自动移除)',
c.project.keepEmptyLanes,
(bool v) => c.setKeepEmptyLanes(v),
),
_rowSwitch(
t,
'自动保存',
'保存过一次路径后按间隔写回文件(同步 .bak 备份)',
c.project.autoSaveEnabled,
(bool v) => c.setAutoSave(enabled: v),
),
if (c.project.autoSaveEnabled)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: <Widget>[
Text('间隔', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 10),
for (final int m in <int>[1, 5, 10, 30])
Padding(
padding: const EdgeInsets.only(right: 6),
child: _chip(
t,
'$m 分钟',
c.project.autoSaveMinutes == m,
() => c.setAutoSave(minutes: m),
),
),
],
),
),
const SizedBox(height: 10),
_section(t, '架构图网格'),
_rowSwitch(
t,
'吸附网格',
'识别 / 移动 / 缩放优先对位到网格',
c.arch.gridSnap,
(bool v) => c.setArchGrid(snap: v),
),
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: <Widget>[
Text('粒度', style: TextStyle(color: t.sub, fontSize: 11)),
const SizedBox(width: 10),
for (final double g in <double>[10, 20, 40, 80])
Padding(
padding: const EdgeInsets.only(right: 6),
child: _chip(
t,
'${g.round()} px',
c.arch.gridSize == g,
() => c.setArchGrid(size: g),
),
),
],
),
),
const SizedBox(height: 18),
_section(t, '更新'),
Row(
children: <Widget>[
Expanded(
child: Text('当前版本 v$kAppVersion;检查到新版本可直接升级。',
style: TextStyle(color: t.dim, fontSize: 11)),
),
OutlinedButton(
onPressed: _checkUpdate,
child: const Text('检查更新'),
),
],
),
],
),
),
const Divider(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FilledButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('完成'),
),
],
),
],
),
),
),
);
}
/// 小节标题。
Widget _section(Tokens t, String s) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
s,
style: TextStyle(
color: t.text2,
fontSize: 12.5,
fontWeight: FontWeight.w700,
),
),
);
/// 选项卡片(主题等二选一)。
Widget _optCard(
Tokens t, {
required bool active,
required String title,
required String subtitle,
required VoidCallback onTap,
}) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.14) : t.panel2,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: active ? t.accent : t.line,
width: active ? 1.3 : 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
style: TextStyle(
color: active ? t.accent : t.text,
fontSize: 12.5,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(subtitle, style: TextStyle(color: t.dim, fontSize: 10.5)),
],
),
),
);
}
/// 开关行。
Widget _rowSwitch(
Tokens t,
String title,
String desc,
bool value,
ValueChanged<bool> onChanged,
) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(title,
style: TextStyle(
color: t.text, fontSize: 12, fontWeight: FontWeight.w600)),
Text(desc,
style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.4)),
],
),
),
Switch(
value: value,
onChanged: onChanged,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
],
),
);
}
/// 粒度 / 间隔小圆片。
Widget _chip(Tokens t, String label, bool active, VoidCallback onTap) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(7),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 4),
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.16) : t.panel2,
borderRadius: BorderRadius.circular(7),
border: Border.all(color: active ? t.accent : t.line),
),
child: Text(
label,
style: TextStyle(
color: active ? t.accent : t.sub,
fontSize: 10.5,
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
),
),
),
);
}
}
/// 通用文本编辑对话框(图形文字 / 连线标签共用)。
///
/// 返回新文本;取消返回 null。
/// 「打开文档…」的文档类型选择:列出全部模块(未开放灰显不可选)。
///
/// 返回所选模块;用户取消返回 null。
Future<EdcModule?> showDocumentTypeDialog(BuildContext context) async {
return showDialog<EdcModule>(
context: context,
builder: (BuildContext ctx) {
final Tokens t = ctx.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: Text('打开文档',
style: TextStyle(
color: t.text, fontSize: 15, fontWeight: FontWeight.w700)),
content: SizedBox(
width: 400,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
for (final EdcModule m in kModules)
InkWell(
onTap: m.available ? () => Navigator.pop(ctx, m) : null,
borderRadius: BorderRadius.circular(9),
child: Opacity(
opacity: m.available ? 1 : 0.5,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 8),
child: Row(
children: <Widget>[
Container(
width: 30,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Color(m.accent).withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8),
),
child:
Icon(m.icon, size: 17, color: Color(m.accent)),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(m.name,
style: TextStyle(
color: t.text,
fontSize: 12.5,
fontWeight: FontWeight.w600,
)),
Text(
'文档后缀 ${m.suffix}'
'${m.available ? '' : ' · 未开放'}',
style: TextStyle(
color: t.dim, fontSize: 10.5),
),
],
),
),
],
),
),
),
),
],
),
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
],
);
},
);
}
Future<String?> showTextEditDialog(
BuildContext context, {
required String title,
required String initial,
}) async {
final TextEditingController ctrl = TextEditingController(text: initial);
final String? result = await showDialog<String>(
context: context,
builder: (BuildContext ctx) {
final Tokens t = ctx.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: Text(title,
style: TextStyle(
color: t.text, fontSize: 15, fontWeight: FontWeight.w700)),
content: SizedBox(
width: 380,
child: TextField(
controller: ctrl,
autofocus: true,
minLines: 1,
maxLines: 4,
style: TextStyle(color: t.text, fontSize: 13),
decoration: InputDecoration(
hintText: '输入文字(可多行)',
hintStyle: TextStyle(color: t.dim, fontSize: 12),
filled: true,
fillColor: t.panel2,
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
onSubmitted: (String v) => Navigator.of(ctx).pop(v),
),
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(ctx).pop(), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(ctrl.text),
child: const Text('确定')),
],
);
},
);
// 等对话框退场动画结束后再释放输入控制器(动画期间组件仍会引用它)。
Future<void>.delayed(const Duration(milliseconds: 400), ctrl.dispose);
return result;
}
class HelpDialog extends StatefulWidget {
/// 构造帮助中心(左侧垂直导航 + 右侧内容,不再水平滑动)。
const HelpDialog({super.key});
/// 创建状态。
@override
State<HelpDialog> createState() => _HelpDialogState();
}
/// 帮助中心状态:记录当前分页(左侧垂直导航索引)。
class _HelpDialogState extends State<HelpDialog> {
int _tab = 0;
/// 分页标题(与内容顺序一致)。
static const List<String> _tabs = <String>[
'首页与模块',
'时序图 · 动作',
'时序图 · 视图导出',
'架构图 · 绘制识别',
'架构图 · 编辑导出',
'界面与快捷键',
'关于',
];
/// 左侧垂直导航条目。
Widget _navItem(Tokens t, int index, String label) {
final bool active = _tab == index;
return InkWell(
onTap: () => setState(() => _tab = index),
borderRadius: BorderRadius.circular(8),
child: Container(
margin: const EdgeInsets.only(bottom: 6),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: active
? t.accent.withValues(alpha: 0.14)
: Colors.transparent,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: active ? t.accent : Colors.transparent,
),
),
child: Row(
children: <Widget>[
Icon(
active ? Icons.chevron_right : Icons.circle,
size: active ? 15 : 6,
color: active ? t.accent : t.dim,
),
const SizedBox(width: 8),
Expanded(
child: Text(
label,
style: TextStyle(
color: active ? t.accent : t.sub,
fontSize: 12,
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
),
),
),
],
),
),
);
}
/// 渲染帮助中心:左侧分页导航 + 右侧内容(垂直滚动)。
@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: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// 左侧:垂直导航(窄栏,内容过高时纵向滚动)。
SizedBox(
width: 150,
child: ListView(
children: <Widget>[
for (int i = 0; i < _tabs.length; i++)
_navItem(t, i, _tabs[i]),
],
),
),
const SizedBox(width: 12),
Container(width: 1, color: t.line2),
const SizedBox(width: 12),
// 右侧:当前分页内容。
// 每个分页自身就是可滚动列表(_section 返回 ListView),
// 这里不能再套 SingleChildScrollView——无界高度会把内容撑空。
Expanded(
child: IndexedStack(
index: _tab,
children: <Widget>[
// 目标:从首页进入正确模块、理解文档与数据位置。
_section(t, <List<String>>[
<String>['打开软件是空白首页', '软件采用「空白启动」:打开后进入首页(不再直接进时序图)。在首页选择要新建的文档类型,或打开已有文档。'],
<String>['六个设计模块', '首页与左上角品牌菜单一次列全:架构图、时序图已开放;电器原理图、IO 表、拓扑图、PID 图灰显「未开放」(暂不可进入)。'],
<String>['新建 / 打开 / 最近', '首页点模块卡片即新建对应文档;「打开文档…」先选类型再选文件;「最近打开」记录最近文件(可单条删除 / 清空)。'],
<String>['切换模块 / 回首页', '左上角 logo 按钮 → 品牌菜单:首页、架构图设计、时序图设计、软件设置。切换模块前如有未保存修改会先确认。'],
<String>['文档格式', '时序图保存为 *.seq.json(只含时序内容);架构图保存为 *.arch.json(只含架构内容);旧版 .edc.json 文件可继续打开。'],
<String>['数据保存在哪里', '桌面:%APPDATA%/EDC(autosave 快照、recent 最近列表、library 素材库;旧目录自动复制迁移)。安卓:公共目录 Documents/EDC(兼容旧目录读取)。'],
]),
// 目标:搭建时序方案、增删改动作与工位(沿用既有说明)。
_section(t, <List<String>>[
<String>['我要新建方案', '顶部「新建」创建空白时序设计;「打开」按时序 / 架构模块分别载入 .seq.json / .arch.json(兼容旧版 .edc.json)。'],
<String>['我要先看看示例', '首次启动载入 5 个动作的示例节拍(装配线节拍),可直接修改。'],
<String>['我要新增动作', '双击画布空白处在点击相位新增;或左侧「新建」在 0° 新增(默认最外层)。'],
<String>['我要删除动作', '选中后:左侧「删除」/ 行内删除图标 / Delete 键 / 右键菜单;至少保留一个动作 / 泳道。'],
<String>['我要改动作属性', '双击画布色块(条形块 / 圆弧)或左侧动作行 → 打开动作编辑对话框;也可选中后点左侧行内编辑图标。'],
<String>['我要编辑工位', '左侧「文档设置」→「编辑工位」:可增删工位、改名称与颜色、上下调整顺序;删除工位后其动作自动改挂到第一个工位。'],
<String>['我要改时间轴长度', '左侧「文档设置」入口(或按 F2)→「循环与相位」→ 循环时长 → 应用。'],
<String>['我要调相位 / 时长', '拖动动作块平移相位;拖条形右端改持续角;圆周视图拖弧两端改起止角;右侧滑杆可精调。'],
<String>['泳道加宽(并列动作)', '双击条形视图左侧泳道编号(或点左侧栏「N 槽」徽标)→ 选 1–5 槽;拖拽动作可同时换道 + 换槽位。'],
<String>['空泳道的保留 / 移除', 'F2 文档设置 →「泳道」→ 保留空泳道(默认开):动作全部移走的泳道保留,序号不变;关闭则自动移除。'],
<String>['我要加前置依赖(输入)', '右侧「前置依赖 · 输入」→「添加前置依赖」;或右键动作 →「添加依赖」。FS 绿色实线=完成后启动;SS 琥珀虚线=可提前启动(带 +n°)。'],
<String>['连线重叠怎么办', '点选连线后拖动可沿法线方向平移整条线(圆周沿半径方向);双击连线或右键「复位走线偏移」恢复;同一组连线会自动错开。'],
<String>['我要编辑相位分区', '左侧「文档设置」→「编辑相位分区」;增删分区、改名称与起止角;可重叠、可留空、>360° 表示跨圈。'],
]),
// 目标:视图操作、AI 生成与三视图导出(沿用既有说明)。
_section(t, <List<String>>[
<String>['我要切换视图', '顶部「条形节拍 / 圆周节拍 / 流程图」分段开关,三种视图共享同一份数据;流程图由时序图自动生成(只读)。每次切换都会自动「适应窗口」。'],
<String>['我要缩放 / 平移', 'Ctrl+滚轮 以光标为锚点缩放;普通滚轮或拖拽空白平移。'],
<String>['我要完整显示', '顶部「适应视图」:自动按内容(含刻度、箭头、跨圈标注)计算缩放与居中。'],
<String>['我要开关标注', '左侧「显示选项」逐项开关双刻度、依赖箭头、圆环背景、层标注、跨循环高亮等。'],
<String>['我要 AI 生成', '顶部「AI 生成」→ 填 DeepSeek API Key → 选模型(Flash / Pro)→ 选强度(高 / 最高)→ 用自然语言描述 → 生成。'],
<String>['我要看节拍统计', '画布左下角「节拍统计」按钮 → 弹窗查看循环周期、动作数、关键路径、最大并行度、相位覆盖率与瓶颈工位。'],
<String>['我要导出 SVG / PNG', '顶部「导出」下拉菜单:SVG(矢量、分层、带语义 id)/ PNG(2 倍像素位图);三种视图通用。'],
<String>['我要导出 drawio', '流程图视图专用:顶部「导出」→「导出 drawio」,输出 diagrams.net(draw.io)可继续编辑的工程文件。'],
<String>['我要保存 / 恢复', '「保存」写入 .seq.json 并生成 .bak;每 5 秒自动快照(异常退出可恢复);「软件设置」中可开启「自动保存」(默认每 10 分钟一次,需先手动保存过一次路径)。'],
]),
// 目标:架构图的绘制、识别与图元库(本轮重点)。
_section(t, <List<String>>[
<String>['工具条怎么用', '架构图顶部工具:选择 / 手绘 / 连线 / 橡皮,旁边是「识别 N」确认按钮(N = 待识别墨迹笔数)。'],
<String>['手绘识别', '「手绘」工具下按住拖动:松手自动把笔迹扶正为标准图形(矩形 / 圆 / 箭头 / 折线 / 曲线 / 云 / 圆柱……);识别不了的保留为墨迹,可用橡皮擦掉。'],
<String>['多笔组合识别', '支持两笔组合(如两笔试画一个矩形)、圆柱拼接(顶盖 + 柱体);与上一笔刚生成的图形也能在 2.5 秒内合并。'],
<String>['平板手写总识别不准', '左栏「手绘识别」关闭「松手自动识别」(安卓默认关闭):笔迹先保留为墨迹,画完点顶部「识别(N)」按钮统一确认,识别更从容。'],
<String>['图形库', '左栏「图形库」内置标准图形(矩形 / 圆角矩形 / 椭圆 / 圆 / 三角 / 菱形 / 六边形 / 圆柱 / 云)与 IT 图元(服务器 / 客户端 / 移动端 / 防火墙 / 交换机 / 消息队列),点一下即插入画布。'],
<String>['橡皮', '「橡皮」工具:拖过图形 / 墨迹 / 连线即擦除;一次连续擦除算一步撤销(Ctrl+Z 可整段回退)。'],
<String>['文字怎么输入', '双击图形 → 编辑图形文字;双击连线 → 编辑标签;双击空白 → 新建文本(输入法直接打字)。'],
<String>['图层', '左栏「图层」:新建 / 可见(眼睛)/ 锁定(锁)/ 颜色 / 双击改名。隐藏图层不绘制不可选;锁定图层可见但不可选(仍可作吸附参照)。'],
<String>['标尺与辅助', '四边标尺单位固定为 mm(垂直轴数值在右侧);F8 正交移动 / F10 极轴追踪(角度在左栏设置);支持网格吸附与磁力对齐线。'],
<String>['默认图纸', '新建架构图的画布为 A0 图纸(1189×841 mm,1 世界单位 = 1 mm),自动适配视口;画布上绘制浅色 A0 边界。'],
]),
// 目标:架构图编辑操作与导出。
_section(t, <List<String>>[
<String>['连线规则', '连线一律正交(横平竖直):两端垂直出入图元边框(箭头不会乱指),同一图元多条连线自动错开;选中后可拖端点换吸附、拖折点或线段平移走线(平板已加大命中范围),拖动时有磁力对齐与虚线导引;鼠标悬停连线显示抓取光标。'],
<String>['对齐 / 均布', '框选或 Ctrl 多选后,右栏出现 8 个对齐按钮:左 / 横向居中 / 右、顶 / 纵向居中 / 底、横向均布、纵向均布(以选中范围为参照,均布需 ≥3 个)。'],
<String>['层级 / 复制 / 删除', '选中后右栏可「上移一层 / 下移一层」;拖拽移动、白色手柄缩放;Delete 删除选中;Ctrl+A 全选。'],
<String>['我要导出 DXF', '顶部「导出」→「导出 DXF」:AutoCAD R12 格式(图层 / 图形 / 连线 / 文字),可直接在 AutoCAD / DraftSight / ZWCAD 打开继续编辑。'],
<String>['我要导出 SVG / PNG', '顶部「导出」→ SVG(矢量)/ PNG(位图);导出使用纯白背景,与屏幕主题无关。'],
<String>['我要保存 / 恢复', '「保存」写入 .arch.json 并生成 .bak;自动快照与「自动保存」设置与时序图通用。'],
]),
// 目标:调整界面与使用快捷键。
_section(t, <List<String>>[
<String>['我要隐藏 / 显示侧栏', '工具栏右侧两个侧栏按钮,分别控制左、右侧栏;图钉可钉住侧栏(固定占位)或悬浮(鼠标移开自动收起)。'],
if (Platform.isAndroid)
<String>['触屏操作', '单指点选;按住拖动移动 / 手绘 / 擦除;双指捏合缩放、双指拖拽平移;长按空白进入框选。']
else
<String>['拖拽 / 缩放', '左键拖拽移动或绘制;Ctrl+滚轮缩放;中键 / 右键拖拽平移。'],
<String>['撤销 / 保存', 'Ctrl+Z / Ctrl+Y 撤销重做;Ctrl+S 保存;Ctrl+O / Ctrl+N 打开 / 新建;Delete 删除选中。'],
<String>['功能键', 'F1 帮助(本窗口);F2 文档设置(时序图:单位 / 循环 / 泳道 / 相位分区);F3 切换深 / 浅主题。'],
<String>['检查更新', '首页右上角更新图标,或帮助 / 设置中「检查更新」:检测到新版本可直接下载升级(下载限速 320KB/s)。'],
]),
// 关于:设计人、版本、版权、授权信息与本机 MAC。
_about(context, t),
],
),
),
],
),
),
Align(
alignment: Alignment.centerRight,
child: FilledButton(onPressed: () => Navigator.pop(context), child: const Text('关闭')),
),
],
),
),
),
);
}
/// 用系统默认程序打开网址(官网导航)。
///
/// 安卓经原生 Intent 打开浏览器;桌面用 rundll32 / start。
Future<void> _openUrl(String url) async {
if (AndroidDocs.isAvailable) {
await AndroidDocs.openUrl(url);
return;
}
try {
await Process.run('rundll32', <String>['url.dll,FileProtocolHandler', url]);
} catch (_) {
try {
await Process.run('cmd', <String>['/c', 'start', '', url], runInShell: true);
} catch (_) {}
}
}
/// 「关于」页:软件信息 + 平台 / 授权状态 + 官网入口;
/// Windows 版追加授权指南(MAC 申请 .lic),安卓版展示免授权与保存位置说明。
Widget _about(BuildContext context, Tokens t) {
final bool android = AndroidDocs.isAvailable;
final LicenseInfo info = LicenseService.instance.info;
final String lic = !kLicenseRequired
? '已开放(临时免授权)'
: (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(
children: <Widget>[
const AppLogo(size: 48),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('EDC|易得 · Easy Design Collection',
style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)),
const SizedBox(height: 4),
Text('V$kAppVersion(${android ? '安卓版' : 'Windows 版'})',
style: TextStyle(color: t.dim, fontSize: 12)),
],
),
),
],
),
const SizedBox(height: 14),
row('设计人', '呆头鹅'),
row(
'授权状态',
!kLicenseRequired ? '开放授权版本' : (android ? '已授权(安卓版免授权)' : lic),
vc: (android || !kLicenseRequired || info.valid) ? t.ok : t.danger,
),
if (!android)
// 注意:绝不能展示「期望授权串」——它等同于 .lic 内容,公开即可被绕过授权。
row('本机 MAC', info.mac ?? '读取失败'),
row('版权声明', 'Copyright © 2026 EDC(Easy Design Collection)呆头鹅。保留所有权利。'),
row('产品简介', '设计合集(Easy Design Collection):时序图设计面向 PLC 流程节拍 / '
'相位角设计(条形 / 圆周 / 流程图三视图、FS / SS 依赖与关键路径、泳道加宽);'
'架构图设计支持手绘识别标准图形、正交连线与标签;支持导出 SVG / PNG / drawio。'),
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.groups_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('开发者邮箱:liuyu65@126.com'),
guideLine('设计交流群:添加开发者微信 online-goose,加入「设计与制造业设计交流群」。'),
guideLine('官网:sincos.cc'),
],
),
),
const SizedBox(height: 10),
if (android)
// 安卓版说明:免授权 + 保存位置。
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.android, 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('本版面向应用商店分发,无需授权,全部功能可用。'),
guideLine('保存 / 导出文件位于「文件管理」可见的公共目录(默认 Documents/EDC,'
'可在保存对话框中更改位置)。'),
],
),
),
],
);
}
/// 渲染帮助中的一个条目列表,每行左侧为标题、右侧为说明。
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(),
);
}
}