// 应用外壳:组织工具栏、左右可停靠侧栏、画布舞台与状态栏的整体布局, // 并集中处理文件、导出、快捷键与侧栏停靠等交互。 // // 架构位置:位于 UI 层顶层(由 main.dart 的根组件加载),向下装配 // CanvasView / CanvasOverlays / 各类对话框,并通过 AppController 读写 // 项目状态。本文件重点包含: // · 全局快捷键绑定(撤销/重做/保存/打开/新建/删除/帮助等); // · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机; // · 自适应/紧凑工具栏布局(按可用宽度切换); // · 文件打开/保存/另存为与 SVG、PNG 导出流程。 import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import 'package:flutter/services.dart'; import '../arch/arch_dxf.dart'; import '../arch/arch_export.dart'; import '../arch/arch_models.dart'; import '../modules/module_registry.dart'; import '../persistence/recent_store.dart'; import '../sketch/sketch_models.dart'; import '../sketch/sketch_solver.dart'; import '../export/drawio_writer.dart'; import '../export/export_renderer.dart'; import '../export/svg_writer.dart'; import '../layout/layout.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../persistence/android_docs.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; import '../update/update_service.dart'; import '../version.dart'; import 'ai_dialog.dart'; import 'arch_panel.dart'; import 'arch_view.dart'; import 'brand_menu.dart'; import 'canvas_overlays.dart'; import 'canvas_view.dart'; import 'dialogs.dart'; import 'home_view.dart'; import 'update_dialog.dart'; import 'update_icon.dart'; /// 应用外壳组件:承载主界面布局与文件/侧栏等交互逻辑。 class AppShell extends StatefulWidget { /// 创建应用外壳,[controller] 为全局应用控制器。 const AppShell({super.key, required this.controller}); /// 全局应用控制器。 final AppController controller; /// 创建应用外壳对应的状态对象。 @override State createState() => _AppShellState(); } /// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态, /// 并提供文件操作、导出与快捷键处理。 class _AppShellState extends State { // ---- 侧栏状态机:可见(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; // ---- 由上述三态派生的侧栏呈现方式 ---- /// 左侧栏宽度:随屏幕宽度动态压缩(300 → 200),窄屏双侧栏停靠也不溢出。 double get _leftPanelWidth { final double w = MediaQuery.sizeOf(context).width; return math.min(300.0, math.max(200.0, w * 0.24)); } /// 右侧栏宽度:随屏幕宽度动态压缩(340 → 240),窄屏双侧栏停靠也不溢出。 double get _rightPanelWidth { final double w = MediaQuery.sizeOf(context).width; return math.min(340.0, math.max(240.0, w * 0.26)); } /// 工具栏整体缩放系数:触屏平台(安卓 / iOS)缩小到 80%, /// 一排即可放下全部操作且不影响点按;桌面端保持原尺寸。 double get _toolScale => (Platform.isAndroid || Platform.isIOS) ? 0.8 : 1.0; /// 工具栏字号:随 [_toolScale] 缩放并保底 9,兼顾紧凑与可读。 double _toolFont(double size) => math.max(9.0, size * _toolScale); /// 左侧栏是否处于停靠(固定)状态。 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); // 延迟几秒再检查,避免与启动渲染争资源。 WidgetsBinding.instance.addPostFrameCallback((_) => _autoCheckUpdate()); } // ---- 应用内更新状态 ---- /// 检测到的新版本信息;为空表示暂无更新(或尚未检查 / 检查失败)。 UpdateInfo? _update; /// 是否正在手动检查更新(防止重复点击)。 bool _checkingUpdate = false; /// 是否已完成一次按平台 / 屏幕宽度的默认布局初始化。 bool _layoutInited = false; /// 首次构建时按平台与屏幕宽度设定侧栏默认状态(动态兼容不同分辨率): /// - 触屏平台(Android / iOS):默认收起为贴边轨道,给画布让出完整宽度; /// - 桌面窄窗口(< 1500 逻辑宽):同样默认收起,避免两侧栏挤占画布。 @override void didChangeDependencies() { super.didChangeDependencies(); if (_layoutInited) return; _layoutInited = true; final bool touch = Platform.isAndroid || Platform.isIOS; final double w = MediaQuery.of(context).size.width; if (touch || w < 1500) { _leftVisible = false; _rightVisible = false; _leftPinned = false; _rightPinned = false; } } /// 取消订阅并释放资源。 @override void dispose() { c.removeListener(_onChange); super.dispose(); } /// 控制器变化回调:触发重建。 void _onChange() => setState(() {}); // ===================== 文件与导出流程 ===================== /// 当前有未保存修改时弹窗确认是否放弃;返回 true 表示可以继续。 Future _confirmDiscardIfDirty() async { if (!c.dirty) return true; 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('继续')), ], ), ); return ok == true; } /// 记录「最近打开」(异步写盘,失败静默)。 void _rememberRecent(String path, String moduleId) { RecentStore.remember(path: path, moduleId: moduleId); } /// 从首页 / 品牌菜单进入某模块并**新建**该类型文档(未保存修改先确认)。 Future _startModule(EdcModule m) async { if (!m.available) return; if (moduleOf(c.appMode)?.id == m.id) return; // 已在该模块 if (!await _confirmDiscardIfDirty()) return; switch (m.id) { case 'sequence': c.newProject(); c.setAppMode(AppMode.sequence); case 'architecture': c.newArchProject(); c.setAppMode(AppMode.architecture); default: c.setStatus('${m.name}:文档类型尚未开放'); } } /// 返回首页(未保存修改先确认)。 Future _goHome() async { if (c.appMode == AppMode.home) return; if (!await _confirmDiscardIfDirty()) return; c.goHome(); } /// 品牌菜单命令路由(`_home` / `_settings` / 模块 id)。 Future _handleBrandCommand(String cmd) async { if (!mounted) return; if (cmd == '_home') { await _goHome(); return; } if (cmd == '_settings') { await showDialog( context: context, builder: (_) => SoftwareSettingsDialog(controller: c), ); return; } final EdcModule? m = moduleById(cmd); if (m != null) await _startModule(m); } /// 新建项目:当前模块内新建(未保存修改先确认)。 Future _newProject() async { if (!await _confirmDiscardIfDirty()) return; // 架构图模块:新建独立的架构图文档(空画布 + 默认图层)。 if (c.appMode == AppMode.architecture) { c.newArchProject(); return; } c.newProject(); } /// 打开文档(工具栏 / Ctrl+O):模块内直接打开;首页时先选择文档类型。 Future _open() async { final EdcModule? m = moduleOf(c.appMode); if (m == null) { await _openDocumentChooser(); return; } await _openDocumentOfModule(m); } /// 「打开文档…」:先选文档类型,再走对应类型的打开流程。 Future _openDocumentChooser() async { final EdcModule? m = await showDocumentTypeDialog(context); if (m == null) return; await _openDocumentOfModule(m); } /// 打开某模块的文档:时序图 → `*.seq.json`;架构图 → `*.arch.json`。 Future _openDocumentOfModule(EdcModule m) async { if (!await _confirmDiscardIfDirty()) return; if (!mounted) return; final bool arch = m.id == 'architecture'; final String suffix = m.suffix; // 安卓版:从公共目录打开(兼容旧目录)。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: false, defaultName: '', suffix: suffix, ), ); if (name == null) return; try { final Uint8List? bytes = await AndroidDocs.readFile(name); if (bytes == null) { if (mounted) await showMessage(context, '打开失败', '未找到文件 $name'); return; } final String content = utf8.decode(bytes); if (arch) { c.setAppMode(AppMode.architecture); c.loadArchDoc(ArchDoc.decode(content), path: null); } else { c.setAppMode(AppMode.sequence); c.loadProject(Project.decode(content), path: null); } c.setStatus('已打开 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '打开失败', '$e'); } return; } final String? path = await pickFile( context, save: false, initialPath: c.currentFilePath, suffix: suffix, ); if (path == null) return; try { await _openDocumentAt(m, path); } catch (e) { if (mounted) await showMessage(context, '打开失败', '不是有效的${m.name}文档:$e'); } } /// 直接打开给定路径的文档(最近打开 / 文件选择共用;桌面与安卓一致)。 Future _openDocumentAt(EdcModule m, String path) async { String src; if (AndroidDocs.isAvailable) { final String name = path.split(RegExp(r'[\\/]')).last; final Uint8List? bytes = await AndroidDocs.readFile(name); if (bytes == null) throw Exception('未找到文件 $name'); src = utf8.decode(bytes); } else { src = await File(path).readAsString(); } if (m.id == 'architecture') { c.setAppMode(AppMode.architecture); c.loadArchDoc(ArchDoc.decode(src), path: AndroidDocs.isAvailable ? null : path); } else { c.setAppMode(AppMode.sequence); c.loadProject(Project.decode(src), path: AndroidDocs.isAvailable ? null : path); } _rememberRecent(path, m.id); } /// 打开最近文件(失败时移除失效条目并提示)。 Future _openRecent(EdcModule m, RecentDoc doc) async { if (!await _confirmDiscardIfDirty()) return; try { await _openDocumentAt(m, doc.path); } catch (e) { await RecentStore.remove(doc.path); if (mounted) { await showMessage(context, '打开失败', '文件可能已被移动或删除:\n$e'); } } } /// 保存:已有路径则直接保存,否则转入“另存为”。 /// /// 时序图与架构图分别保存为 `*.seq.json` 与 `*.arch.json` 两个独立文件 /// (内容互不包含;时序图中不含架构数据)。 Future _save() async { // 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。 if (AndroidDocs.isAvailable || c.currentFilePath == null) { await _saveAs(); return; } if (c.appMode == AppMode.architecture) { try { await c.saveArchAs(c.archFilePath!); _rememberRecent(c.archFilePath!, 'architecture'); } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } return; } final bool ok = await c.save(); if (ok && c.filePath != null) { _rememberRecent(c.filePath!, 'sequence'); } } /// 另存为:按当前模块选择目标路径(`*.seq.json` / `*.arch.json`),写入并生成 `.bak` 备份。 Future _saveAs() async { final bool arch = c.appMode == AppMode.architecture; final String suffix = arch ? '.arch.json' : '.seq.json'; // 安卓版:写入公共 Documents(MediaStore 通道)。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}$suffix', suffix: suffix, ), ); if (name == null) return; try { if (arch) { await AndroidDocs.saveFile( name, Uint8List.fromList(utf8.encode(c.arch.encode())), mime: 'application/json'); await c.markArchSaved('${AndroidDocs.location()}/$name'); _rememberRecent('${AndroidDocs.location()}/$name', 'architecture'); } else { final Uint8List data = Uint8List.fromList( utf8.encode(c.project.encode(includeArch: false))); await AndroidDocs.saveFile(name, data, mime: 'application/json'); await c.markSaved('${AndroidDocs.location()}/$name'); _rememberRecent('${AndroidDocs.location()}/$name', 'sequence'); } } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } return; } final String? path = await pickFile( context, save: true, initialPath: c.currentFilePath, defaultName: c.currentFilePath == null ? '${c.project.name}$suffix' : null, suffix: suffix, ); if (path == null) return; try { if (arch) { await c.saveArchAs(path); _rememberRecent(path, 'architecture'); } else { await c.saveAs(path); _rememberRecent(path, 'sequence'); if (mounted) { c.setStatus('已保存 ${path.split(RegExp(r'[\\/]')).last}(含 .bak 备份)'); } } } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } } /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 /// /// 三种视图均支持(流程图由 [FlowLayout] 几何直接生成)。 Future _exportSvg() async { if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); return; } // 安卓版:写入公共 Documents/EDC。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}.svg', suffix: '.svg', ), ); if (name == null) return; try { final String svg = SvgWriter( project: c.project, tokens: Tokens.of(c.brightness), mode: c.project.viewState.mode, ).build(); await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}.svg', suffix: '.svg', ); if (path == null) return; try { final String svg = SvgWriter( project: c.project, tokens: Tokens.of(c.brightness), mode: c.project.viewState.mode, ).build(); await File(path).writeAsString(svg, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。 /// /// 三种视图均支持(流程图走 [FlowchartPainter] 离屏渲染)。 Future _exportPng() async { if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); return; } final Uint8List bytes; try { bytes = await renderExportPng( project: c.project, tokens: Tokens.of(c.brightness), criticalActions: c.criticalActions, criticalDeps: c.criticalDeps, ); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); return; } if (!mounted) return; // 安卓版:写入配置的公共目录。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}.png', suffix: '.png', ), ); if (name == null) return; try { await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}.png', suffix: '.png', ); if (path == null) return; try { await File(path).writeAsBytes(bytes, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出架构图 SVG(矢量,纯白背景)。 Future _exportArchSvg() async { if (!c.licensed) { if (mounted) { await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); } return; } final String svg = buildArchSvg(doc: c.arch, baseTokens: Tokens.of(c.brightness)); if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}-架构图.svg', suffix: '.svg', ), ); if (name == null) return; try { await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}-架构图.svg', suffix: '.svg', ); if (path == null) return; try { await File(path).writeAsString(svg, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出架构图 PNG(固定 1920×1080 逻辑画布 × 2 倍像素,纯白背景)。 Future _exportArchPng() async { if (!c.licensed) { if (mounted) { await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); } return; } final Uint8List bytes; try { bytes = await renderArchPng( doc: c.arch, baseTokens: Tokens.of(c.brightness), projectName: c.project.name, ); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); return; } if (!mounted) return; if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}-架构图.png', suffix: '.png', ), ); if (name == null) return; try { await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}-架构图.png', suffix: '.png', ); if (path == null) return; try { await File(path).writeAsBytes(bytes, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出架构图 DXF(AutoCAD R12 ASCII):图层 / 图形 / 连线 / 文字均保留。 Future _exportArchDxf() async { if (!c.licensed) { if (mounted) { await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 DXF。'); } return; } final String dxf = buildArchDxf(doc: c.arch); if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}-架构图.dxf', suffix: '.dxf', ), ); if (name == null) return; try { await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(dxf)), mime: 'application/dxf'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}-架构图.dxf', suffix: '.dxf', ); if (path == null) return; try { await File(path).writeAsString(dxf, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } /// 导出 drawio:仅流程图视图提供,输出 diagrams.net 可直接打开并继续编辑的 XML。 /// /// 条形 / 圆周视图调用时给出明确提示(不做静默失败)。 Future _exportDrawio() async { if (c.project.viewState.mode != ViewMode.flow) { if (mounted) { await showMessage(context, '导出 drawio', '仅流程图视图支持导出 drawio;条形 / 圆周视图请导出 SVG 或 PNG。'); } return; } if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 drawio。'); return; } final String xml = DrawioWriter(project: c.project, tokens: Tokens.of(c.brightness)).build(); // 安卓版:写入公共 Documents 目录。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, defaultName: '${c.project.name}.drawio', suffix: '.drawio', ), ); if (name == null) return; try { await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(xml)), mime: 'application/xml'); if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } return; } final String? path = await pickFile( context, save: true, defaultName: '${c.project.name}.drawio', suffix: '.drawio', ); if (path == null) return; try { await File(path).writeAsString(xml, flush: true); if (mounted) c.setStatus('已导出 $path'); } catch (e) { if (mounted) await showMessage(context, '导出失败', '$e'); } } // ===================== 主界面构建 ===================== /// 首页(空白启动工作台):新建文档网格 / 打开 / 最近打开。 Widget _buildHome(Tokens t) { return Scaffold( backgroundColor: t.bg, body: HomeView( controller: c, onNewModule: _startModule, onOpenDocument: _openDocumentChooser, onOpenRecent: _openRecent, onOpenSettings: () => _handleBrandCommand('_settings'), onOpenHelp: () => showDialog(context: context, builder: (_) => const HelpDialog()), onCheckUpdate: _openUpdate, ), ); } /// 构建主界面:绑定全局快捷键,按“工具栏 / 中部(侧栏 + 画布) / 状态栏” /// 三段式纵向布局组织界面。 @override Widget build(BuildContext context) { final Tokens t = context.tok; // 首页(空白启动工作台):不渲染工作区工具栏 / 画布 / 状态栏。 if (c.appMode == AppMode.home) { return _buildHome(t); } // 顶层模块:架构图模式下画布、工具栏与侧栏切换为架构图工具。 final bool arch = c.appMode == AppMode.architecture; // 流程图视图只读:撤销 / 重做 / 删除等编辑操作统一停用(与置灰按钮一致)。 final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; // 全局快捷键绑定:编辑、文件、帮助、主题等。 return CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.keyZ, control: true): () { if (!flow) c.undo(); }, const SingleActivator(LogicalKeyboardKey.keyY, control: true): () { if (!flow) 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.keyA, control: true): () { if (c.appMode == AppMode.architecture) { if (c.sketchMode) { c.selectAllSketch(); } else { c.selectAllArch(); } } }, const SingleActivator(LogicalKeyboardKey.delete): () { if (c.appMode == AppMode.architecture) { if (c.sketchMode) { c.deleteSketchSelection(); } else { c.removeArchSelection(); } } else if (!flow && 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, const SingleActivator(LogicalKeyboardKey.escape): () { // 草图命令进行中:Esc 取消命令(其余场景 Esc 不拦截)。 if (c.appMode == AppMode.architecture && c.sketchMode && (c.sketchPendingCons != null || c.sketchPendingDim != null)) { c.cancelSketchCommand(); } }, }, child: Focus( autofocus: true, child: Scaffold( backgroundColor: t.bg, body: Column( children: [ // 顶部:系统状态栏区域与工具栏同底色,内容在系统栏下方, // 移动端实现真正的全屏(无黑边),桌面端 padding 为 0 无影响。 Container( color: t.chrome, padding: EdgeInsets.only(top: MediaQuery.paddingOf(context).top), child: _toolbar(t), ), Expanded( child: Row( // 拉伸交叉轴:保证左右侧栏始终从工具栏一直贯通到底部状态栏。 crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // 左侧栏:仅在停靠状态占用布局宽度。 if (_leftDocked) _leftPanel(t), Expanded( // 画布舞台:可绘制区域,叠加画布视图与浮层。 child: Stack( children: [ if (arch) // 架构图:独立画布(手绘识别 / 连线 / 属性编辑)。 Positioned.fill( child: Container( color: t.canvas2, child: ArchView(controller: c), ), ) else ...[ // 底层:可交互的画布。 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), ], ), ), // 底部:系统导航栏区域与状态栏同底色,内容在系统栏上方。 Container( color: t.chrome, padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom), child: _statusBar(t), ), ], ), ), ), ); } // ===================== 应用内更新 ===================== /// 启动后静默检查更新:发现新版本时在工具栏按钮上显示红色角标。 Future _autoCheckUpdate() async { // 测试环境不发起网络检查(避免 pending timer 与真实请求)。 if (Platform.environment['FLUTTER_TEST'] == 'true') return; await Future.delayed(const Duration(seconds: 3)); if (!mounted || _update != null) return; try { final UpdateInfo? info = await UpdateService.check(); if (mounted && info != null) setState(() => _update = info); } catch (_) { // 静默失败:不打扰用户 } } /// 更新检查按钮:圆环 + 上箭头 + 底座(按 docs/更新.png 的设计绘制); /// 检测到新版本时叠加红色角标。 Widget _updateBtn(Tokens t) { final UpdateInfo? info = _update; final Widget btn = _iconWidgetBtn( UpdateIcon(size: 18 * _toolScale, color: t.text), _openUpdate, tooltip: info == null ? '检查更新' : '发现新版本 v${info.version}', ); if (info == null) return btn; // 红点固定放在按钮左上角(默认是右上角,更醒目也符合「有更新」的提示习惯)。 return Badge( backgroundColor: t.danger, smallSize: 8, alignment: Alignment.topLeft, child: btn, ); } /// 打开更新对话框:已有检测结果时直接弹出,否则先检查一次。 Future _openUpdate() async { if (_checkingUpdate) return; UpdateInfo? info = _update; if (info == null) { _checkingUpdate = true; c.setStatus('正在检查更新…'); try { info = await UpdateService.check(); } catch (e) { if (mounted) c.setStatus('检查更新失败:$e'); } finally { _checkingUpdate = false; } if (!mounted) return; if (info == null) { // 没有更新的说明与安装包:明确提示当前已是最新版本。 c.setStatus('已是最新版本(v$kAppVersion)'); await showMessage(context, '检查更新', '当前已是最新版本(v$kAppVersion)。'); return; } setState(() => _update = info); } if (!mounted) return; await showDialog( context: context, // 点对话框外灰色区域不关闭(下载中防误触退出)。 barrierDismissible: false, builder: (_) => UpdateDialog(controller: c, info: info!), ); } // ===================== 工具栏(自适应 / 紧凑) ===================== /// 构建顶部工具栏:左侧为品牌与文件/编辑操作,右侧为导出、缩放、 /// 单位、侧栏开关与主题切换。根据可用宽度在完整布局与紧凑布局间切换; /// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。 Widget _toolbar(Tokens t) { final double s = _toolScale; final bool arch = c.appMode == AppMode.architecture; final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; return Container( height: 54 * s, padding: EdgeInsets.symmetric(horizontal: 6 * s), 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 = [ BrandMenuButton(controller: c, scale: s, onCommand: _handleBrandCommand), SizedBox(width: 14 * s), _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'), SizedBox(width: 6 * s), // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 6 * s), if (!arch) _aiBtn(t), if (!arch) SizedBox(width: 12 * s), if (arch) _archTools(t, false) else _segmented(t), ]; right = [ // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 _exportMenu(t), SizedBox(width: 6 * s), _zoomBox(t), SizedBox(width: 6 * s), _iconBtn(t, Icons.crop_free, arch ? c.archFit : c.fitView, tooltip: '适应视图'), if (!arch) SizedBox(width: 8 * s), if (!arch) _unitDropdown(t), if (!arch) SizedBox(width: 8 * s), sideToggleLeft, sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), _updateBtn(t), _themeToggle(t), ]; } else { // 紧凑布局:图标化 + 导出合并为菜单,尽量压缩宽度。 left = [ BrandMenuButton(controller: c, scale: s, compact: true, onCommand: _handleBrandCommand), SizedBox(width: 10 * s), _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'), SizedBox(width: 4 * s), // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 4 * s), // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 if (!arch) _aiBtn(t), if (!arch) SizedBox(width: 8 * s), if (arch) _archTools(t, true) else _segmented(t, compact: true), ]; right = [ // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 _exportMenu(t), SizedBox(width: 4 * s), _zoomBox(t), _iconBtn(t, Icons.crop_free, arch ? c.archFit : c.fitView, tooltip: '适应视图'), if (!arch) _unitDropdown(t), sideToggleLeft, sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), _updateBtn(t), _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 ViewMode mode = c.project.viewState.mode; Widget seg(String label, bool active, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), child: Container( width: (compact ? 84 : 118) * _toolScale, height: 34 * _toolScale, 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: _toolFont(12), )), ), ); } return Container( padding: EdgeInsets.all(3 * _toolScale), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line2), ), child: Row( children: [ seg('条形节拍', mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar)), seg('圆周节拍', mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular)), seg('流程图', mode == ViewMode.flow, () => c.setViewMode(ViewMode.flow)), ], ), ); } /// 架构图工具分段控件:选择 / 手绘 / 连线(草图模式显示草图状态条)。 Widget _archTools(Tokens t, bool compact) { // 草图模式:工具在左侧栏,这里显示状态与快捷退出。 if (c.sketchMode) { return Container( padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), height: 34 * _toolScale, decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.accent), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.edit_note, size: 15 * _toolScale, color: t.accent), SizedBox(width: 6 * _toolScale), Text( '参数化草图 · ${sketchToolLabel(c.sketchTool)}', style: TextStyle( color: t.accent, fontSize: _toolFont(11), fontWeight: FontWeight.w600, ), ), SizedBox(width: 10 * _toolScale), InkWell( onTap: () => c.setSketchMode(false), borderRadius: BorderRadius.circular(7), child: Container( padding: EdgeInsets.symmetric( horizontal: 8 * _toolScale, vertical: 3 * _toolScale), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line), ), child: Text('退出草图', style: TextStyle(color: t.sub, fontSize: _toolFont(10.5))), ), ), ], ), ); } final ArchTool tool = c.archTool; Widget seg(String label, IconData icon, ArchTool value, String tip) { final bool active = tool == value; return Tooltip( message: tip, child: InkWell( onTap: () => c.setArchTool(value), borderRadius: BorderRadius.circular(10), child: Container( width: (compact ? 74 : 90) * _toolScale, height: 34 * _toolScale, 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: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 15 * _toolScale, color: active ? t.accent : t.sub), SizedBox(width: 4 * _toolScale), Text(label, style: TextStyle( color: active ? t.accent : t.sub, fontWeight: active ? FontWeight.w600 : FontWeight.normal, fontSize: _toolFont(12), )), ], ), ), ), ); } return Row( mainAxisSize: MainAxisSize.min, children: [ Container( padding: EdgeInsets.all(3 * _toolScale), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line2), ), child: Row( children: [ seg('选择', Icons.near_me_outlined, ArchTool.select, '选择 / 移动 / 缩放'), seg('手绘', Icons.gesture, ArchTool.pen, c.archAutoRecognize ? '按住拖动绘制,松手自动识别' : '按住拖动绘制;画完点「识别」确认识别'), seg('连线', Icons.arrow_right_alt, ArchTool.connect, '从图形拖到另一个图形(横平竖直正交走线,角点可拖拽)'), seg('橡皮', Icons.cleaning_services_outlined, ArchTool.eraser, '擦除图形 / 墨迹 / 连线(拖动连擦,一次撤销可整体回退)'), ], ), ), SizedBox(width: 6 * _toolScale), // 「识别」确认按钮:手动模式下把待识别墨迹统一识别(自动模式下也可用)。 Container( padding: EdgeInsets.all(3 * _toolScale), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(12), border: Border.all(color: t.line2), ), child: InkWell( onTap: c.arch.strokes.isEmpty ? null : c.archRecognizeInk, borderRadius: BorderRadius.circular(9), child: Container( height: 34 * _toolScale, padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), alignment: Alignment.center, child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.auto_fix_high, size: 15 * _toolScale, color: c.arch.strokes.isEmpty ? t.dim : t.accent), SizedBox(width: 5 * _toolScale), Text( '识别(${c.arch.strokes.length})', style: TextStyle( color: c.arch.strokes.isEmpty ? t.dim : t.accent, fontSize: _toolFont(11), fontWeight: FontWeight.w600, ), ), ], ), ), ), ), ], ); } /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮(时序图 / 架构图通用)。 Widget _zoomBox(Tokens t) { final double s = _toolScale; final bool arch = c.appMode == AppMode.architecture; final double zoom = arch ? c.arch.zoom : c.project.viewState.zoom; final String pct = '${(zoom * 100).round()}%'; return Container( height: 34 * s, padding: EdgeInsets.symmetric(horizontal: 4 * s), decoration: BoxDecoration( color: t.panel, borderRadius: BorderRadius.circular(9), border: Border.all(color: t.line2), ), child: Row( children: [ _miniIcon(t, Icons.remove, () => arch ? c.archZoomBy(0.9) : c.zoomBy(0.9)), SizedBox( width: 52 * s, child: Text(pct, textAlign: TextAlign.center, style: TextStyle(color: t.text, fontSize: _toolFont(11))), ), _miniIcon(t, Icons.add, () => arch ? c.archZoomBy(1.1) : c.zoomBy(1.1)), ], ), ); } /// 缩放控件内的小图标按钮。 Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(6), child: Padding( padding: EdgeInsets.all(6 * _toolScale), child: Icon(icon, size: 15 * _toolScale, color: t.sub), ), ); } /// 时间单位下拉框:切换 ms / s / min。 Widget _unitDropdown(Tokens t) { final double s = _toolScale; return Container( height: 34 * s, padding: EdgeInsets.symmetric(horizontal: 10 * s), 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: _toolFont(11), fontWeight: FontWeight.w600), icon: Icon(Icons.keyboard_arrow_down, color: t.accent, size: 18 * s), 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 * _toolScale, height: 26 * _toolScale, 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 * _toolScale, color: active ? t.accent : t.dim), ), ); } return Container( padding: EdgeInsets.all(4 * _toolScale), 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(); }), ], ), ); } /// 导出下拉菜单:合并原「导出 SVG / 导出 PNG」两个按钮。 /// /// 选项规则(1.3 产品约定): /// - 「导出 SVG」「导出 PNG」三种视图(条形 / 圆周 / 流程图)均可用; /// - 「导出 drawio」仅在流程图视图出现(条形 / 圆周视图不提供); /// - 未授权时各项置灰(桌面无 license 不允许导出)。 Widget _exportMenu(Tokens t) { final double s = _toolScale; final bool arch = c.appMode == AppMode.architecture; final bool licensed = c.licensed; final bool flow = c.project.viewState.mode == ViewMode.flow; final Color fg = licensed ? Colors.white : t.dim; return Padding( padding: EdgeInsets.symmetric(horizontal: 3 * s), child: PopupMenuButton( tooltip: arch ? '导出(SVG / PNG / DXF)· 架构图' : '导出(SVG / PNG${flow ? ' / drawio' : ''})', color: t.panel2, position: PopupMenuPosition.under, onSelected: (String v) { if (v == 'svg') { if (arch) { _exportArchSvg(); } else { _exportSvg(); } } if (v == 'png') { if (arch) { _exportArchPng(); } else { _exportPng(); } } if (v == 'dxf' && arch) _exportArchDxf(); if (v == 'drawio') _exportDrawio(); }, itemBuilder: (BuildContext ctx) => >[ _exportItem( t, 'svg', Icons.code, '导出 SVG', arch ? '矢量图:架构图无损缩放 / 二次编辑' : '矢量图:无损缩放 / 打印 / 二次编辑', licensed), _exportItem(t, 'png', Icons.image_outlined, '导出 PNG', '位图(3840×2160):分享 / 汇报', licensed), // 架构图额外支持 DXF(AutoCAD 系软件可继续编辑)。 if (arch) _exportItem(t, 'dxf', Icons.architecture, '导出 DXF', 'AutoCAD / DraftSight 等可编辑的 CAD 图纸', licensed), // drawio 仅在流程图视图提供;其余视图不出现该项目。 if (!arch && flow) _exportItem(t, 'drawio', Icons.account_tree_outlined, '导出 drawio', 'diagrams.net 可编辑工程', licensed), ], child: Container( height: 34 * s, padding: EdgeInsets.symmetric(horizontal: 12 * s), decoration: BoxDecoration( color: licensed ? t.accent2 : t.panel2, borderRadius: BorderRadius.circular(9), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.ios_share, size: 15 * s, color: fg), SizedBox(width: 6 * s), Text('导出', style: TextStyle(fontSize: _toolFont(11), fontWeight: FontWeight.w600, color: fg)), Icon(Icons.arrow_drop_down, size: 18 * s, color: fg), ], ), ), ), ); } /// 导出菜单单项:图标 + 名称 + 一句说明;[enabled] 为 false 时整体置灰。 /// /// 菜单宽度有限(PopupMenu 默认上限约 256px),文本统一单行省略, /// 避免窄窗口 / 紧凑布局下溢出。 PopupMenuItem _exportItem( Tokens t, String value, IconData icon, String label, String hint, bool enabled) { final Color main = enabled ? t.text : t.dim; return PopupMenuItem( value: value, enabled: enabled, height: 46, child: Row( children: [ Icon(icon, size: 17, color: enabled ? t.accent : t.dim), const SizedBox(width: 10), Expanded( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)), Text(hint, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)), ], ), ), ], ), ); } /// AI 生成按钮:打开「自然语言 → 时序图」对话框;尺寸随 [_toolScale] 缩放。 /// /// AI 只服务时序图(生成条形 / 圆周视图的底层数据),流程图页置灰禁用。 Widget _aiBtn(Tokens t) { final double s = _toolScale; final bool enabled = c.project.viewState.mode != ViewMode.flow; final Widget btn = FilledButton.icon( onPressed: enabled ? () => showDialog( context: context, builder: (_) => AiGenerateDialog(controller: c), ) : null, icon: Icon(Icons.auto_awesome, size: 16 * s), label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), style: FilledButton.styleFrom( backgroundColor: enabled ? t.accent2 : t.panel2, foregroundColor: enabled ? Colors.white : t.dim, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), minimumSize: Size(0, 34 * s), tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), ); return Padding( padding: EdgeInsets.symmetric(horizontal: 3 * s), child: enabled ? btn : Tooltip(message: 'AI 生成仅针对时序图(条形 / 圆周视图)', child: btn), ); } /// 图标按钮,可附带 tooltip 与自定义颜色;尺寸随 [_toolScale] 缩放, /// 触屏平台收紧点按区域,避免默认 48dp 目标把工具栏撑满。 Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) { final double s = _toolScale; return IconButton( onPressed: onTap, icon: Icon(icon, size: 18 * s, color: onTap == null ? t.dim : (color ?? t.text)), tooltip: tooltip, splashRadius: 16 * s, padding: EdgeInsets.zero, constraints: BoxConstraints(minWidth: 34 * s, minHeight: 34 * s), // 新版 Flutter 的 IconButton 已移除 tapTargetSize 形参,改由 style 提供。 style: IconButton.styleFrom(tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null), ); } /// 自定义图标组件版按钮(用于更新按钮的矢量图标): /// 尺寸与点按区域与 [_iconBtn] 完全一致。 Widget _iconWidgetBtn(Widget icon, VoidCallback? onTap, {String? tooltip}) { final double s = _toolScale; return IconButton( onPressed: onTap, icon: icon, tooltip: tooltip, splashRadius: 16 * s, padding: EdgeInsets.zero, constraints: BoxConstraints(minWidth: 34 * s, minHeight: 34 * s), style: IconButton.styleFrom(tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null), ); } // ===================== 侧栏停靠状态机(钉住 / 悬浮 / 轨道) ===================== /// 侧栏标题栏控制按钮:切换钉住状态与隐藏侧栏。 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 (Platform.isAndroid || Platform.isIOS) { // 触屏平台:点把手直接停靠展开(无悬停概念)。 _leftPinned = true; } else if (!_leftPinned) { _leftHover = true; } } else { _rightVisible = true; if (Platform.isAndroid || Platform.isIOS) { _rightPinned = true; } else 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), ); } // ===================== 左侧栏内容 ===================== /// 架构图左侧栏容器(手绘识别 / 图形库 / 颜色 / 示例场景)。 Widget _archLeftPanel(Tokens t, {bool floating = false}) { return Container( width: _leftPanelWidth, 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: 10), ArchLeftBody(controller: c), ], ), ), ); } /// 架构图右侧栏容器(选中对象属性)。 Widget _archRightPanel(Tokens t, {bool floating = false}) { return Container( width: _rightPanelWidth, 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: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), child: ArchRightBody(controller: c), ), ), ], ), ); } /// 构建左侧栏:项目概览、动作/工位列表、视图模式、显示选项、 /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 Widget _leftPanel(Tokens t, {bool floating = false}) { // 架构图模块使用独立的左侧栏(图形库 / 识别开关 / 示例)。 if (c.appMode == AppMode.architecture) { return _archLeftPanel(t, floating: floating); } final bool bar = c.project.viewState.mode == ViewMode.bar; final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( width: _leftPanelWidth, 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), _editEntry( t, icon: Icons.edit_note, label: '文档设置', enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => SettingsDialog(controller: c), ), ), // 较浅的分隔横线,区分上方「文档设置」与下方「动作和执行编辑」。 const SizedBox(height: 14), Divider(height: 1, thickness: 1, color: t.line), const SizedBox(height: 14), Row( children: [ // 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。 Expanded(child: _sectionLabel(t, '动作和执行编辑')), _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, flow ? null : () => c.addAction(startAngle: 0)), const SizedBox(width: 6), // 至少保留一个动作 / 泳道:只剩一个时禁用删除;流程图只读时禁用。 _headerAction( t, Icons.delete_outline, '删除', t.danger, Colors.white, (flow || c.selectedId == null || c.project.actions.length <= 1) ? null : () => c.deleteAction(c.selectedId!), ), ], ), const SizedBox(height: 8), // 按泳道 / 轨道分组:同一泳道内的多个动作合并显示(最多两行,/ 分隔)。 ..._laneRows(t, bar), const SizedBox(height: 8), // 工位 / 相位分区管理入口,同属「动作和执行编辑」区域。 // 工位:一个流程可包含多个工位,可增删改与排序。 _editEntry( t, icon: Icons.precision_manufacturing_outlined, label: '编辑工位', badge: c.project.stations.length, enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => StationDialog(controller: c), ), ), const SizedBox(height: 8), // 相位分区:可任意增删、改名、改起止角;流程图只读时置灰。 _editEntry( t, icon: Icons.tune, label: '编辑相位分区', badge: c.project.phaseZones.length, enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => PhaseZoneDialog(controller: c), ), ), const SizedBox(height: 12), _sectionLabel(t, '视图模式'), const SizedBox(height: 8), // 该栏永久只保留条形 / 圆周两个时序视图的切换; // 流程图由时序图生成、属独立载体,入口在顶部工具栏(不在本栏混排)。 Row( children: [ Expanded(child: _modeButton(t, '条形节拍(甘特)', c.project.viewState.mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar))), const SizedBox(width: 8), Expanded(child: _modeButton(t, '圆周节拍(同心)', c.project.viewState.mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular))), ], ), const SizedBox(height: 12), _sectionLabel(t, '显示选项'), const SizedBox(height: 6), ..._displayOptions(t, bar), 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), // 提示随视图模式切换:流程图是只读预览,给出交互方式说明。 if (flow) ...[ Text('流程图只读:点击节点可选中对应动作', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('滚轮缩放 · 拖拽平移 · Ctrl+滚轮连续缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), Text('需要修改请切回条形 / 圆周视图', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), ] else ...[ 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.text2, fontSize: 11.5, letterSpacing: 1.2, fontWeight: FontWeight.w600), ); /// 侧栏中的“单行编辑入口”卡片:图标 + 文案 + 可选计数徽标 + 右箭头。 /// /// 用于把复杂的设置模块收敛为一个点击即可进入的入口。 /// [enabled] 为 false 时整体置灰(流程图只读视图下禁用编辑入口)。 Widget _editEntry( Tokens t, { required IconData icon, required String label, required VoidCallback onTap, int? badge, bool enabled = true, }) { final Widget card = InkWell( onTap: enabled ? onTap : null, borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Row( children: [ Icon(icon, size: 16, color: enabled ? t.accent : t.dim), const SizedBox(width: 8), Expanded(child: Text(label, style: TextStyle(color: enabled ? t.text2 : t.dim, fontSize: 12))), if (badge != null) ...[ Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), decoration: BoxDecoration( color: enabled ? t.accent.withValues(alpha: 0.14) : t.line.withValues(alpha: 0.35), borderRadius: BorderRadius.circular(6), ), child: Text('$badge', style: TextStyle( color: enabled ? t.accent : t.dim, fontSize: 10.5, fontWeight: FontWeight.w700)), ), const SizedBox(width: 4), ], Icon(Icons.chevron_right, size: 16, color: t.dim), ], ), ), ); if (enabled) return card; return Tooltip(message: '流程图只读:修改请切回条形 / 圆周视图', child: card); } /// 左侧栏的泳道槽位小徽标:显示当前槽位数,点击可调整(1–5 槽)。 /// /// 槽位数 > 1 时高亮显示(多槽位泳道内动作按子行并列放置)。 Widget _laneSlotChip(Tokens t, int lane) { final int n = c.project.slotsOf(lane); return Builder( builder: (BuildContext ctx) => Tooltip( message: '泳道 L${lane + 1} 槽位数:$n(点击调整,最多 5)', child: InkWell( borderRadius: BorderRadius.circular(6), onTap: () async { final RenderBox box = ctx.findRenderObject()! as RenderBox; await showLaneSlotMenu(context, c, box.localToGlobal(Offset.zero), lane); }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: n > 1 ? t.accent.withValues(alpha: 0.14) : t.panel2, borderRadius: BorderRadius.circular(6), border: Border.all(color: n > 1 ? t.accent.withValues(alpha: 0.4) : t.line2), ), child: Text('$n 槽', style: TextStyle(color: n > 1 ? t.accent : t.dim, fontSize: 10)), ), ), ), ); } /// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。 /// /// [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 = c.project.renderLanes; 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)); // 空泳道(开启「保留空泳道」后动作被全部移走):显示占位行。 if (acts.isEmpty) { out.add(_emptyLaneRow(t, lane, li)); continue; } // 单动作泳道沿用普通动作行;多动作泳道合并显示。 out.add(acts.length == 1 ? _actionRow(t, acts.first, li, bar) : _laneRow(t, lane, li, acts, bar)); } return out; } /// 左侧栏中的空泳道占位行(开启「保留空泳道」后,动作被全部移走的泳道)。 Widget _emptyLaneRow(Tokens t, int lane, int li) { return Padding( padding: const EdgeInsets.only(bottom: 6), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Row( children: [ Container( width: 22, height: 22, decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(6), border: Border.all(color: t.line2), ), alignment: Alignment.center, child: Text('${li + 1}', style: TextStyle(color: t.dim, fontSize: 11, fontWeight: FontWeight.w700)), ), const SizedBox(width: 9), Expanded( child: Text('空泳道(已保留,可拖入动作)', style: TextStyle(color: t.dim, fontSize: 11)), ), _laneSlotChip(t, lane), ], ), ), ); } /// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。 Widget _laneRow(Tokens t, int lane, int li, List acts, bool bar) { if (acts.isEmpty) return const SizedBox.shrink(); final bool flow = c.project.viewState.mode == ViewMode.flow; 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, ), // 双击泳道行直接编辑该泳道的主动作(流程图只读时禁用)。 onDoubleTap: flow ? null : () => showDialog( context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), 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: math.max(2, c.project.slotsOf(lane)), 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), Flexible( child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.sub, fontSize: 11), ), Text('${acts.length} 个动作', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), ], ), ), const SizedBox(width: 6), _laneSlotChip(t, lane), const SizedBox(width: 4), InkWell( onTap: flow ? null : () => 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: flow ? t.line2 : (sel ? t.accent : t.dim)), ), ), ], ), ), ), ); } /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 Widget _actionRow(Tokens t, Action a, int i, bool bar) { final bool flow = c.project.viewState.mode == ViewMode.flow; 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, ), // 双击动作行直接进入编辑(流程图只读时禁用)。 onDoubleTap: flow ? null : () => showDialog( context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), 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}' '${c.project.slotsOf(a.layer) > 1 ? ' · 槽 ${effectiveSlot(c.project, a) + 1}' : ''}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), ], ), ), const SizedBox(width: 6), Flexible( child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( bar ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' : 'L${a.layer + 1}', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.sub, fontSize: 10), ), Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), ], ), ), const SizedBox(width: 6), _laneSlotChip(t, a.layer), const SizedBox(width: 4), InkWell( onTap: flow ? null : () => 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: flow ? t.line2 : (sel ? t.accent : t.dim)), ), ), // 选中该动作时才出现删除入口;至少保留一个动作 / 泳道;流程图只读时隐藏。 if (sel && !flow && c.project.actions.length > 1) ...[ 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}) { // 架构图模块使用独立的右侧栏(选中对象属性)。 if (c.appMode == AppMode.architecture) { return _archRightPanel(t, floating: floating); } final Action? a = c.selected; final bool bar = c.project.viewState.mode == ViewMode.bar; final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( width: _rightPanelWidth, 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), // 流程图只读提示:节点与连线自动生成,编辑请回时序视图。 if (flow) ...[ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.info, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Icon(Icons.lock_outline, size: 15, color: t.warn), const SizedBox(width: 8), Expanded( child: Text('流程图只读:节点与连线由时序图自动生成,修改请切回条形 / 圆周视图。', style: TextStyle(color: t.sub, fontSize: 10.5, height: 1.55)), ), ], ), ), const SizedBox(height: 12), ], ..._propertyFields(t, a, bar), const SizedBox(height: 10), if (!bar) ...[ _sectionLabel(t, '角度编辑'), const SizedBox(height: 8), // 流程图只读:滑块仅展示数值,不可拖动。 Opacity( opacity: flow ? 0.45 : 1, child: IgnorePointer( ignoring: flow, child: Column( children: [ _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), ], 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, enabled: !flow), const SizedBox(height: 6), OutlinedButton.icon( onPressed: flow ? null : () => 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, enabled: !flow), 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), ), ], ), ); } /// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。 /// /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 Widget _depRow(Tokens t, Action a, Dependency d, {bool enabled = true}) { 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: enabled ? () => c.removeDependency(d.fromId, a.id) : null, child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), ), ], ), ); } /// 输出依赖展示行:本动作 [a] 作为前置指向 [target],可删除。 /// /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 Widget _outDepRow(Tokens t, Action a, Action target, Dependency d, {bool enabled = true}) { 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: enabled ? () => c.removeDependency(a.id, target.id) : null, child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), ), ], ), ); } /// 右侧栏底部的帮助与快捷键提示卡片。 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) { // 架构图模式:状态栏展示架构图统计与工具。 if (c.appMode == AppMode.architecture) return _archStatusBar(t); final UnitSettings u = c.project.units; final ViewMode mode = c.project.viewState.mode; final bool circular = mode == ViewMode.circular; final List items = [ '循环周期 ${tfmt(c.project.cycle.durationMs, u)}', '相位 360° = 100%', '动作 ${c.project.actions.length}', '依赖 ${_depCount()}', circular ? '轨道 L1–L${c.project.renderLaneCount}' : '工位 ${c.project.stations.length}', mode == ViewMode.flow ? '泳道 L1–L${c.project.renderLaneCount}(流程节点 ${c.project.actions.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)), ], ), ); } /// 架构图状态栏:元素统计 / 当前工具 / 缩放 / 状态消息。 Widget _archStatusBar(Tokens t) { final ArchDoc doc = c.arch; final String toolLabel = c.sketchMode ? '草图·${sketchToolLabel(c.sketchTool)}' : switch (c.archTool) { ArchTool.select => '选择', ArchTool.pen => c.archAutoRecognize ? '手绘识别' : '手绘(待确认)', ArchTool.connect => '连线', ArchTool.eraser => '橡皮', }; final List items = [ c.sketchMode ? '参数化草图' : '架构图模式', if (c.sketchMode) ...[ '实体 ${doc.sketch.entities.length}', '约束 ${doc.sketch.constraints.where((SketchConstraint k) => !k.internal).length}', '尺寸 ${doc.sketch.dims.length}', '自由度 ${sketchDofCount(doc.sketch)}', ] else ...[ '元件 ${doc.shapes.length}', '连线 ${doc.connectors.length}', '墨迹 ${doc.strokes.length}', '图层 ${doc.layerById(doc.activeLayer).name}', ], '工具 $toolLabel', if (!c.sketchMode && c.archOrtho) '正交 开', if (!c.sketchMode && c.archPolar) '极轴 ${c.archPolarDeg.round()}°', '缩放 ${(doc.zoom * 100).round()}%', 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)), ], ), ); } }