// 应用外壳:组织工具栏、左右可停靠侧栏、画布舞台与状态栏的整体布局, // 并集中处理文件、导出、快捷键与侧栏停靠等交互。 // // 架构位置:位于 UI 层顶层(由 main.dart 的根组件加载),向下装配 // CanvasView / CanvasOverlays / 各类对话框,并通过 AppController 读写 // 项目状态。本文件重点包含: // · 全局快捷键绑定(撤销/重做/保存/打开/新建/删除/帮助等); // · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机; // · 自适应/紧凑工具栏布局(按可用宽度切换); // · 文件打开/保存/另存为与 SVG、PNG 导出流程。 import 'dart:io'; import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/material.dart' hide Action; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import '../export/svg_writer.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; import 'ai_dialog.dart'; import 'app_logo.dart'; import 'canvas_overlays.dart'; import 'canvas_view.dart'; import 'dialogs.dart'; /// 应用外壳组件:承载主界面布局与文件/侧栏等交互逻辑。 class AppShell extends StatefulWidget { /// 创建应用外壳,[controller] 为全局应用控制器。 const AppShell({super.key, required this.controller}); /// 全局应用控制器。 final AppController controller; /// 创建应用外壳对应的状态对象。 @override State createState() => _AppShellState(); } /// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态, /// 并提供文件操作、导出与快捷键处理。 class _AppShellState extends State { /// 画布舞台的绘制边界 key,用于 PNG 导出时抓取像素。 final GlobalKey _stageKey = GlobalKey(); // ---- 侧栏状态机:可见(visible) × 钉住(pinned) × 悬停(hover) ---- /// 左侧栏是否可见。 bool _leftVisible = true; /// 左侧栏是否钉住(钉住则停靠,不随鼠标移出隐藏)。 bool _leftPinned = true; /// 鼠标是否悬停在左侧栏区域(仅未钉住时用于悬浮展开)。 bool _leftHover = false; /// 右侧栏是否可见。 bool _rightVisible = true; /// 右侧栏是否钉住。 bool _rightPinned = true; /// 鼠标是否悬停在右侧栏区域。 bool _rightHover = false; /// 控制器快捷访问器。 AppController get c => widget.controller; // ---- 由上述三态派生的侧栏呈现方式 ---- /// 左侧栏是否处于停靠(固定)状态。 bool get _leftDocked => _leftVisible && _leftPinned; /// 右侧栏是否处于停靠(固定)状态。 bool get _rightDocked => _rightVisible && _rightPinned; /// 左侧栏是否处于悬浮展开状态。 bool get _leftFloat => _leftVisible && !_leftPinned && _leftHover; /// 右侧栏是否处于悬浮展开状态。 bool get _rightFloat => _rightVisible && !_rightPinned && _rightHover; /// 左侧栏是否收起为贴边轨道。 bool get _leftRail => !_leftDocked && !_leftFloat; /// 右侧栏是否收起为贴边轨道。 bool get _rightRail => !_rightDocked && !_rightFloat; /// 订阅控制器变化以便刷新界面。 @override void initState() { super.initState(); c.addListener(_onChange); } /// 取消订阅并释放资源。 @override void dispose() { c.removeListener(_onChange); super.dispose(); } /// 控制器变化回调:触发重建。 void _onChange() => setState(() {}); // ===================== 文件与导出流程 ===================== /// 新建项目:若当前有未保存修改,先弹窗确认是否放弃。 Future _newProject() async { if (c.dirty) { final bool? ok = await showDialog( context: context, builder: (BuildContext ctx) => AlertDialog( title: const Text('放弃未保存的修改?'), content: const Text('当前项目有未保存的修改,继续将丢失这些修改。'), actions: [ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('继续')), ], ), ); if (ok != true) return; } c.newProject(); } /// 打开项目:选择 .seq.json 文件并解码加载。 Future _open() async { final String? path = await pickFile(context, save: false, initialPath: c.filePath); if (path == null) return; try { final String src = await File(path).readAsString(); c.loadProject(Project.decode(src), path: path); } catch (e) { if (mounted) await showMessage(context, '打开失败', '$e'); } } /// 保存项目:已有路径则直接保存,否则转入“另存为”。 Future _save() async { if (c.filePath != null) { await c.save(); return; } await _saveAs(); } /// 另存为:选择目标路径后写入文件(同时生成 .bak 备份)。 Future _saveAs() async { final String? path = await pickFile(context, save: true, initialPath: c.filePath); if (path == null) return; try { await c.saveAs(path); if (mounted) c.setStatus('已保存 ${path.split(RegExp(r'[\\/]')).last}(含 .bak 备份)'); } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } } /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 Future _exportSvg() async { final String? path = await pickFile(context, save: true, initialPath: c.filePath); if (path == null) return; final String svgPath = path.replaceAll(RegExp(r'\.json$'), '.svg'); try { final String svg = SvgWriter( project: c.project, tokens: Tokens.of(c.brightness), mode: c.project.viewState.mode, ).build(); await File(svgPath).writeAsString(svg, flush: true); if (mounted) c.setStatus('已导出 $svgPath'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出 PNG:把画布舞台的 [RenderRepaintBoundary] 以 2 倍像素比 /// 渲染为位图并写入文件。 Future _exportPng() async { final String? path = await pickFile(context, save: true, initialPath: c.filePath); if (path == null) return; final String pngPath = path.replaceAll(RegExp(r'\.(json|svg)$'), '.png'); try { // 抓取画布舞台的渲染对象并转换为图像。 final RenderRepaintBoundary boundary = _stageKey.currentContext!.findRenderObject()! as RenderRepaintBoundary; final ui.Image image = await boundary.toImage(pixelRatio: 2); final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png); await File(pngPath).writeAsBytes(data!.buffer.asUint8List(), flush: true); if (mounted) c.setStatus('已导出 $pngPath'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } // ===================== 主界面构建 ===================== /// 构建主界面:绑定全局快捷键,按“工具栏 / 中部(侧栏 + 画布) / 状态栏” /// 三段式纵向布局组织界面。 @override Widget build(BuildContext context) { final Tokens t = context.tok; // 全局快捷键绑定:编辑、文件、帮助、主题等。 return CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.keyZ, control: true): c.undo, const SingleActivator(LogicalKeyboardKey.keyY, control: true): c.redo, const SingleActivator(LogicalKeyboardKey.keyS, control: true): _save, const SingleActivator(LogicalKeyboardKey.keyO, control: true): _open, const SingleActivator(LogicalKeyboardKey.keyN, control: true): _newProject, const SingleActivator(LogicalKeyboardKey.delete): () { if (c.selectedId != null) c.deleteAction(c.selectedId!); }, const SingleActivator(LogicalKeyboardKey.f1): () => showDialog(context: context, builder: (_) => const HelpDialog()), const SingleActivator(LogicalKeyboardKey.f2): () => showDialog(context: context, builder: (_) => SettingsDialog(controller: c)), const SingleActivator(LogicalKeyboardKey.f3): c.toggleTheme, }, child: Focus( autofocus: true, child: Scaffold( backgroundColor: t.bg, body: Column( children: [ // 顶部:自适应工具栏。 _toolbar(t), Expanded( child: Row( // 拉伸交叉轴:保证左右侧栏始终从工具栏一直贯通到底部状态栏。 crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // 左侧栏:仅在停靠状态占用布局宽度。 if (_leftDocked) _leftPanel(t), Expanded( // 画布舞台:可绘制区域,叠加画布视图与浮层。 child: Stack( children: [ Positioned.fill( child: RepaintBoundary( key: _stageKey, child: Stack( children: [ // 底层:可交互的画布。 Positioned.fill( child: Container(color: t.canvas2, child: CanvasView(controller: c)), ), // 上层:信息浮层。 Positioned.fill( child: CanvasOverlays( controller: c, // 侧栏收起时让浮层避开边缘把手。 leftInset: _leftRail ? 22 : 0, rightInset: _rightRail ? 22 : 0, ), ), ], ), ), ), // 收起状态:贴边轨道(悬停可展开为悬浮面板)。 if (_leftRail) Positioned(left: 0, top: 0, bottom: 0, child: _rail(t, true)), if (_rightRail) Positioned(right: 0, top: 0, bottom: 0, child: _rail(t, false)), // 悬浮状态:覆盖在画布上的可浮动侧栏。 if (_leftFloat) Positioned(left: 0, top: 0, bottom: 0, child: _floating(t, true)), if (_rightFloat) Positioned(right: 0, top: 0, bottom: 0, child: _floating(t, false)), ], ), ), // 右侧栏:仅在停靠状态占用布局宽度。 if (_rightDocked) _rightPanel(t), ], ), ), // 底部:状态栏。 _statusBar(t), ], ), ), ), ); } // ===================== 工具栏(自适应 / 紧凑) ===================== /// 构建顶部工具栏:左侧为品牌与文件/编辑操作,右侧为导出、缩放、 /// 单位、侧栏开关与主题切换。根据可用宽度在完整布局与紧凑布局间切换。 Widget _toolbar(Tokens t) { final bool dirty = c.dirty; final String fileLabel = c.filePath == null ? '文件:未保存(内存中)' : '文件:${c.filePath!.split(RegExp(r'[\\/]')).last}'; final Widget fileChip = Container( height: 34, padding: const EdgeInsets.symmetric(horizontal: 12), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(9), border: Border.all(color: t.line2), ), child: Row( children: [ Text(fileLabel, style: TextStyle(color: t.sub, fontSize: 11)), const SizedBox(width: 10), Container(width: 7, height: 7, decoration: BoxDecoration(color: dirty ? t.warn : t.ok, shape: BoxShape.circle)), const SizedBox(width: 6), Text(dirty ? '未保存' : '已保存', style: TextStyle(color: dirty ? t.warn : t.ok, fontSize: 11)), ], ), ); return Container( height: 54, padding: const EdgeInsets.symmetric(horizontal: 6), decoration: BoxDecoration( color: t.chrome, border: Border(bottom: BorderSide(color: t.line2)), ), child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints cons) { // 响应式断点:宽于 1760 用完整布局;否则用紧凑布局, // 保证在 1920×1080(含 150% 缩放下的 1280 逻辑宽度)也能全部显示。 final bool compact = cons.maxWidth < 1760; // 侧栏开关(两种布局共用)。 final Widget sideToggleLeft = _iconBtn(t, Icons.view_sidebar_outlined, () => setState(() { if (_leftVisible) { _leftVisible = false; _leftHover = false; } else { _leftVisible = true; if (!_leftPinned) _leftHover = true; } }), tooltip: '显示 / 隐藏左侧栏'); final Widget sideToggleRight = Transform( alignment: Alignment.center, transform: Matrix4.diagonal3Values(-1.0, 1.0, 1.0), child: _iconBtn(t, Icons.view_sidebar_outlined, () => setState(() { if (_rightVisible) { _rightVisible = false; _rightHover = false; } else { _rightVisible = true; if (!_rightPinned) _rightHover = true; } }), tooltip: '显示 / 隐藏右侧栏'), ); final List left; final List right; if (!compact) { // 完整布局:文字按钮 + 文件状态胶囊。 left = [ const AppLogo(size: 32), const SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('时序图设计器', style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w700, letterSpacing: 1)), Text('Sequence Diagram Studio', style: TextStyle(color: t.dim, fontSize: 10)), ], ), const SizedBox(width: 18), _ghost(t, '新建', _newProject), _ghost(t, '打开', _open), _ghost(t, '保存', _save), const SizedBox(width: 6), _ghost(t, '撤销', c.canUndo ? c.undo : null, icon: Icons.undo), _ghost(t, '重做', c.canRedo ? c.redo : null, icon: Icons.redo), const SizedBox(width: 6), _addBtn(t, '添加动作', () => c.addAction(startAngle: 0)), _toggleBtn(t, '编辑', Icons.edit, () { final Action? a = c.selected; if (a != null) { showDialog(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)); } }), _aiBtn(t), const SizedBox(width: 12), _segmented(t), ]; right = [ _primaryBtn(t, '导出 SVG', _exportSvg), const SizedBox(width: 6), _ghost(t, '导出 PNG', _exportPng), const SizedBox(width: 6), _zoomBox(t), const SizedBox(width: 6), _ghost(t, '适应视图', c.fitView), const SizedBox(width: 8), _unitDropdown(t), const SizedBox(width: 8), fileChip, const SizedBox(width: 8), sideToggleLeft, sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), _themeToggle(t), ]; } else { // 紧凑布局:图标化 + 导出合并为菜单,尽量压缩宽度。 left = [ const AppLogo(size: 28), const SizedBox(width: 8), Text('时序图设计器', style: TextStyle(color: t.text, fontSize: 13, fontWeight: FontWeight.w700, letterSpacing: 0.5)), const SizedBox(width: 8), _iconBtn(t, Icons.note_add_outlined, _newProject, tooltip: '新建 Ctrl+N'), _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), const SizedBox(width: 4), _iconBtn(t, Icons.undo, c.canUndo ? c.undo : null, tooltip: '撤销 Ctrl+Z'), _iconBtn(t, Icons.redo, c.canRedo ? c.redo : null, tooltip: '重做 Ctrl+Y'), const SizedBox(width: 4), _iconBtn(t, Icons.add_circle_outline, () => c.addAction(startAngle: 0), tooltip: '添加动作', color: t.ok), _iconBtn(t, Icons.edit, () { final Action? a = c.selected; if (a != null) { showDialog(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)); } }, tooltip: '编辑', color: t.accent), // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 _aiBtn(t), const SizedBox(width: 8), _segmented(t, compact: true), ]; right = [ // 导出保持两个独立按钮(不用合并菜单,便于一眼识别)。 _ghost(t, '导出 SVG', _exportSvg), const SizedBox(width: 4), _ghost(t, '导出 PNG', _exportPng), const SizedBox(width: 4), _zoomBox(t), _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), _unitDropdown(t), sideToggleLeft, sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), _themeToggle(t), ]; } // 用「最小宽度 = 视口宽度」约束让内容铺满整条工具栏: // 空间足够时 Spacer 把右侧工具组顶到最右(不再留空白); // 空间不足时横向滚动,避免溢出。 return SingleChildScrollView( scrollDirection: Axis.horizontal, child: ConstrainedBox( constraints: BoxConstraints(minWidth: cons.maxWidth), child: IntrinsicWidth( child: Row(children: [...left, const Spacer(), ...right]), ), ), ); }, ), ); } /// 视图模式分段控件:条形节拍 / 圆周节拍一键切换。 /// /// [compact] 为真时使用更窄的宽度,适配 1920×1080 等较小窗口。 Widget _segmented(Tokens t, {bool compact = false}) { final bool bar = c.project.viewState.mode == ViewMode.bar; Widget seg(String label, bool active, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), child: Container( width: compact ? 96 : 140, height: 34, alignment: Alignment.center, decoration: BoxDecoration( color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent, borderRadius: BorderRadius.circular(10), border: active ? Border.all(color: t.accent, width: 1.4) : null, ), child: Text(label, style: TextStyle( color: active ? t.accent : t.sub, fontWeight: active ? FontWeight.w600 : FontWeight.normal, fontSize: 12, )), ), ); } return Container( padding: const EdgeInsets.all(3), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line2), ), child: Row( children: [ seg('条形节拍', bar, () => c.setViewMode(ViewMode.bar)), seg('圆周节拍', !bar, () => c.setViewMode(ViewMode.circular)), ], ), ); } /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮。 Widget _zoomBox(Tokens t) { return Container( height: 34, padding: const EdgeInsets.symmetric(horizontal: 4), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(9), border: Border.all(color: t.line2), ), child: Row( children: [ _miniIcon(t, Icons.remove, () => c.zoomBy(0.9)), SizedBox( width: 52, child: Text('${(c.project.viewState.zoom * 100).round()}%', textAlign: TextAlign.center, style: TextStyle(color: t.text, fontSize: 11)), ), _miniIcon(t, Icons.add, () => c.zoomBy(1.1)), ], ), ); } /// 缩放控件内的小图标按钮。 Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(6), child: Padding( padding: const EdgeInsets.all(6), child: Icon(icon, size: 15, color: t.sub), ), ); } /// 时间单位下拉框:切换 ms / s / min。 Widget _unitDropdown(Tokens t) { return Container( height: 34, padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(9), border: Border.all(color: t.accent, width: 1.2), ), child: DropdownButton( value: c.project.units.timeUnit, underline: const SizedBox.shrink(), dropdownColor: t.dialog, borderRadius: BorderRadius.circular(9), style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600), icon: Icon(Icons.keyboard_arrow_down, color: t.accent, size: 18), items: TimeUnit.values .map((TimeUnit u) => DropdownMenuItem(value: u, child: Text(timeUnitLabel(u)))) .toList(), onChanged: (TimeUnit? u) { if (u != null) c.setUnits(c.project.units.copyWith(timeUnit: u)); }, ), ); } /// 主题切换控件:日间 / 夜间两段式按钮。 Widget _themeToggle(Tokens t) { final bool light = c.brightness == Brightness.light; Widget half(IconData icon, bool active, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(8), child: Container( width: 32, height: 26, alignment: Alignment.center, decoration: BoxDecoration( color: active ? t.accent.withValues(alpha: 0.18) : Colors.transparent, borderRadius: BorderRadius.circular(8), border: active ? Border.all(color: t.accent, width: 1.2) : null, ), child: Icon(icon, size: 16, color: active ? t.accent : t.dim), ), ); } return Container( padding: const EdgeInsets.all(4), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line2), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ half(Icons.wb_sunny_outlined, light, () { if (light) return; c.toggleTheme(); }), half(Icons.nightlight_round, !light, () { if (!light) return; c.toggleTheme(); }), ], ), ); } /// 次要(幽灵)样式按钮;[onTap] 为 null 时呈禁用态。 Widget _ghost(Tokens t, String label, VoidCallback? onTap, {IconData? icon}) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 3), child: TextButton.icon( onPressed: onTap, icon: icon == null ? null : Icon(icon, size: 16, color: onTap == null ? t.dim : t.text), label: Text(label, style: TextStyle(fontSize: 11, color: onTap == null ? t.dim : t.text)), style: TextButton.styleFrom( backgroundColor: t.panel, side: BorderSide(color: t.line2), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), minimumSize: const Size(0, 34), ), ), ); } /// 主强调“添加”按钮(绿色填充)。 Widget _addBtn(Tokens t, String label, VoidCallback onTap) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 3), child: FilledButton.icon( onPressed: onTap, icon: const Icon(Icons.add, size: 17), label: Text(label, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600)), style: FilledButton.styleFrom( backgroundColor: t.ok, foregroundColor: t.onAccent, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), minimumSize: const Size(0, 34), ), ), ); } /// 强调色“编辑”按钮。 Widget _toggleBtn(Tokens t, String label, IconData icon, VoidCallback onTap) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 3), child: FilledButton.icon( onPressed: onTap, icon: Icon(icon, size: 16), label: Text(label, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600)), style: FilledButton.styleFrom( backgroundColor: t.accent, foregroundColor: t.onAccent, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), minimumSize: const Size(0, 34), ), ), ); } /// 主色填充按钮(用于导出等主要动作)。 Widget _primaryBtn(Tokens t, String label, VoidCallback onTap) { return FilledButton( onPressed: onTap, style: FilledButton.styleFrom( backgroundColor: t.accent2, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), minimumSize: const Size(0, 34), ), child: Text(label, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600)), ); } /// AI 生成按钮:打开「自然语言 → 时序图」对话框。 Widget _aiBtn(Tokens t) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 3), child: FilledButton.icon( onPressed: () => showDialog( context: context, builder: (_) => AiGenerateDialog(controller: c), ), icon: const Icon(Icons.auto_awesome, size: 16), label: const Text('AI 生成', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700)), style: FilledButton.styleFrom( backgroundColor: t.accent2, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), minimumSize: const Size(0, 34), tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), ), ); } /// 图标按钮,可附带 tooltip 与自定义颜色;尺寸紧凑以节省工具栏宽度。 Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) { return IconButton( onPressed: onTap, icon: Icon(icon, size: 18, color: onTap == null ? t.dim : (color ?? t.text)), tooltip: tooltip, splashRadius: 16, padding: EdgeInsets.zero, constraints: const BoxConstraints(minWidth: 34, minHeight: 34), ); } // ===================== 侧栏停靠状态机(钉住 / 悬浮 / 轨道) ===================== /// 侧栏标题栏控制按钮:切换钉住状态与隐藏侧栏。 Widget _panelControls(Tokens t, bool left) { final bool pinned = left ? _leftPinned : _rightPinned; return Row( mainAxisSize: MainAxisSize.min, children: [ _headerIcon( t, pinned ? Icons.push_pin : Icons.push_pin_outlined, pinned ? '取消钉住(改为悬浮)' : '钉住侧栏', () => setState(() { if (left) { _leftPinned = !_leftPinned; _leftHover = _leftPinned; } else { _rightPinned = !_rightPinned; _rightHover = _rightPinned; } }), active: pinned, ), _headerIcon( t, Icons.close, '隐藏侧栏', () => setState(() { if (left) { _leftVisible = false; _leftHover = false; } else { _rightVisible = false; _rightHover = false; } }), ), ], ); } /// 侧栏标题栏中的小图标按钮,[active] 控制高亮。 Widget _headerIcon(Tokens t, IconData icon, String tip, VoidCallback onTap, {bool active = false}) { return Tooltip( message: tip, child: InkWell( onTap: onTap, borderRadius: BorderRadius.circular(6), child: Padding( padding: const EdgeInsets.all(4), child: Icon(icon, size: 15, color: active ? t.accent : t.dim), ), ), ); } /// 侧栏收起时的贴边轨道:鼠标进入即展开为悬浮面板,点击亦可展开。 Widget _rail(Tokens t, bool left) { final bool visible = left ? _leftVisible : _rightVisible; final bool pinned = left ? _leftPinned : _rightPinned; return MouseRegion( cursor: SystemMouseCursors.click, onEnter: (_) { if (visible && !pinned) { setState(() { if (left) { _leftHover = true; } else { _rightHover = true; } }); } }, child: GestureDetector( onTap: () => setState(() { if (left) { _leftVisible = true; if (!_leftPinned) _leftHover = true; } else { _rightVisible = true; if (!_rightPinned) _rightHover = true; } }), child: Container( width: 22, decoration: BoxDecoration( color: t.panel.withValues(alpha: 0.96), border: Border( right: left ? BorderSide(color: t.line) : BorderSide.none, left: left ? BorderSide.none : BorderSide(color: t.line), ), ), alignment: Alignment.topCenter, padding: const EdgeInsets.only(top: 14), child: Icon(left ? Icons.chevron_right : Icons.chevron_left, size: 18, color: t.sub), ), ), ); } /// 悬浮侧栏:用 [MouseRegion] 跟踪悬停,鼠标移出即收回为轨道。 Widget _floating(Tokens t, bool left) { return MouseRegion( onEnter: (_) => setState(() { if (left) { _leftHover = true; } else { _rightHover = true; } }), onExit: (_) => setState(() { if (left) { _leftHover = false; } else { _rightHover = false; } }), child: left ? _leftPanel(t, floating: true) : _rightPanel(t, floating: true), ); } // ===================== 左侧栏内容 ===================== /// 构建左侧栏:项目概览、动作/工位列表、视图模式、显示选项、 /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 Widget _leftPanel(Tokens t, {bool floating = false}) { final List actions = c.project.actions; final bool bar = c.project.viewState.mode == ViewMode.bar; return Container( width: 300, decoration: BoxDecoration( color: t.panel, border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), boxShadow: floating ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] : null, ), child: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ _sectionLabel(t, '节拍周期设置'), const Spacer(), _panelControls(t, true), ], ), const SizedBox(height: 8), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Container( width: 34, height: 34, decoration: BoxDecoration( color: t.accent2.withValues(alpha: 0.2), borderRadius: BorderRadius.circular(9), ), alignment: Alignment.center, child: Text('周', style: TextStyle(color: t.accent2, fontSize: 13, fontWeight: FontWeight.w700)), ), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('节拍周期设置', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.text, fontSize: 13, fontWeight: FontWeight.w600)), Text( '项目:${c.project.name} · ${c.filePath == null ? '未保存' : c.filePath!.split(RegExp(r'[\\/]')).last}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10), ), ], ), ), ], ), const Divider(height: 16), // 循环时长(= 时间轴长度)即一个循环的 360°/100%,点击即可编辑。 Row( children: [ Text('循环', style: TextStyle(color: t.dim, fontSize: 10.5)), const SizedBox(width: 6), Expanded( child: Tooltip( message: '点击编辑循环时长 / 时间轴长度', child: InkWell( onTap: () => showDialog( context: context, builder: (_) => SettingsDialog(controller: c), ), borderRadius: BorderRadius.circular(6), child: Row( children: [ Flexible( child: Text( '${tfmt(c.project.cycle.durationMs, c.project.units)} = 360° = 100%', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.accent, fontSize: 11), ), ), const SizedBox(width: 4), Icon(Icons.edit, size: 12, color: t.accent), ], ), ), ), ), const SizedBox(width: 8), Text('动作 ${actions.length} · 依赖 ${_depCount()}', style: TextStyle(color: t.dim, fontSize: 10.5)), ], ), ], ), ), const SizedBox(height: 12), Row( children: [ Flexible( child: _sectionLabel(t, bar ? '动作 / 执行器泳道' : '动作列表(按轨道 L1→L${c.project.laneCount})'), ), const Spacer(), _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, () => c.addAction(startAngle: 0)), const SizedBox(width: 6), _headerAction( t, Icons.delete_outline, '删除', t.danger, Colors.white, c.selectedId == null ? null : () => c.deleteAction(c.selectedId!), ), ], ), const SizedBox(height: 8), // 按泳道 / 轨道分组:同一泳道内的多个动作合并显示(最多两行,/ 分隔)。 ..._laneRows(t, bar), const SizedBox(height: 12), _sectionLabel(t, '视图模式'), const SizedBox(height: 8), Row( children: [ Expanded(child: _modeButton(t, '条形节拍(甘特)', bar, () => c.setViewMode(ViewMode.bar))), const SizedBox(width: 10), Expanded(child: _modeButton(t, '圆周节拍(同心)', !bar, () => c.setViewMode(ViewMode.circular))), ], ), const SizedBox(height: 12), _sectionLabel(t, '显示选项'), const SizedBox(height: 6), ..._displayOptions(t, bar), const SizedBox(height: 4), // 相位分区编辑入口:可任意增删、改名、改起止角。 Align( alignment: Alignment.centerLeft, child: TextButton.icon( onPressed: () => showDialog( context: context, builder: (_) => PhaseZoneDialog(controller: c), ), icon: const Icon(Icons.tune, size: 14), label: Text('编辑相位分区(${c.project.phaseZones.length})', style: const TextStyle(fontSize: 11.5)), style: TextButton.styleFrom( foregroundColor: t.accent, padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), minimumSize: const Size(0, 26), ), ), ), const SizedBox(height: 8), _sectionLabel(t, '工位负载 / 相位占用'), const SizedBox(height: 10), ..._stationLoads(t), const SizedBox(height: 12), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.info, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), const SizedBox(height: 6), Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('双击空白新建动作 · F1 打开帮助', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), ], ), ), ], ), ), ); } /// 侧栏小节标题文本(单行,过长时省略)。 Widget _sectionLabel(Tokens t, String s) => Text( s, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 11, letterSpacing: 1.4, fontWeight: FontWeight.w500), ); /// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。 /// /// [onTap] 为 null 时按钮呈禁用态(降低不透明度),用于「未选中动作时禁用删除」。 Widget _headerAction(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback? onTap) { final bool enabled = onTap != null; return Opacity( opacity: enabled ? 1 : 0.4, child: InkWell( onTap: onTap, borderRadius: BorderRadius.circular(8), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(8)), child: Row( children: [ Icon(icon, size: 14, color: fg), const SizedBox(width: 4), Text(label, style: TextStyle(color: fg, fontSize: 11, fontWeight: FontWeight.w700)), ], ), ), ), ); } /// 左侧栏:按泳道 / 轨道分组的行列表。 List _laneRows(Tokens t, bool bar) { final List lanes = {for (final Action a in c.project.actions) a.layer}.toList()..sort(); final List out = []; for (int li = 0; li < lanes.length; li++) { final int lane = lanes[li]; final List acts = c.project.actions.where((Action a) => a.layer == lane).toList() ..sort((Action a, Action b) => a.startAngle.compareTo(b.startAngle)); // 单动作泳道沿用普通动作行;多动作泳道合并显示。 out.add(acts.length == 1 ? _actionRow(t, acts.first, li, bar) : _laneRow(t, lane, li, acts, bar)); } return out; } /// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。 Widget _laneRow(Tokens t, int lane, int li, List acts, bool bar) { if (acts.isEmpty) return const SizedBox.shrink(); final Action primary = acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first); final bool sel = c.isSelected(primary.id); final Station? st = c.project.stationById(primary.stationId); final String joined = acts.map((Action a) => '${a.id} ${a.name}').join(' / '); double a0 = acts.first.startAngle; double a1 = acts.first.endAngle; for (final Action a in acts) { a0 = math.min(a0, a.startAngle); a1 = math.max(a1, a.endAngle); } return Padding( padding: const EdgeInsets.only(bottom: 6), child: InkWell( onTap: () => c.select( primary.id, toggle: HardwareKeyboard.instance.isControlPressed || HardwareKeyboard.instance.isShiftPressed, ), borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), decoration: BoxDecoration( color: sel ? t.sel : t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), ), child: Row( children: [ Container( width: 22, height: 22, decoration: BoxDecoration( color: Color(primary.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6), ), alignment: Alignment.center, child: Text('${li + 1}', style: TextStyle(color: t.chip, fontSize: 11, fontWeight: FontWeight.w700)), ), const SizedBox(width: 9), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( joined, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle( color: sel ? t.text : t.text2, fontSize: 12.5, height: 1.25, fontWeight: sel ? FontWeight.w600 : FontWeight.normal, ), ), Text( '${st?.name ?? primary.stationId} · ${primary.driver}' '${acts.length > 1 ? ' · 共 ${acts.length} 个' : ''}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10), ), ], ), ), const SizedBox(width: 6), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', style: TextStyle(color: t.sub, fontSize: 11), ), Text('${acts.length} 个动作', style: TextStyle(color: t.dim, fontSize: 10)), ], ), const SizedBox(width: 6), InkWell( onTap: () => showDialog( context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), borderRadius: BorderRadius.circular(7), child: Container( width: 28, height: 24, alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line2), ), child: Icon(Icons.edit, size: 13, color: sel ? t.accent : t.dim), ), ), ], ), ), ), ); } /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 Widget _actionRow(Tokens t, Action a, int i, bool bar) { final bool sel = c.isSelected(a.id); final Station? st = c.project.stationById(a.stationId); return Padding( padding: const EdgeInsets.only(bottom: 6), child: InkWell( // Ctrl / Shift 点击可多选,用于批量对齐等操作。 onTap: () => c.select( a.id, toggle: HardwareKeyboard.instance.isControlPressed || HardwareKeyboard.instance.isShiftPressed, ), borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), decoration: BoxDecoration( color: sel ? t.sel : t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), ), child: Row( children: [ Container( width: 22, height: 22, decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6)), alignment: Alignment.center, child: Text('${i + 1}', style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), ), const SizedBox(width: 9), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(a.name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: sel ? t.text : t.text2, fontSize: 12, fontWeight: sel ? FontWeight.w600 : FontWeight.normal)), Text('${a.id} · ${st?.name ?? a.stationId} · ${a.driver}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), ], ), ), const SizedBox(width: 6), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( bar ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' : 'L${a.layer + 1}', style: TextStyle(color: t.sub, fontSize: 10), ), Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), style: TextStyle(color: t.dim, fontSize: 10)), ], ), const SizedBox(width: 6), InkWell( onTap: () => showDialog( context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), borderRadius: BorderRadius.circular(7), child: Container( width: 28, height: 24, alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line2), ), child: Icon(Icons.edit, size: 13, color: sel ? t.accent : t.dim), ), ), // 选中该动作时才出现删除入口,避免误触。 if (sel) ...[ const SizedBox(width: 4), InkWell( onTap: () => c.deleteAction(a.id), borderRadius: BorderRadius.circular(7), child: Container( width: 28, height: 24, alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), border: Border.all(color: t.danger.withValues(alpha: 0.6)), ), child: Icon(Icons.delete_outline, size: 13, color: t.danger), ), ), ], ], ), ), ), ); } /// 视图模式选择按钮(条形 / 圆周)。 Widget _modeButton(Tokens t, String label, bool active, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), child: Container( height: 44, alignment: Alignment.center, decoration: BoxDecoration( color: active ? t.accent.withValues(alpha: 0.16) : t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: active ? t.accent : t.line, width: 1.2), ), child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: active ? t.accent : t.sub, fontSize: 11)), ), ); } /// 显示选项复选列表:根据视图模式返回不同的开关项。 List _displayOptions(Tokens t, bool bar) { final ViewState v = c.project.viewState; final List> opts = bar ? >[ ['时间轴 / 相位双刻度', v.showRuler, (bool x) => c.setViewFlag(showRuler: x)], ['依赖箭头 FS / SS', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], ['跨循环片段标记', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], ['相位分区标注', v.showPhaseBands, (bool x) => c.setViewFlag(showPhaseBands: x)], ] : >[ ['同心圆环背景', v.showRingBg, (bool x) => c.setViewFlag(showRingBg: x)], ['顺序箭头(FS / SS)', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], ['层半径标注', v.showLayerLabels, (bool x) => c.setViewFlag(showLayerLabels: x)], ['跨循环高亮', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], ]; return opts.map((List o) { final bool on = o[1] as bool; return InkWell( onTap: () => (o[2] as void Function(bool))(!on), child: Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ Container( width: 16, height: 16, decoration: BoxDecoration( color: on ? t.accent.withValues(alpha: 0.22) : Colors.transparent, borderRadius: BorderRadius.circular(4), border: Border.all(color: on ? t.accent : t.line2), ), child: on ? Icon(Icons.check, size: 12, color: t.accent) : null, ), const SizedBox(width: 10), Text(o[0] as String, style: TextStyle(color: t.sub, fontSize: 11)), ], ), ), ); }).toList(); } /// 各工位的相位占用统计:汇总持续角并渲染为进度条。 List _stationLoads(Tokens t) { final Map load = {}; for (final Action a in c.project.actions) { load[a.stationId] = (load[a.stationId] ?? 0) + a.durationAngle; } final List out = []; for (final Station s in c.project.stations) { final double deg = load[s.id] ?? 0; out.add(Padding( padding: const EdgeInsets.only(bottom: 10), child: Column( children: [ Row( children: [ Expanded( child: Text('${s.id} ${s.name}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.sub, fontSize: 11)), ), Text('${deg.toStringAsFixed(0)}° · ${(deg / 3.6).toStringAsFixed(1)}%', style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), ], ), const SizedBox(height: 5), ClipRRect( borderRadius: BorderRadius.circular(4), child: LinearProgressIndicator( value: (deg / 360).clamp(0, 1), minHeight: 8, backgroundColor: t.track, valueColor: AlwaysStoppedAnimation(t.accent), ), ), ], ), )); } return out; } /// 统计项目中所有动作的依赖总数。 int _depCount() { int n = 0; for (final Action a in c.project.actions) { n += a.deps.length; } return n; } // ===================== 右侧栏内容 ===================== /// 构建右侧栏:选中动作的属性、角度编辑、工艺单位、编辑操作、 /// 依赖关系与导出入口。[floating] 为 true 时以悬浮卡片样式呈现。 Widget _rightPanel(Tokens t, {bool floating = false}) { final Action? a = c.selected; final bool bar = c.project.viewState.mode == ViewMode.bar; return Container( width: 340, decoration: BoxDecoration( color: t.panel, border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), boxShadow: floating ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] : null, ), child: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), child: Row( children: [ _sectionLabel(t, '属性 · 选中动作'), const Spacer(), _panelControls(t, false), ], ), ), Expanded( child: a == null ? Center( child: Text('未选中动作\n点击画布或左侧列表选择', textAlign: TextAlign.center, style: TextStyle(color: t.dim, fontSize: 11, height: 1.6)), ) : SingleChildScrollView( padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _selectedHeader(t, a, bar), const SizedBox(height: 14), ..._propertyFields(t, a, bar), const SizedBox(height: 10), if (!bar) ...[ _sectionLabel(t, '角度编辑'), const SizedBox(height: 8), _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), (double v) => c.setActionStart(a.id, v * 360)), _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), (double v) => c.setActionDuration(a.id, v * 180)), const SizedBox(height: 8), ], _unitCard(t), const SizedBox(height: 12), _sectionLabel(t, bar ? '编辑操作' : '层 / 编辑操作'), const SizedBox(height: 10), if (bar) Row( children: [ Expanded(child: _editTool(t, Icons.add, '添加动作', t.ok, t.onAccent, () => c.addAction(startAngle: 0))), const SizedBox(width: 8), Expanded(child: _editTool(t, Icons.edit, '编辑', t.accent, t.onAccent, () { showDialog(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)); })), const SizedBox(width: 8), Expanded(child: _editTool(t, Icons.copy, '复制', t.panel2, t.sub, c.duplicateSelected, border: t.line2)), const SizedBox(width: 8), Expanded(child: _editTool(t, Icons.delete_outline, '删除', t.panel2, t.sub, () => c.deleteAction(a.id), border: t.line2)), ], ) else ...[ Row( children: [ Expanded(child: _wideBtn(t, Icons.add, '新增轨道 L${c.project.laneCount + 1}', t.accent2, Colors.white, () => c.changeLayer(a.id, 1))), const SizedBox(width: 8), Expanded(child: _wideBtn(t, Icons.keyboard_arrow_up, '重排 / 合并层', t.panel2, t.sub, () => c.changeLayer(a.id, -1), border: t.line2)), ], ), const SizedBox(height: 8), Row( children: [ _editTool(t, Icons.copy, '复制动作', t.panel2, t.sub, c.duplicateSelected, border: t.line2), const SizedBox(width: 8), _editTool(t, Icons.delete_outline, '删除动作', t.panel2, t.sub, () => c.deleteAction(a.id), border: t.line2), const SizedBox(width: 8), _editTool(t, Icons.align_horizontal_left, '对齐相位', t.panel2, t.sub, c.alignPhase, border: t.line2), ], ), const SizedBox(height: 12), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.info, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('新增动作放在最外层;箭头方向即执行顺序', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('绿实线 FS 严格顺序 · 琥珀虚线 SS 并行重叠', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), ], ), ), ], const SizedBox(height: 12), // 输入依赖:允许多条(多前置)。 _sectionLabel(t, '前置依赖 · 输入(${a.deps.length})'), const SizedBox(height: 8), if (a.deps.isEmpty) Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11)) else for (final Dependency d in a.deps) _depRow(t, a, d), const SizedBox(height: 6), OutlinedButton.icon( onPressed: () => showDialog( context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), icon: const Icon(Icons.add_link, size: 15), label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)), style: OutlinedButton.styleFrom( foregroundColor: t.accent, side: BorderSide(color: t.line2), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(vertical: 10), minimumSize: const Size(double.infinity, 0), ), ), const SizedBox(height: 12), // 输出依赖:本动作作为前置指向的后续动作(允许多结果)。 _sectionLabel(t, '输出依赖 · 结果(${_outgoingDeps(a).length})'), const SizedBox(height: 8), if (_outgoingDeps(a).isEmpty) Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11)) else for (final (Action target, Dependency d) in _outgoingDeps(a)) _outDepRow(t, a, target, d), if (bar) ...[ const SizedBox(height: 12), _sectionLabel(t, '导出'), const SizedBox(height: 8), _exportRow(t, 'SVG(矢量 · 可编辑 · 打印级)', _exportSvg), const SizedBox(height: 6), _exportRow(t, 'PNG / PDF / 工艺卡', _exportPng), ], const SizedBox(height: 12), _helpCard(t), ], ), ), ), ], ), ); } /// 选中动作的头部信息卡:编号、名称、工位/驱动与跨圈标记。 Widget _selectedHeader(Tokens t, Action a, bool bar) { final Station? st = c.project.stationById(a.stationId); return Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line), ), child: Row( children: [ Container( width: 34, height: 34, decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(8)), alignment: Alignment.center, child: Text(a.id, style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), ), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(a.name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w600)), Text('${st?.id ?? a.stationId} · ${a.driver} · 层 L${a.layer + 1}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), ], ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), decoration: BoxDecoration( color: (a.wrap ? t.warn : t.accent).withValues(alpha: 0.14), borderRadius: BorderRadius.circular(8), border: Border.all(color: a.wrap ? t.warn : t.accent), ), child: Text(a.wrap ? '跨圈' : '选中', style: TextStyle(color: a.wrap ? t.warn : t.accent, fontSize: 11)), ), ], ), ); } /// 构建属性键值列表:条形视图按时间维度,圆周视图按相位维度。 List _propertyFields(Tokens t, Action a, bool bar) { final UnitSettings u = c.project.units; final double cycle = c.project.cycle.durationMs; final List> fields; if (bar) { fields = >[ ['开始时刻', tfmt(a.startAngle / 360 * cycle, u), pfmt(a.startAngle, u)], ['结束时刻', tfmt(a.endAngle / 360 * cycle, u), a.wrap ? '${a.endAngle.toStringAsFixed(1)}° → ${(a.endAngle - 360).toStringAsFixed(1)}°' : pfmt(a.endAngle, u)], ['持续时间', tfmt(a.durationAngle / 360 * cycle, u), pfmt(a.durationAngle, u)], ['循环归属', a.wrap ? '当前圈 + 下一圈' : '当前圈', a.wrap ? '跨圈片段' : '单圈内'], ['顺序约束', _depSummary(a), '前序动作关系'], ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], ]; } else { fields = >[ ['起始相位', pfmt(a.startAngle, u), '${tfmt(a.startAngle / 360 * cycle, u)} · 12 点钟起顺时针'], ['结束相位', pfmt(a.endAngle, u), tfmt(a.endAngle / 360 * cycle, u)], ['持续相位', pfmt(a.durationAngle, u), '${tfmt(a.durationAngle / 360 * cycle, u)} · 占循环 ${(a.durationAngle / 3.6).toStringAsFixed(2)}%'], ['所在层', 'L${a.layer + 1}', '层内序号 ${a.layer + 1}'], ['顺序约束', _depSummary(a), '前序动作关系'], ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], ]; } final List out = []; for (int i = 0; i < fields.length; i++) { out.add(Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), decoration: BoxDecoration( color: i.isEven ? t.panel2.withValues(alpha: 0.7) : Colors.transparent, borderRadius: BorderRadius.circular(8), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text(fields[i][0], style: TextStyle(color: t.sub, fontSize: 11)), const Spacer(), Flexible( child: Text(fields[i][1], textAlign: TextAlign.right, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.text, fontSize: 12, fontWeight: FontWeight.w600)), ), ], ), if (fields[i][2].isNotEmpty) Align( alignment: Alignment.centerRight, child: Text(fields[i][2], style: TextStyle(color: t.dim, fontSize: 10)), ), ], ), )); } return out; } /// 生成依赖摘要文本。 /// /// 一个动作可以有多条输入依赖(多输入)与多条输出依赖(多结果), /// 因此这里按类型汇总条数,而不是只取一条。 String _depSummary(Action a) { if (a.deps.isEmpty) return '无输入'; int fs = 0; int ss = 0; int other = 0; for (final Dependency d in a.deps) { if (d.type == DepType.fs) { fs++; } else if (d.type == DepType.ss) { ss++; } else { other++; } } final List parts = []; if (fs > 0) parts.add('FS ×$fs'); if (ss > 0) parts.add('SS ×$ss'); if (other > 0) parts.add('其它 ×$other'); return '${a.deps.length} 条(${parts.join(' · ')})'; } /// 收集以 [a] 为起点的输出依赖(即 a 是前置、指向其它动作)。 /// /// 返回 `(目标动作, 依赖)` 列表;一个动作可以输出多个结果。 List<(Action, Dependency)> _outgoingDeps(Action a) { final List<(Action, Dependency)> out = <(Action, Dependency)>[]; for (final Action target in c.project.actions) { for (final Dependency d in target.deps) { if (d.fromId == a.id) out.add((target, d)); } } return out; } /// 根据动作中点相位归类到用户定义的相位分区;未命中时返回「—」。 String _phaseZone(Action a) { final double mid = (a.startAngle + a.endAngle) / 2 % 360; for (final PhaseZone z in c.project.phaseZones) { if (z.contains(mid)) return z.name; } return '—'; } /// 带标签与数值显示的滑块(用于起始角 / 持续角编辑)。 Widget _slider(Tokens t, String label, double value, String display, ValueChanged onChanged) { return Padding( padding: const EdgeInsets.only(bottom: 6), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text(label, style: TextStyle(color: t.sub, fontSize: 11)), const Spacer(), Text(display, style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), ], ), SliderTheme( data: SliderTheme.of(context).copyWith( trackHeight: 4, thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 7), overlayShape: const RoundSliderOverlayShape(overlayRadius: 14), ), child: Slider(value: value, onChanged: onChanged), ), ], ), ); } /// 工艺单位与精度卡片:切换时间/相位单位并显示换算关系。 Widget _unitCard(Tokens t) { final UnitSettings u = c.project.units; return Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ _sectionLabel(t, '工艺单位与精度'), const Spacer(), InkWell( onTap: () => showDialog( context: context, builder: (_) => SettingsDialog(controller: c)), child: Row( children: [ Icon(Icons.tune, size: 14, color: t.accent), const SizedBox(width: 4), Text('参数', style: TextStyle(color: t.accent, fontSize: 11)), ], ), ), ], ), const SizedBox(height: 10), _unitRow(t, '时间单位', TimeUnit.values.map((TimeUnit x) => (timeUnitLabel(x), x == u.timeUnit)).toList(), (int i) { c.setUnits(c.project.units.copyWith(timeUnit: TimeUnit.values[i])); }), const SizedBox(height: 8), _unitRow(t, '相位单位', <(String, bool)>[('°', u.phaseUnit == PhaseUnit.deg), ('%', u.phaseUnit == PhaseUnit.percent)], (int i) { c.setUnits(c.project.units.copyWith(phaseUnit: i == 0 ? PhaseUnit.deg : PhaseUnit.percent)); }), const SizedBox(height: 10), Divider(height: 1, color: t.line), const SizedBox(height: 8), Text( '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)} 1% = ${tfmtAuto(c.project.cycle.durationMs / 100)} 1 圈 = ${tfmt(c.project.cycle.durationMs, u)}', style: TextStyle(color: t.dim, fontSize: 10), ), ], ), ); } /// 单位选择行:一组互斥的选项按钮。 Widget _unitRow(Tokens t, String label, List<(String, bool)> options, ValueChanged onPick) { return Row( children: [ SizedBox(width: 64, child: Text(label, style: TextStyle(color: t.sub, fontSize: 11))), for (int i = 0; i < options.length; i++) Padding( padding: const EdgeInsets.only(right: 6), child: InkWell( onTap: () => onPick(i), borderRadius: BorderRadius.circular(8), child: Container( width: 54, height: 32, alignment: Alignment.center, decoration: BoxDecoration( color: options[i].$2 ? t.accent.withValues(alpha: 0.18) : t.panel, borderRadius: BorderRadius.circular(8), border: Border.all(color: options[i].$2 ? t.accent : t.line2), ), child: Text(options[i].$1, style: TextStyle(color: options[i].$2 ? t.accent : t.sub, fontSize: 11)), ), ), ), ], ); } /// 右侧栏中的方形编辑工具按钮。 Widget _editTool(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(9), child: Container( width: 74, height: 58, decoration: BoxDecoration( color: bg, borderRadius: BorderRadius.circular(9), border: Border.all(color: border ?? bg), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(icon, size: 18, color: fg), const SizedBox(height: 4), Text(label, style: TextStyle(color: fg, fontSize: 10, fontWeight: FontWeight.w600)), ], ), ), ); } /// 横向加宽的按钮(图标 + 文字)。 Widget _wideBtn(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(9), child: Container( height: 40, alignment: Alignment.center, decoration: BoxDecoration( color: bg, borderRadius: BorderRadius.circular(9), border: Border.all(color: border ?? bg), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(icon, size: 15, color: fg), const SizedBox(width: 6), Flexible( child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: fg, fontSize: 11)), ), ], ), ), ); } /// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。 Widget _depRow(Tokens t, Action a, Dependency d) { final Color col = d.type == DepType.fs ? t.fs : t.ss; return Container( margin: const EdgeInsets.only(bottom: 5), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line), ), child: Row( children: [ Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), const SizedBox(width: 8), Expanded( child: Text( '${d.fromId} → ${a.id} ${d.type.name.toUpperCase()}${d.type == DepType.ss ? ' +${d.offsetAngle.toStringAsFixed(0)}°' : ''}', style: TextStyle(color: t.sub, fontSize: 10), ), ), InkWell( onTap: () => c.removeDependency(d.fromId, a.id), child: Icon(Icons.close, size: 14, color: t.dim), ), ], ), ); } /// 输出依赖展示行:本动作 [a] 作为前置指向 [target],可删除。 Widget _outDepRow(Tokens t, Action a, Action target, Dependency d) { final Color col = d.type == DepType.fs ? t.fs : t.ss; return Container( margin: const EdgeInsets.only(bottom: 5), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line), ), child: Row( children: [ Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), const SizedBox(width: 8), Expanded( child: Text( '${a.id} → ${target.id} ${d.type.name.toUpperCase()}${d.type == DepType.ss ? ' +${d.offsetAngle.toStringAsFixed(0)}°' : ''}', style: TextStyle(color: t.sub, fontSize: 10), ), ), InkWell( onTap: () => c.removeDependency(a.id, target.id), child: Icon(Icons.close, size: 14, color: t.dim), ), ], ), ); } /// 导出入口行(点击触发对应导出流程)。 Widget _exportRow(Tokens t, String label, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), child: Container( height: 42, alignment: Alignment.centerLeft, padding: const EdgeInsets.symmetric(horizontal: 12), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line2), ), child: Text(label, style: TextStyle(color: t.sub, fontSize: 11)), ), ); } /// 右侧栏底部的帮助与快捷键提示卡片。 Widget _helpCard(Tokens t) { return Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Icon(Icons.help_outline, size: 16, color: t.accent), const SizedBox(width: 6), Text('帮助 · 快捷键', style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), ], ), const SizedBox(height: 8), Text('拖拽 = 平移相位 · 拖端点 = 改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('Shift+拖 = 改层 · F1 = 帮助中心', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('Ctrl+Z / Ctrl+Y = 撤销 / 重做', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), ], ), ); } // ===================== 状态栏 ===================== /// 底部状态栏:横向滚动展示循环周期、动作/依赖数、单位换算与 /// 当前状态消息,右侧提示未保存状态与常用快捷键。 Widget _statusBar(Tokens t) { final UnitSettings u = c.project.units; final bool circular = c.project.viewState.mode == ViewMode.circular; final List items = [ '循环周期 ${tfmt(c.project.cycle.durationMs, u)}', '相位 360° = 100%', '动作 ${c.project.actions.length}', '依赖 ${_depCount()}', circular ? '轨道 L1–L${c.project.laneCount}' : '工位 ${c.project.stations.length}', circular ? '同心圆 ${c.project.laneCount}' : '时间轴 0–${tfmt(c.project.cycle.durationMs, u)}', '单位 ${timeUnitLabel(u.timeUnit)} / ${phaseUnitLabel(u.phaseUnit)}', '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}', c.status, ]; return Container( height: 32, padding: const EdgeInsets.symmetric(horizontal: 16), decoration: BoxDecoration( color: t.chrome, border: Border(top: BorderSide(color: t.line2)), ), child: Row( children: [ Expanded( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: items.map((String s) { final bool last = s == items.last; return Padding( padding: const EdgeInsets.only(right: 22), child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)), ); }).toList(), ), ), ), if (c.dirty) Padding( padding: const EdgeInsets.only(right: 14), child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)), ), Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)), ], ), ); } }