From 6cfa79507c39a68b3df04b0663631b0f7eb047e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=86=E5=A4=B4=E9=B9=85?= Date: Fri, 18 Sep 2026 16:50:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20V1.0.0=20=E5=8F=91=E5=B8=83=EF=BC=88?= =?UTF-8?q?=E5=91=86=E5=A4=B4=E9=B9=85=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 默认浅色白底主题;字体整数化 + Microsoft YaHei UI 提升清晰度 - 相位分区:圆周/条形显示、沿弧排列、拖拽边界(虚线参考+弱吸附)、增删改(对话框/右键/双击) - 动作:Ctrl 多选批量对齐;上下拖拽自由换行;左右端拖拽改起止(虚线+弱吸附+左右箭头光标) - 动作编辑支持角度与时间双向换算 - 圆周顺时针箭头移至刻度环外;条形左侧标题列收窄 - 侧栏可隐藏/钉住;适应视图按内容自适应;节拍统计改为按钮弹窗 - AI 生成时序图(DeepSeek,Flash/Pro,推理强度),基于 dart:io 无插件 - 窗口标题显示文件名/未命名文件;关于信息(设计人/版本/版权) - 全量中文注释、docs/ARCHITECTURE.md、docs/HELP.md(按任务组织) - 构建脚本输出到 dist/,并附带 dist 生成物 --- .gitignore | 2 + .metadata | 30 + BUILD-NOTES.md | 99 + README.md | 44 + analysis_options.yaml | 33 + demo/app-icon.png | Bin 0 -> 17641 bytes docs/ARCHITECTURE.md | 362 ++++ docs/HELP.md | 301 +++ lib/ai/ai_client.dart | 185 ++ lib/export/svg_writer.dart | 333 +++ lib/layout/layout.dart | 264 +++ lib/main.dart | 161 ++ lib/model/models.dart | 937 +++++++++ lib/model/units.dart | 151 ++ lib/persistence/storage.dart | 235 +++ lib/render/bar_painter.dart | 549 +++++ lib/render/circular_painter.dart | 591 ++++++ lib/state/app_controller.dart | 836 ++++++++ lib/theme/tokens.dart | 333 +++ lib/ui/ai_dialog.dart | 280 +++ lib/ui/app_logo.dart | 88 + lib/ui/app_shell.dart | 1849 +++++++++++++++++ lib/ui/canvas_overlays.dart | 899 ++++++++ lib/ui/canvas_view.dart | 569 +++++ lib/ui/dialogs.dart | 1355 ++++++++++++ pubspec.lock | 277 +++ pubspec.yaml | 89 + scripts/build.bat | 32 + scripts/run.bat | 13 + scripts/setup-cmake.bat | 23 + test/model_test.dart | 60 + test/widget_test.dart | 59 + tools/gen-icon.py | 142 ++ windows/.gitignore | 17 + windows/CMakeLists.txt | 108 + windows/flutter/CMakeLists.txt | 109 + .../flutter/generated_plugin_registrant.cc | 11 + windows/flutter/generated_plugin_registrant.h | 15 + windows/flutter/generated_plugins.cmake | 23 + windows/runner/CMakeLists.txt | 46 + windows/runner/Runner.rc | 121 ++ windows/runner/flutter_window.cpp | 108 + windows/runner/flutter_window.h | 39 + windows/runner/main.cpp | 54 + windows/runner/resource.h | 16 + windows/runner/resources/app_icon.ico | Bin 0 -> 47579 bytes windows/runner/runner.exe.manifest | 14 + windows/runner/utils.cpp | 69 + windows/runner/utils.h | 19 + windows/runner/win32_window.cpp | 288 +++ windows/runner/win32_window.h | 102 + 51 files changed, 12340 insertions(+) create mode 100644 .metadata create mode 100644 BUILD-NOTES.md create mode 100644 analysis_options.yaml create mode 100644 demo/app-icon.png create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/HELP.md create mode 100644 lib/ai/ai_client.dart create mode 100644 lib/export/svg_writer.dart create mode 100644 lib/layout/layout.dart create mode 100644 lib/main.dart create mode 100644 lib/model/models.dart create mode 100644 lib/model/units.dart create mode 100644 lib/persistence/storage.dart create mode 100644 lib/render/bar_painter.dart create mode 100644 lib/render/circular_painter.dart create mode 100644 lib/state/app_controller.dart create mode 100644 lib/theme/tokens.dart create mode 100644 lib/ui/ai_dialog.dart create mode 100644 lib/ui/app_logo.dart create mode 100644 lib/ui/app_shell.dart create mode 100644 lib/ui/canvas_overlays.dart create mode 100644 lib/ui/canvas_view.dart create mode 100644 lib/ui/dialogs.dart create mode 100644 pubspec.lock create mode 100644 pubspec.yaml create mode 100644 scripts/build.bat create mode 100644 scripts/run.bat create mode 100644 scripts/setup-cmake.bat create mode 100644 test/model_test.dart create mode 100644 test/widget_test.dart create mode 100644 tools/gen-icon.py create mode 100644 windows/.gitignore create mode 100644 windows/CMakeLists.txt create mode 100644 windows/flutter/CMakeLists.txt create mode 100644 windows/flutter/generated_plugin_registrant.cc create mode 100644 windows/flutter/generated_plugin_registrant.h create mode 100644 windows/flutter/generated_plugins.cmake create mode 100644 windows/runner/CMakeLists.txt create mode 100644 windows/runner/Runner.rc create mode 100644 windows/runner/flutter_window.cpp create mode 100644 windows/runner/flutter_window.h create mode 100644 windows/runner/main.cpp create mode 100644 windows/runner/resource.h create mode 100644 windows/runner/resources/app_icon.ico create mode 100644 windows/runner/runner.exe.manifest create mode 100644 windows/runner/utils.cpp create mode 100644 windows/runner/utils.h create mode 100644 windows/runner/win32_window.cpp create mode 100644 windows/runner/win32_window.h diff --git a/.gitignore b/.gitignore index b0ab185..9f09d80 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,9 @@ build/ *.iml .idea/ .vscode/ +# 保留 pubspec.lock 以便复现构建(应用工程应提交) *.lock +!pubspec.lock # Node node_modules/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..61ff721 --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "9584c6713b324636289d067944a46fd6b49df14b" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9584c6713b324636289d067944a46fd6b49df14b + base_revision: 9584c6713b324636289d067944a46fd6b49df14b + - platform: windows + create_revision: 9584c6713b324636289d067944a46fd6b49df14b + base_revision: 9584c6713b324636289d067944a46fd6b49df14b + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/BUILD-NOTES.md b/BUILD-NOTES.md new file mode 100644 index 0000000..1a03151 --- /dev/null +++ b/BUILD-NOTES.md @@ -0,0 +1,99 @@ +# 构建说明(含绿盾 / 透明加密环境的规避) + +本项目是 Flutter Windows 桌面应用。常规环境直接: + +```bash +flutter pub get +flutter build windows --release +``` + +但在**安装了绿盾(Tipray LdTerm)等透明加密 DLP** 的机器上,编译会遇到两个问题, +本文记录现象、根因与规避方法。 + +--- + +## 现象 + +1. **CMake 配置失败** + + ``` + CMake Error at .../CMakeFiles/4.3.1-msvc1/CMakeSystem.cmake:1: + Parse error. Expected a command name, got bad character with text "..." + ``` + + 即使是最小 CMake 工程也会复现;生成的 `CMakeSystem.cmake` 变成 4491 字节的乱码 + (正常约 200–400 字节纯文本)。 + +2. **链接失败** + + ``` + \\?\C:\Users\...\Temp\lnk{...}.tmp : general error c1010070: + Failed to load and parse the manifest. + LINK : fatal error LNK1327: 运行 mt.exe 期间出错 + ``` + +## 根因 + +绿盾按**进程名**对“受控程序”创建的文件做透明加密: + +- `cmake.exe` 写出的 `CMakeSystem.cmake` 被加密,CMake 随后读取到密文 → 解析失败; +- `link.exe` 写出的临时清单 `lnk{...}.tmp` 被加密,`mt.exe` 读取到密文 → LNK1327。 + +实验证明:把 `cmake.exe` **重命名**为任意其它名字后,同样的配置流程生成的文件就是正常明文, +说明绿盾是按可执行文件名匹配策略的。 + +## 规避方法(已内置到本仓库) + +### 1. 复制并重命名 CMake + +```powershell +$src = "C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake" +robocopy $src "E:\cmake-lv" /E +Copy-Item "E:\cmake-lv\bin\cmake.exe" "E:\cmake-lv\bin\cmk2.exe" +``` + +> 必须复制**整个 CMake 目录**(含 `share/cmake-*`),否则找不到内置模块。 + +### 2. 让 Flutter 使用该副本 + +Flutter 默认硬编码使用 Visual Studio 自带的 CMake。本仓库对 Flutter 工具打了一个 +向后兼容的小补丁:`visual_studio.dart` 的 `cmakePath` getter 支持环境变量覆盖。 + +设置环境变量即可: + +```powershell +$env:FLUTTER_CMAKE_PATH = "E:\cmake-lv\bin\cmk2.exe" +``` + +### 3. 禁用清单嵌入(绕开 mt.exe) + +`windows/runner/CMakeLists.txt` 中: + +```cmake +target_link_options(${BINARY_NAME} PRIVATE "/MANIFEST:NO") +add_custom_command(TARGET ${BINARY_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/runner.exe.manifest" + "$/${BINARY_NAME}.exe.manifest") +``` + +清单改为**外部文件**方式随 exe 一同输出,不再调用 `mt.exe`。 + +### 4. 完整构建命令 + +```powershell +$env:FLUTTER_STORAGE_BASE_URL = "https://storage.flutter-io.cn" +$env:PUB_HOSTED_URL = "https://pub.flutter-io.cn" +$env:FLUTTER_CMAKE_PATH = "E:\cmake-lv\bin\cmk2.exe" +flutter build windows --release +``` + +--- + +## 其它环境备注 + +- **项目路径不要包含中文**。CMake 对非 ASCII 路径兼容性差,建议放在纯英文路径下。 +- **无管理员权限**时无法创建符号链接,因此本项目**不引入任何原生插件** + (不使用 `path_provider` / `file_selector`)。应用数据目录通过 + `%APPDATA%` 环境变量获取,文件打开/保存使用自研的应用内文件浏览器。 +- 国内网络请使用上述 Flutter/Pub 镜像。 diff --git a/README.md b/README.md index ac0f541..6faf70a 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,38 @@ - **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致 - **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES +## 试用(测试版) + +已按设计文档落地**可运行的 Flutter Windows 桌面测试版**(源码在 `lib/`)。 + +**运行 / 构建** + +```bash +flutter pub get +flutter run -d windows # 开发调试 +scripts\build.bat # 发布版(构建并复制到浅目录 dist\) +``` + +产物:`dist\sequence_diagram.exe`(直接 `flutter build windows --release` 则在 `build\windows\x64\runner\Release\`) + +**已实现功能** + +- 条形节拍(甘特 / 流程图)+ 圆周节拍(同心圆)双视图,**共享同一份数据**,顶部一键切换 +- FS 严格顺序(绿色实线)/ SS 并行重叠(琥珀虚线)依赖箭头 + ★ 关键路径高亮 +- 拖拽编辑相位、拖端点改持续角、`Shift`+拖拽改层、双击空白新建动作(默认最外层) +- 右侧属性面板:角度滑杆、依赖增删、复制 / 对齐 / 改层 / 删除 +- 工艺参数面板(`F2`):`ms/s/min`、`°/%`、显示精度、换算表、吸附与网格 +- 深 / 浅双主题(`F3`);`Ctrl+滚轮` 缩放、`Ctrl+Z/Y` 撤销重做 +- **左右侧栏可隐藏 / 显示,并可钉住**:钉住时固定占位,取消钉住后悬浮、鼠标移开自动收起 +- 画布浮层:标题、图例、选中动作卡、节拍统计、编辑工具、实时预览(按窗口宽度自适应取舍) +- **导出 SVG**:分层、带语义 `id` 与 `data-*` 元数据,可直接进工艺卡 / MES +- **导出 PNG**:按 2 倍像素比导出当前画布 +- **自动定时快照 + 启动崩溃恢复 + `.bak` 备份**(异常退出后可恢复) +- 应用内帮助中心(`F1`)与 [`docs/HELP.md`](docs/HELP.md) +- 时钟 / 周期盘图标(`tools/gen-icon.py` 生成) + +> 若本机装有绿盾等透明加密软件,构建前请阅读 [`BUILD-NOTES.md`](BUILD-NOTES.md)(含规避方案)。 + ## 设计预览(2560 × 1440) **圆周节拍视图**(同心圆 · 12 点钟起始 · 顺序箭头) @@ -31,6 +63,10 @@ | 路径 | 说明 | | --- | --- | +| [`lib/`](lib/) | **测试版源码**:模型 / 状态 / 布局 / 渲染 / 导出 / 持久化 / UI | +| [`docs/HELP.md`](docs/HELP.md) | 使用帮助:快速开始、界面与侧栏、快捷键、双视图、单位、导出、崩溃恢复 | +| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | **架构文档**:模块依赖、数据流、关键算法、性能分析与优化点 | +| [`BUILD-NOTES.md`](BUILD-NOTES.md) | 构建说明与绿盾(透明加密)环境的规避方法 | | [`docs/DESIGN.md`](docs/DESIGN.md) | 完整设计文档:需求、技术选型、数据模型、单位体系、布局算法、SVG 导出、配色规范、里程碑、风险 | | `demo/*.svg` | 设计示例图源文件(矢量,可直接编辑,含深/浅两套) | | `demo/*.png` | 2K(2560×1440)预览图 | @@ -54,3 +90,11 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模 - [ ] M2 圆周视图 + 双视图切换动画 + 拖拽吸附 + 属性面板 + 撤销重做 - [ ] M3 SVG / PNG 导出 + 依赖编辑 + 关键路径与统计 + 深浅主题 + Golden 测试 - [ ] M4 PLC 点位对接(OPC UA / 三菱 MC / Modbus)+ 工艺卡 PDF + 自动节拍优化 + +## 关于 + +- **软件**:时序图工作台 · Sequence Diagram Studio +- **设计人**:呆头鹅 +- **版本**:V1.0.0 +- **版权**:Copyright © 2026 呆头鹅。保留所有权利。 +- **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md) diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..cb1e3ab --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,33 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - windows/** + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/demo/app-icon.png b/demo/app-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..0adbcc108e4525b950d0433936241f29f3bb004c GIT binary patch literal 17641 zcmdVCd0dSB_dkBFYi6pMqD2&KqlF4dwk$QHBoaahVaR%0ib$d6DkW=WFG~$kp<5y3 zw#-$QvX+~>Y-tke);6?_nwjf&uHK)|=kfXd9>2%;|L^?4_1eyPE$8)mo%1~B)xLn4 zzP$tk1OU)$+SJK&0J!+c1w9@7Pii$}H^AilX_F@fMxJS^nsN1P<+eeRX8||H58^y3 z;4Hp+J!JGJ*NNn|=Y4YcZ{hM4w0|Vxxa?)x^OkB z<=gMyuf}zU{@Ff}N(nlj6FxjDvZK5CW@qPDKC=72_!r#Lr+Q*(t*?mr($rW9@b%Y^ zD`svS`vMb4y98i9wOkh>r;dPHN09YdZUc((enh=D z0f+R|0MU+ISuY;g3)IYSo8fEZTo9(UXq(o|nxAPzH8_G$tT1aNsDEA#6_}Fw$t3jS ztGzrS<)8X3;(?Ip1d_0Nvo->r^yNGQm6#Amd3ek74IzJ~lgvOio(B%?dYWQS5TBVN z?l1Ncz_YbhUA!2eEE6a<%Gney3~J-R*DM1{gWqqRRUg0ULe4_HRDsZr2kZ1S0H3lA zs6j1GAk#&!=7&WDcv~ zxFbxpQ8yur^1B9Dmn(o1gH#-FJ!MPfB13^TqMLxAa|W))^nOzq>Z8;JiO+s;3xIrX zkquCKro`kd5C$v9em4a1TQ~YOteyj|2?|X0+Yjdh!1WmWJ%2yU&j!hRW$0UMCGep_ zh=b=rHi4zF-;~ImLWsx4i2xkQphS}Tx28G=6Mci-j1@uP;RtK}kTLbflz4%S__bPq z{ETiQbrM0pZ0y3}Zu9539wDhKd@L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W zM;Itn-Eii?^pjwLugpLgf>ufu%fkO0Ru$?OWjNyZMfTgdC}S=DX@Oznm?T|1NOsg$ zo42pw;U5V&kEId}l0bDj=!h+@ImV-`JP*QE#`&8kV)8Ivq;E5hB`9 zv`ra{)Hvt<9b=`PQAaa;m4o#$#=;3@=MR&v8h0LCy6H?dr=nxHw7;t5UDIHU{9WaU z#aoQJYQ`hl{l^lW4gNTSM|x_D37WtQAiHP1inh9lGp5d$`qpQoN^aoHX?DckbtP&h zc!|)9L+x8dNAD*hDwlKC}M6`A2tHp)=-%a?|2u3-%&`X+AS2U-gp2{Xb<(l%D_q literal 0 HcmV?d00001 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..1a7beeb --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,362 @@ +# 架构文档 · 时序图工作台(Sequence Diagram Studio) + +> 面向 PLC 流程节拍 / 相位角设计的 Flutter Windows 桌面软件。 +> 本文档描述代码结构、数据流、关键算法与**可优化点**,供后续性能与体验优化使用。 + +--- + +## 1. 产品定位与核心概念 + +- **一份数据,两种视图**:条形节拍(甘特 / 流程图)⇄ 圆周节拍(同心圆相位图)。 +- **循环 = 一圈**:一个生产循环固定映射为 `360°` 与 `100%`;模型内部时间恒以**毫秒**存储。 +- **相位角**:`angle(deg) = ms / cycleMs × 360`,圆周图以 **12 点钟为 0°、顺时针**递增。 +- **动作分层**:每个动作占一条同心圆环,半径 `r = R0 + layer × pitch`;新增动作默认落在最外层。 +- **依赖约束**:`FS`(完成-启动,绿色实线)/ `SS`(起始-起始,琥珀虚线),用于关键路径计算。 + +--- + +## 2. 技术栈与工程约束 + +| 项 | 选型 | +| --- | --- | +| UI 框架 | Flutter 3.x(Desktop, Windows) | +| 渲染 | `CustomPainter` 自绘(无第三方图表库) | +| 状态 | `ChangeNotifier`(`AppController`)+ 局部 `setState` | +| 模型 | 不可变类 + `copyWith` / `toJson` / `fromJson` | +| 持久化 | 纯 `dart:io` 读写 JSON(`.seq.json`) | +| 导出 | 自研 SVG 序列化器 + `RepaintBoundary.toImage` 导出 PNG | +| 主题 | Token 化(`Tokens`),深/浅两套 | + +**硬性约束** + +1. **不引入任何原生插件**(无 `path_provider` / `file_selector`)。 + 原因:无管理员权限无法创建符号链接,Windows 插件会引入 symlink 步骤。 + 因此:应用数据目录用 `%APPDATA%` 环境变量自行拼装;文件打开/保存用**应用内自研文件浏览器**。 +2. **项目路径不含中文**(CMake 对非 ASCII 路径兼容性差)。 +3. **透明加密(绿盾)规避**:见 `BUILD-NOTES.md`(CMake 重命名副本 + `/MANIFEST:NO`)。 +4. 窗口默认按主屏 **94%** 打开(`windows/runner/main.cpp`),保证面板不越出屏幕。 + +--- + +## 3. 目录结构与依赖方向 + +``` +lib/ +├── main.dart # 启动:Storage.init → AppController.start → MaterialApp +├── model/ +│ ├── models.dart # 领域模型 + JSON 协议(单一事实来源,不依赖 UI/持久化) +│ └── units.dart # 单位换算、格式化、解析、吸附/归一化 +├── layout/ +│ └── layout.dart # 纯几何:条形布局、圆周布局、极坐标/弧/命中测试 +├── state/ +│ └── app_controller.dart # 唯一可变状态 + 撤销栈 + 关键路径 + 自动保存 +├── render/ +│ ├── bar_painter.dart # 条形视图绘制 +│ └── circular_painter.dart# 圆周视图绘制 +├── export/ +│ └── svg_writer.dart # SVG 序列化(分层 + data-* 元数据) +├── persistence/ +│ └── storage.dart # 快照 / .bak / 读写文件 +├── theme/ +│ └── tokens.dart # 颜色与主题 Token +└── ui/ + ├── app_shell.dart # 三栏外壳:工具栏 / 侧栏 / 状态栏 / 快捷键 + ├── canvas_view.dart # 画布手势层(选择 / 拖拽 / 缩放 / 平移 / 右键) + ├── canvas_overlays.dart # 画布浮层(标题 / 图例 / 统计 / 预览 / 浮动工具条) + ├── dialogs.dart # 文件浏览器 / 动作编辑 / 依赖编辑 / 工艺参数 / 帮助 + └── app_logo.dart # 时钟徽标(与 .ico 同源) +``` + +**依赖方向(单向,无环)** + +``` +model ◄── layout ◄── render + ▲ ▲ ▲ + │ │ │ +state ──────┴──── export + ▲ + │ +ui ──► theme +``` + +- `model` 是最底层,不依赖任何其它模块。 +- `state` 只依赖 `model` + `persistence`。 +- `render` 依赖 `model` + `layout` + `theme`(纯绘制,无状态)。 +- `ui` 依赖以上全部,负责交互与组合。 + +--- + +## 4. 数据模型(`model/models.dart`) + +### 4.1 实体 + +| 类型 | 说明 | +| --- | --- | +| `Project` | 聚合根:名称、`schema`、`Cycle`、`Station[]`、`Action[]`、`UnitSettings`、`ViewState` | +| `Action` | `id / name / stationId / driver / startAngle / durationAngle / layer / color / deps[]` | +| `Dependency` | `fromId / toId / type(FS/SS/FF/SF) / offsetAngle` | +| `Station` | `id / name / order / color` | +| `Cycle` | `durationMs / startAngle / direction(cw/ccw) / origin(twelve/three) / snapDeg` | +| `UnitSettings` | 时间/相位单位、精度、吸附、显示选项(网格、跨圈拆分等) | +| `ViewState` | 视图模式、缩放、平移、显示开关(依赖/刻度/相位分区/圆环背景/层标注)、选中 id | + +### 4.2 关键设计 + +- **不可变**:所有字段 `final`,更新一律通过 `copyWith`,配合撤销栈实现历史快照。 +- **只存角度**:时间由 `cycleMs` 实时换算,避免单位切换带来的精度漂移。 +- **跨圈判定**:`Action.wrap => endAngle > 360.0001`;渲染时拆成 `[θ0,360]` 与 `[0,θ1-360]` 两段。 +- **JSON 协议**:`schema: "seqdiagram/1.2"`,`Project.encode()` 带缩进便于 diff; + `fromJson` 对缺失字段有默认值,保证向后兼容。 +- **单位只是显示偏好**:切换 `ms/s/min`、`°/%` 不修改任何模型数值。 + +--- + +## 5. 状态与业务逻辑(`state/app_controller.dart`) + +`AppController extends ChangeNotifier`,是整个应用唯一的可变状态源。 + +### 5.1 职责 + +- 持有当前 `Project`、主题 `brightness`、文件路径、脏标记、状态栏文案。 +- **撤销 / 重做**:`_undo` / `_redo` 两个 `List` 栈(上限 200), + `_mutate()` 统一入栈并触发 `_recomputeCritical()` 与 `notifyListeners()`。 +- **编辑 API**:`addAction / deleteAction / duplicateSelected / setActionStart / setActionDuration / changeLayer / setLayer / addDependency / removeDependency / alignPhase`。 +- **视图 API**:`setViewMode / setZoom / zoomBy / panBy / resetView / fitView / setViewFlag / toggleDeps`。 +- **单位 API**:`setUnits / setCycleDuration`。 +- **持久化**:`save / saveAs / loadProject / newProject`,以及 5 秒一次的 `_autosave`。 + +### 5.2 关键路径算法(`_recomputeCritical`) + +用于高亮“累计最长链”。步骤: + +1. 由 `Action.deps` 建图,统计入度 `indeg` 与后继表 `succ`。 +2. **Kahn 拓扑排序**;若存在环(`topo.length != n`)则退化为原始顺序,保证不崩。 +3. 按拓扑序计算每个动作的**最早开始角** `earliest`,并按依赖类型取约束: + - `FS`:`predEnd + offset` + - `SS`:`earliest[pred] + offset` + - `FF`:`predEnd + offset − duration` + - `SF`:`earliest[pred] + offset − duration` + 取最大值作为 `earliest[id]`,同时记录前驱 `prev[id]`。 +4. 找结束角最大的动作作为链尾,沿 `prev` 回溯,得到 `criticalActions` 与 `criticalDeps` 两个 `Set`。 + +复杂度 `O(V + E)`,每次编辑重算,当前规模(数十动作)无压力。 + +### 5.3 自动保存 + +- `start()` 启动 `Timer.periodic(5s)` → `Storage.writeAutosave(...)`。 +- 退出时 `AppLifecycleListener.onExitRequested` 调用 `markCleanOnExit()` 写入“干净”快照。 +- 启动时 `main.dart` 检查 `Storage.checkRecovery()`,若上次非正常退出则弹恢复向导。 + +--- + +## 6. 布局与坐标系统(`layout/layout.dart`) + +纯函数 + 布局类,**不依赖 Flutter Widget**(只用 `Offset/Rect/Size/Path`)。 + +### 6.1 条形布局 `BarLayout` + +| 常量 | 值 | 说明 | +| --- | --- | --- | +| `leftGutter` | 300 | 左侧标题列宽度(**关键**:避免文字压到条形块) | +| `topPad` | 210 | 第一行动作的 y | +| `barH` | 34 | 条形高度 | +| `rowVisual` | 50 | 行条纹/背景高度 | +| `bottomReserve` | 350 | 为底部统计/工具浮层预留的高度 | +| `pitch` | 动态 46–66 | `(height − topPad − bottomReserve) / n` 后 clamp | + +- `plotLeft = leftGutter`,`plotRight = width − 56`。 +- `xFor(deg) = plotLeft + deg/360 × span`;`yFor(i) = topPad + i × pitch`。 +- `ordered` 排序键:工位 `order` → `startAngle` → `id`。 +- `hitTest` 线性扫描所有行(见 §12 优化点)。 + +### 6.2 圆周布局 `CircularLayout` + +- 圆心默认画布中心(下移 18px)。 +- `r0 = 58`,`pitch = clamp((maxR − r0)/(layers−1), 24, 46)`,`ringWidth = clamp(pitch×0.72, 14, 34)`。 +- `radiusFor(layer) = r0 + layer × pitch`。 +- 命中测试:先按径向距离筛选到某层,再判断角度是否落在弧内(含跨圈)。 +- 辅助函数:`polar / angleOf / arcPath / splitArcs`。 + +--- + +## 7. 渲染层(`render/*`) + +### 7.1 条形 `BarPainter` + +绘制顺序:相位分区带 → 双刻度轴(上=时间,下=相位)→ 0°/360° 循环边界 → 行条纹与左侧标题 → 条形与文字 → 依赖箭头。 + +- 相位分区带为固定语义区间:上料 / 夹紧 / 加工 / 检测 / 下料,只绘制“有动作落入”的区间。 +- 条形文字策略:宽度 >150 时文字内嵌;靠近右边界时文字外置左对齐;否则外置右对齐。 +- 跨圈:在主条形左侧画一段半透明尾段,并标注“跨循环延续 n°”。 +- 依赖:`|Δrow| ≤ 1` 走短正交路径;跨多行时在中间行右侧找“泳道”绕行(`lane`,按序号错开)。 +- 依赖标签 chip 显示 `FS 顺序` / `SS +n°`,关键依赖加 ★。 + +### 7.2 圆周 `CircularPainter` + +绘制顺序:底盘 → 同心环背景(可关)→ 四象限虚线 → 层标注(可关)→ 依赖弧 → 动作弧 → 起点标记 → 顺时针指示 → 刻度环。 + +- 动作弧按 `splitArcs` 拆分,跨圈尾段半透明 + 虚线。 +- 选中动作叠加白色描边与外侧强调色虚线弧。 +- 依赖弧:同层/相邻层用中间半径 `rC`;跨层用外圈 `RMAX+24`;末端沿径向指向目标环。 + +### 7.3 主题 Token(`theme/tokens.dart`) + +- `Tokens` 是一组语义颜色(`bg/panel/text/accent/fs/ss/crit/ring*/…`)+ `brightness`。 +- 通过 `ThemeExtension` 注入,`context.tok` 取用。 +- `buildTheme()` 统一字体(`Microsoft YaHei`)、`ColorScheme`、`TextTheme`。 +- 语义色在深/浅两套中保持一致含义(FS 绿、SS 琥珀、关键路径青)。 + +--- + +## 8. UI 层(`ui/*`) + +### 8.1 `AppShell`(外壳) + +- **快捷键**:`CallbackShortcuts` 绑定 `Ctrl+Z/Y/S/O/N`、`Delete`、`F1/F2/F3`。 +- **工具栏**:`LayoutBuilder` 自适应——宽度 `< 1960` 进入紧凑模式(隐藏文件路径胶囊、图标化“适应窗口/复位视图”), + 极窄时横向滚动兜底。 +- **可停靠侧栏**(本次新增): + - 状态:`_leftVisible/_leftPinned/_leftHover` 与右侧同理。 + - 派生:`_leftDocked`(钉住且可见,占据 Row 空间)、`_leftFloat`(未钉住且悬停,浮于画布)、`_leftRail`(其余情况,显示细把手)。 + - 面板标题栏含图钉(钉住/悬浮)与关闭按钮;边缘把手悬停临时展开、点击固定。 +- **画布区**:`Stack` 承载 `RepaintBoundary(CanvasView + CanvasOverlays)` 与悬浮/把手侧栏。 + `RepaintBoundary` 的 `GlobalKey` 同时用于“导出 PNG”。 +- **状态栏**:循环周期、相位、动作数、依赖数、层/工位、单位、`1°` 换算、当前状态。 + +### 8.2 `CanvasView`(手势) + +- 通过 `Transform` 应用 `zoom / panX / panY`,屏幕坐标 ↔ 逻辑坐标互转(`_toLogical`)。 +- `onTapDown` 选择;`onDoubleTapDown` 空白处新建;`onPanStart/Update` 区分 `move`(平移相位)与 `resize`(改持续角); + `Shift+拖拽` 改层;空白拖拽平移画布。 +- `onPointerSignal`:`Ctrl+滚轮` 缩放,普通滚轮平移。 +- `onSecondaryTapDown`:右键上下文菜单(添加依赖 / 改层 / 复制 / 删除)。 + +### 8.3 `CanvasOverlays`(画布浮层) + +按可用宽高自适应取舍,避免遮挡图元: + +| 浮层 | 显示条件(宽 × 高) | +| --- | --- | +| 标题 + 副标题 | 始终 | +| 圆周左侧图例列(图例 + 选中卡 + 依赖类型) | 宽 ≥ 1500 且高 ≥ 820 | +| 条形底部统计 | 宽 ≥ 900 且高 ≥ 760 | +| 编辑工具 | 宽 ≥ 760 | +| 实时预览卡(圆周↔条形) | 宽 ≥ 1400 且高 ≥ 760 | +| 浮动工具条(圆周) | 始终(圆周视图) | + +### 8.4 `dialogs.dart` + +- `FileBrowserDialog`:自研文件浏览器(驱动器、目录树、过滤 `.json`、保存/打开)。 +- `ActionEditorDialog` / `DependencyEditorDialog`:动作与依赖编辑。 +- `SettingsDialog`:项目名、时间/相位单位、精度、循环时长、吸附、显示等。 +- `HelpDialog`:5 个分页(快速开始 / 界面与侧栏 / 操作与快捷键 / 双视图 / 单位与导出)。 + +--- + +## 9. 导出 + +### 9.1 SVG(`export/svg_writer.dart`) + +- 固定画布 `2560×1440`,输出分层 ``:`background / ruler / layers / actions / dependencies / legend`。 +- 每个动作带 `data-action / data-start / data-duration / data-layer / data-station`,供 MES / 工艺卡消费。 +- 依赖用 `` 定义箭头,FS 实线、SS 虚线。 +- 颜色由 `Tokens` 转 `#rrggbb`,与屏幕一致。 + +### 9.2 PNG(`ui/app_shell.dart`) + +- 对画布 `RepaintBoundary` 调 `toImage(pixelRatio: 2)` → `toByteData(png)` → 写文件。 + +--- + +## 10. 持久化与恢复(`persistence/storage.dart`) + +- 单例 `Storage.instance`,`init()` 解析目录: + `%APPDATA%\SequenceDiagramStudio\autosave\{current.seq.json, session.json}`。 +- `writeAutosave` 写快照 + 会话元数据(路径、是否干净、时间)。 +- `saveProject` 先备份 `.bak`,再写入并刷新快照为“干净”。 +- `checkRecovery` 在启动时判断上次是否异常退出,并附带 `.bak` 供选择恢复。 + +--- + +## 11. 构建与打包 + +- 图标:`tools/gen-icon.py`(Pillow)生成时钟/周期盘图标 → `windows/runner/resources/app_icon.ico`(多尺寸)。 +- 构建:`scripts/build.bat` 设置镜像与 `FLUTTER_CMAKE_PATH`,构建后把 + `build\windows\x64\runner\Release\*` 复制到浅目录 `dist\`。 +- 产物:`dist\sequence_diagram.exe`。 + +--- + +## 12. 性能分析与优化点(重点) + +> 面向“1000 动作仍 60fps”的目标,以下为当前实现的可优化项,按收益排序。 + +### 12.1 重绘与重建 + +1. **`shouldRepaint` 恒为 `true`**(`BarPainter` / `CircularPainter`)。 + - 现状:任何控制器通知都会让画布整帧重绘。 + - 建议:改为比较关键字段(`project` 引用、`zoom/pan`、`selectedId`、`critical*` 的引用或版本号), + 或给 `Project` 引入 `revision` 计数。 +2. **`AppShell` 整体 `setState`**。 + - 现状:`_onChange()` 触发整个外壳重建(含左右面板、状态栏)。 + - 建议:用 `ValueListenableBuilder` / `Selector`(项目已依赖 `flutter_riverpod` 但未使用) + 把重建范围收敛到具体子面板;或拆分多个 `Listenable`。 +3. **`RepaintBoundary` 分层**:给静态浮层(图例、统计)与画布各加独立 `RepaintBoundary`,减少联动重绘。 + +### 12.2 绘制与文本 + +4. **每帧新建 `TextPainter`**。 + - 建议:缓存 `TextPainter`(按 `文本+字号+颜色` 键),或预生成 `ui.Paragraph`。 +5. **`_text` 每次都 `layout()`**。 + - 建议:批量绘制前统一 layout,或对不变量文本做缓存。 +6. **依赖路由为逐条计算**:大规模时应做**空间索引**(网格 / R-tree)与路径缓存。 +7. **图层缓存**:把“同心环背景”“刻度环”“行条纹”等静态内容用 `PictureRecorder` 录制为 + `ui.Picture`,仅在尺寸/主题变化时重录。 + +### 12.3 交互与命中测试 + +8. **`hitTest` 线性扫描**(`BarLayout` / `CircularLayout`)。 + - 现状:`O(n)`,且每次 `onPanUpdate` 都可能重建布局对象。 + - 建议:维护动作的空间索引(条形按行 + 区间树;圆周按层 + 角度区间),并把布局对象在 + `CanvasView` 中按 `(size, project.revision)` 缓存复用。 +9. **拖拽高频写入**:`setActionStart` 每次触发 `_mutate` → 入撤销栈 + 重算关键路径 + 全量通知。 + - 建议:拖拽过程中走“预览态”(不入栈、只通知局部),`onPanEnd` 时合并为一次提交。 + +### 12.4 数据与持久化 + +10. **自动保存 5 秒全量写盘**:大项目可改为增量 / 空闲时写,或使用 `Isolate` 编码 JSON。 +11. **关键路径每次编辑重算**:可做增量更新(仅受影响子图),或对无依赖变更的编辑跳过。 +12. **`Project` 全量复制**:`copyWith` 会重建 `actions` 列表;1000 动作时可考虑结构共享 / 持久化数据结构。 + +### 12.5 浮层与统计 + +13. `_BarStats` 每次 build 计算最大并行度(`O(360×n)`)与覆盖率;应缓存或增量更新。 +14. `_stationLoads` 每次 build 聚合;可并入 `AppController` 的派生数据。 + +### 12.6 其它 + +15. `flutter_riverpod` 已在 `pubspec.yaml` 但未使用——要么接入做细粒度重建,要么移除依赖。 +16. `pixelRatio: 2` 导出大画布时内存占用高;可让用户选择倍率或分块导出。 + +--- + +## 13. 扩展点 + +- **依赖类型**:模型已支持 `FF / SF`,渲染与关键路径已按四类处理,可补 UI 入口。 +- **PLC 点位对接**(路线图 M4):在 `Station/Action` 增加点位字段,导出层扩展 `data-*`。 +- **工艺卡 PDF**:复用 `SvgWriter` 的分层输出,交给外部渲染器。 +- **多循环 / 配方**:`Cycle` 已参数化,可扩展为多循环序列。 + +--- + +## 14. 术语表 + +| 术语 | 含义 | +| --- | --- | +| 节拍 / Cycle | 一个完整生产循环,映射 360° / 100% | +| 相位角 | 动作在循环中的角度位置 | +| FS / SS | 完成-启动 / 起始-起始 依赖类型 | +| 关键路径 | 累计时长最长的依赖链 | +| 跨圈 | 动作结束角 > 360°,跨越循环边界 | +| 泳道 | 条形视图中按工位分组的行 | +| 层 | 圆周视图中动作所在的同心圆环 | diff --git a/docs/HELP.md b/docs/HELP.md new file mode 100644 index 0000000..78aa784 --- /dev/null +++ b/docs/HELP.md @@ -0,0 +1,301 @@ +# 时序图工作台 · 使用帮助(按任务组织) + +> 面向 PLC 流程节拍 / 相位角设计的桌面软件(Flutter Desktop)。 +> 应用内按 **F1** 可随时打开同一份帮助。 +> +> 本文按「**我要完成什么**」来组织:先找到你的目标,再照着步骤做。 + +--- + +## 目录 + +- [A. 开始一个方案](#a-开始一个方案) +- [B. 动作:增、删、改、复制、对齐](#b-动作增删改复制对齐) +- [C. 时间与相位:循环长度、起止角、时长](#c-时间与相位循环长度起止角时长) +- [D. 依赖关系:先后顺序与并行(多输入 / 多输出)](#d-依赖关系先后顺序与并行多输入--多输出) +- [E. 相位分区:编辑名称、起止角、数量](#e-相位分区编辑名称起止角数量) +- [F. 视图:条形 / 圆周、缩放、适应视图、显示选项](#f-视图条形--圆周缩放适应视图显示选项) +- [G. 界面:隐藏 / 钉住侧栏,看统计](#g-界面隐藏--钉住侧栏看统计) +- [H. AI 生成:用自然语言直接生成时序图](#h-ai-生成用自然语言直接生成时序图) +- [I. 导出:SVG / PNG](#i-导出svg--png) +- [J. 保存、打开、崩溃恢复](#j-保存打开崩溃恢复) +- [K. 单位与精度](#k-单位与精度) +- [附录:快捷键与文件格式](#附录快捷键与文件格式) + +--- + +## A. 开始一个方案 + +**我要新建一个空白方案** +1. 顶部「**新建**」(或 `Ctrl+N`)→ 生成含 2 个动作(动作 1 / 动作 2)的空白节拍。 +2. 左侧「项目」卡片里点名称即可在 `F2` 工艺参数中重命名。 + +**我要打开已有方案** +1. 顶部「**打开**」(或 `Ctrl+O`)→ 应用内文件浏览器选择 `.seq.json`。 + +**我要一个示例先看看** +- 首次启动会载入 2 个动作的示例节拍,可直接在此基础上修改。 + +--- + +## B. 动作:增、删、改、复制、对齐 + +**我要新增动作** +- **双击画布空白处**:在点击的相位角处新增,默认放在**最外层**;或 +- 左侧「动作 / 工位泳道」右上角「**新建**」:在 0° 处新增。 + +**我要删除动作** +- 选中动作后,左侧列表标题右侧的「**删除**」(未选中时按钮为灰);或 +- 选中后点左侧该行动态出现的删除图标;或 +- 右侧「编辑操作」里的「删除」;或 +- 选中后按 `Delete`;或 +- 右键动作 → 删除动作。 + +**我要修改动作属性(名称 / 工位 / 驱动 / 颜色)** +- 选中动作 → 右侧「编辑」;或点左侧该行右侧的编辑图标;或顶部「编辑」。 + +**我要复制 / 对齐** +- 右侧「编辑操作」→「复制」/「对齐相位」;圆周视图还有「新增外层 / 重排合并层」。 + +--- + +## C. 时间与相位:循环长度、起止角、时长 + +**我要修改循环长度(时间轴长度)** +- 方式一:左侧「项目」卡片里点击「**循环 2.400 s = 360° = 100%**」→ 打开工艺参数 →「循环与相位」→ 修改「循环时长」→「应用」。 +- 方式二:按 `F2` →「循环与相位」→ 修改「循环时长」。 + +> 时间只存于 `cycle.durationMs`(毫秒);角度 = `ms / cycleMs × 360`,改循环时长不会丢失角度精度。 + +**我要调整某个动作的相位 / 时长** +- 拖动动作块 → 平移相位(自动吸附); +- 拖动条形块**右端** → 改持续角(左端固定); +- 圆周视图 **Shift + 拖拽** → 径向改层; +- 右侧属性面板的「起始角 / 持续角」滑杆可精确调。 + +**我要让动作跨循环** +- 使 `起始角 + 持续角 > 360°` 即可;条形/圆周会自动拆分,尾段以半透明虚线渲染。 + +--- + +## D. 依赖关系:先后顺序与并行(多输入 / 多输出) + +**依赖类型** +| 类型 | 含义 | 画法 | +| --- | --- | --- | +| **FS** 完成-启动 | 前动作完成后才启动 | 绿色实线箭头 | +| **SS** 起始-起始 | 可提前启动(并行重叠) | 琥珀虚线箭头,标签带 `+n°` | +| FF / SF | 完成-完成 / 起始-完成 | 预留类型 | + +**我要给动作添加前置依赖(输入)** +- 选中动作 → 右侧「**前置依赖 · 输入**」→「添加前置依赖」→ 选择前置动作与类型;或 +- 右键动作 →「添加依赖…」。 + +**一个动作可以有多个前置(多输入)** +- 重复添加即可;右侧会逐条列出,每条可单独删除。 + +**一个动作可以输出多个结果(多输出)** +- 在「**输出依赖 · 结果**」区域可以看到本动作指向了哪些后续动作,并可逐条删除。 + +**我要删除依赖** +- 在「前置依赖」或「输出依赖」列表中点击该条右侧的 `×`。 + +--- + +## E. 相位分区:编辑名称、起止角、数量 + +**相位分区是什么** +- 把一个循环按角度划分成的若干**命名工艺阶段**(默认:上料 / 夹紧 / 加工 / 检测 / 下料), + 条形图顶部那条标注带就是它;右侧属性里的「相位归属」也按它判断。 + +**我要编辑相位分区** +1. 按 `F2` →「工艺参数」→ 找到「**相位分区**」→「编辑…」。 +2. 在弹出的编辑器里: + - **添加分区** / **删除分区**(数量不限); + - 修改**名称**、**起始角**、**结束角**; + - 允许区间**重叠**,也允许**留空**;结束角 `> 360°` 表示跨圈; + - 「恢复默认」回到五个标准阶段。 +3. 点「确定」应用。 + +**我要隐藏相位分区标注** +- 左侧「显示选项」→ 取消勾选「相位分区标注」。 + +--- + +## F. 视图:条形 / 圆周、缩放、适应视图、显示选项 + +**我要切换视图** +- 顶部「条形节拍 / 圆周节拍」分段开关;两种视图共享同一份数据。 + +**我要缩放 / 平移** +- `Ctrl + 滚轮`:**以光标为锚点**缩放(25% – 400%); +- 普通滚轮 / 拖拽空白:平移画布。 + +**我要让内容完整显示(适应视图)** +- 顶部「**适应视图**」:按当前内容(含刻度、箭头、跨圈等标注)自动计算缩放与居中, + 编辑过圆周节拍、层数很多时也会自动缩小到完整可见。 + +**我要开关图元标注** +- 左侧「显示选项」: + - 条形视图:时间轴/相位双刻度、依赖箭头 FS/SS、跨循环片段标记、相位分区标注; + - 圆周视图:同心圆环背景、顺序箭头、层半径标注、跨循环高亮。 + +--- + +## G. 界面:隐藏 / 钉住侧栏,看统计 + +**我要隐藏 / 显示侧栏** +- 工具栏右侧有两个侧栏按钮,分别控制左、右侧栏。 + +**我要钉住侧栏** +- 侧栏标题右侧的**图钉**按钮: + - **已钉住**:固定占位,画布让出空间; + - **取消钉住**:变为悬浮层,鼠标移开自动收起; +- 侧栏收起后,画布边缘有细把手:悬停临时展开、点击固定显示。 + +**我要查看节拍统计** +- 画布左下角「**节拍统计**」按钮 → 弹出窗口显示循环周期、动作数量、关键路径、 + 最大并行度、相位覆盖率、瓶颈工位、预估产能。 + +--- + +## H. AI 生成:用自然语言直接生成时序图 + +**我要用一句话生成一张时序图** +1. 顶部「**AI 生成**」按钮。 +2. 在对话框中: + - 填写 **DeepSeek API Key**(仅保存在本机内存,不写入工程文件); + - 选择模型:**Flash · 快速**(`deepseek-chat`)或 **Pro · 深度推理**(`deepseek-reasoner`); + - 选择推理强度:**高 / 最高**; + - 在较大的输入框里用**自然语言**描述工艺流程(工位、动作、时间、先后与并行关系)。 +3. 点「生成」→ 模型返回结构化时序图并自动载入工作台;可在其上继续编辑。 + +**生成效果不理想怎么办** +- 描述里写清:循环时长、工位数量、每个动作大致时长、哪些是顺序(完成后启动)、哪些是并行。 +- 生成后仍可手动微调角度、依赖与相位分区。 + +> 需要有效的 DeepSeek API Key 与可访问 `api.deepseek.com` 的网络。 + +--- + +## I. 导出:SVG / PNG + +**我要导出矢量图(进工艺卡 / MES)** +- 顶部「导出 SVG」→ 选择保存位置。SVG 分层、带语义 `id` 与 `data-*`: + `background / ruler / layers / actions / dependencies / legend`, + 每个动作 ``。 + +**我要导出位图** +- 顶部「导出 PNG」→ 按 2 倍像素比导出当前画布为 `.png`。 + +--- + +## J. 保存、打开、崩溃恢复 + +**我要保存** +- 「保存 / 另存为」写入 `.seq.json`,并在同目录生成 `<文件名>.bak` 备份。 + +**异常退出后恢复** +- 软件每 **5 秒**写入本地快照;若上次未正常退出,下次启动会弹出恢复向导, + 可选择「恢复自动快照 / 从 .bak 恢复 / 忽略并删除快照」。 +- 快照目录:`%APPDATA%\SequenceDiagramStudio\autosave\`。 + +--- + +## K. 单位与精度 + +**我要改单位 / 精度** +- 顶部单位下拉(ms / s / min)快速切换;或 `F2` →「单位与精度」改时间/相位单位与显示精度。 + +**换算关系** +``` +angle(deg) = ms / cycleMs × 360 +ms = angle / 360 × cycleMs +``` + +--- + +## L. 多选与批量对齐 + +**我要同时对齐多个动作** +1. 按住 **Ctrl**(或 Shift)在画布 / 左侧列表逐个点击动作,可**多选**; +2. 点右侧「编辑操作」→「对齐相位」,所有选中动作的起始角会**对齐到主选中项**的起始角。 + +> 不按 Ctrl 点击则替换为单选;再次 Ctrl 点击已选项可取消该动作的选中。 + +## M. 编辑动作:角度 ↔ 时间 + +**我要按时间(而不是角度)修改动作** +- 选中动作 → 右侧「编辑」(或双击行内编辑图标)→ 编辑框内同时提供: + - **起始相位 / 持续相位(°)** + - **起始时刻 / 持续时长**(当前时间单位,如 `s`) +- 两组输入**实时双向换算**:改角度自动更新时间,改时间自动更新角度。 +- 换算关系:`时间 = 角度 / 360 × 循环时长`。 + +**拖拽时的辅助** +- 把鼠标移到**色块左/右端**或**分区边界**附近,指针会变成**左右拖拽箭头**; +- 拖动时会显示**竖直虚线坐标参考**,并带**弱吸附**(自动贴合整 5°、其它动作端点、分区边界)。 + +## N. 关于 + +- **软件**:时序图工作台 · Sequence Diagram Studio +- **设计人**:呆头鹅 +- **版本**:V1.0.0 +- **版权**:Copyright © 2026 呆头鹅。保留所有权利。 + +--- + +## 附录:快捷键与文件格式 + +### 快捷键 + +| 操作 | 行为 | +| --- | --- | +| 左键拖拽动作块 | 平移相位(自动吸附) | +| 拖拽条形块右端 | 改持续角 | +| `Shift` + 拖拽 | 圆周视图改层;条形视图上下拖动改层 | +| 双击空白 | 在点击角度处新建动作 | +| `Ctrl` + 滚轮 | 以光标为锚点缩放 | +| 普通滚轮 | 平移画布 | +| 右键动作 | 菜单:添加依赖 / 改层 / 复制 / 删除 | +| `Ctrl+Z` / `Ctrl+Y` | 撤销 / 重做 | +| `Ctrl+S` / `Ctrl+O` / `Ctrl+N` | 保存 / 打开 / 新建 | +| `Delete` | 删除选中动作 | +| `F1` / `F2` / `F3` | 帮助 / 工艺参数 / 深浅主题 | + +### 工程文件格式(`.seq.json`) + +```json +{ + "schema": "seqdiagram/1.2", + "project": { + "name": "示例节拍", + "units": { "timeUnit": "s", "phaseUnit": "deg", "precision": -1 }, + "cycle": { "durationMs": 2400, "startAngle": 0, "direction": "cw", "origin": "twelve" }, + "stations": [ { "id": "ST1", "name": "工位 1", "order": 0, "color": "#4cc9f0" } ], + "actions": [ + { "id": "A1", "name": "动作 1", "stationId": "ST1", "driver": "气缸 Y1", + "startAngle": 0, "durationAngle": 70, "layer": 0, "color": "#4cc9f0", + "deps": [] }, + { "id": "A2", "name": "动作 2", "stationId": "ST2", "driver": "气缸 Y2", + "startAngle": 80, "durationAngle": 60, "layer": 1, "color": "#7bd88f", + "deps": [ { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 } ] } + ], + "viewState": { "mode": "bar", "zoom": 1, "pan": [0, 0], "showDeps": true }, + "phaseZones": [ { "name": "上料相位", "startAngle": 0, "endAngle": 70 } ] + } +} +``` + +### 从源码构建 + +```bash +flutter pub get +flutter run -d windows # 开发调试 +scripts\build.bat # 发布版:构建并复制到 dist\ +``` + +产物:`dist\sequence_diagram.exe` + +> 若本机装有绿盾等透明加密软件,请先阅读仓库根目录 `BUILD-NOTES.md`。 +> 架构与性能优化点见 `docs/ARCHITECTURE.md`。 diff --git a/lib/ai/ai_client.dart b/lib/ai/ai_client.dart new file mode 100644 index 0000000..9e68110 --- /dev/null +++ b/lib/ai/ai_client.dart @@ -0,0 +1,185 @@ +/// DeepSeek 大模型客户端:把自然语言描述转换为可加载的 [Project]。 +/// +/// 架构位置:独立于 UI 与状态层的纯服务模块,仅依赖 `dart:io`(HttpClient) +/// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [Project] 后交给 +/// [AppController.loadProject] 载入。 +/// +/// 约束:不引入任何原生插件或第三方 HTTP 包,全部使用 `dart:io` 实现。 +library; + +import 'dart:convert'; +import 'dart:io'; + +import '../model/models.dart'; + +/// AI 请求参数。 +class AiSettings { + /// 构造参数。 + const AiSettings({ + required this.apiKey, + required this.model, + required this.effort, + }); + + /// DeepSeek API Key(仅驻留内存,不写入工程文件)。 + final String apiKey; + + /// 模型 id,例如 `deepseek-chat`(Flash)或 `deepseek-reasoner`(Pro)。 + final String model; + + /// 推理强度:`high` / `max`。 + final String effort; +} + +/// 可选的模型项(id + 展示名)。 +class AiModelOption { + /// 构造。 + const AiModelOption(this.id, this.label); + + /// 接口使用的模型 id。 + final String id; + + /// 界面展示名称。 + final String label; +} + +/// 预设模型列表:Flash(快速)与 Pro(深度推理)。 +const List kAiModels = [ + AiModelOption('deepseek-chat', 'Flash · 快速'), + AiModelOption('deepseek-reasoner', 'Pro · 深度推理'), +]; + +/// AI 调用异常(携带可读信息,便于界面直接展示)。 +class AiException implements Exception { + /// 构造。 + AiException(this.message); + + /// 错误信息。 + final String message; + + @override + String toString() => message; +} + +/// DeepSeek 客户端。 +class AiClient { + AiClient._(); + + /// DeepSeek 兼容 OpenAI 的对话补全端点。 + static const String endpoint = 'https://api.deepseek.com/chat/completions'; + + /// 要求模型输出的系统提示词:严格描述 `seqdiagram/1.2` JSON 结构。 + static const String _systemPrompt = ''' +你是工业节拍 / 相位角设计助手。请把用户的自然语言描述转换成严格的 JSON,且**只能输出 JSON**,不要输出解释、注释或 Markdown 代码块。 + +JSON 结构(协议 seqdiagram/1.2): +{ + "schema": "seqdiagram/1.2", + "project": { + "name": "项目名称", + "units": { "timeUnit": "s", "phaseUnit": "deg", "precision": -1, "snapAngle": 1, "snapTime": 0.1, "cycleInputPolicy": "keepAngle" }, + "cycle": { "durationMs": 2400, "startAngle": 0, "direction": "cw", "origin": "twelve", "snapDeg": 1 }, + "stations": [ { "id": "ST1", "name": "工位1", "order": 0, "color": "#4cc9f0" } ], + "actions": [ + { "id": "A1", "name": "动作1", "stationId": "ST1", "driver": "气缸 Y1", + "startAngle": 0, "durationAngle": 60, "layer": 0, "color": "#4cc9f0", "deps": [] } + ], + "viewState": { "mode": "bar", "zoom": 1, "pan": [0, 0], + "showDeps": true, "showRuler": true, "showPhaseBands": true, "showRingBg": true, "showLayerLabels": true }, + "phaseZones": [ { "name": "上料相位", "startAngle": 0, "endAngle": 70 } ] + } +} + +规则: +1. 时间只存于 cycle.durationMs(毫秒);角度为 0–360 度,0° 为 12 点钟方向、顺时针递增。 +2. 每个动作 durationAngle > 0;startAngle + durationAngle 可以超过 360 表示跨循环。 +3. layer 从 0 开始,每个动作独占一层(圆周视图的一个同心圆环)。 +4. deps 为前置依赖数组,元素形如 { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 }; + type 取 FS(完成-启动)/ SS(起始-起始)/ FF / SF。 + 一个动作可以有**多条** deps(多输入),也可以被**多个**动作引用(多输出)。 +5. 颜色从调色板循环取用:#4cc9f0, #7bd88f, #ffd166, #ff8a5c, #f472b6, #a78bfa, #38bdf8, #34d399。 +6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。 +7. 只输出 JSON 本体。 +'''; + + /// 根据自然语言 [prompt] 生成项目。 + /// + /// 抛出 [AiException] 表示网络、鉴权或解析失败。 + static Future generate({ + required String prompt, + required AiSettings settings, + }) async { + if (settings.apiKey.trim().isEmpty) { + throw AiException('请先填写 DeepSeek API Key'); + } + if (prompt.trim().isEmpty) { + throw AiException('请输入自然语言描述'); + } + + final HttpClient client = HttpClient()..connectionTimeout = const Duration(seconds: 20); + try { + final HttpClientRequest req = await client.postUrl(Uri.parse(endpoint)); + req.headers.set(HttpHeaders.contentTypeHeader, 'application/json'); + req.headers.set(HttpHeaders.authorizationHeader, 'Bearer ${settings.apiKey.trim()}'); + req.write(jsonEncode({ + 'model': settings.model, + 'messages': >[ + {'role': 'system', 'content': _systemPrompt}, + {'role': 'user', 'content': prompt.trim()}, + ], + 'stream': false, + 'temperature': 0.2, + 'response_format': {'type': 'json_object'}, + // 兼容支持推理强度的接口;不支持时会被忽略。 + 'reasoning_effort': settings.effort, + })); + final HttpClientResponse res = await req.close(); + final String text = await res.transform(utf8.decoder).join(); + if (res.statusCode != 200) { + throw AiException('接口返回 ${res.statusCode}:${_brief(text)}'); + } + final Map json = jsonDecode(text) as Map; + final List choices = (json['choices'] as List?) ?? []; + if (choices.isEmpty) throw AiException('接口未返回内容'); + final Map msg = + ((choices.first as Map)['message'] as Map?) ?? {}; + final String content = (msg['content'] as String?) ?? ''; + if (content.trim().isEmpty) throw AiException('模型返回为空'); + final String cleaned = _extractJson(content); + try { + return Project.decode(cleaned); + } catch (e) { + throw AiException('模型输出无法解析为时序图:$e'); + } + } on AiException { + rethrow; + } on SocketException catch (e) { + throw AiException('网络连接失败:${e.message}'); + } on HttpException catch (e) { + throw AiException('HTTP 错误:${e.message}'); + } on FormatException catch (e) { + throw AiException('响应格式错误:${e.message}'); + } finally { + client.close(force: true); + } + } + + /// 从模型输出中剥离 Markdown 代码围栏并截取首个 JSON 对象。 + static String _extractJson(String raw) { + String t = raw.trim(); + if (t.startsWith('```')) { + t = t.replaceFirst(RegExp(r'^```[a-zA-Z]*\s*'), ''); + t = t.replaceFirst(RegExp(r'```\s*$'), ''); + } + final int i = t.indexOf('{'); + final int j = t.lastIndexOf('}'); + if (i >= 0 && j > i) t = t.substring(i, j + 1); + return t.trim(); + } + + /// 截断过长的错误信息,避免弹窗过大。 + static String _brief(String s) { + final String one = s.replaceAll(RegExp(r'\s+'), ' ').trim(); + return one.length > 200 ? '${one.substring(0, 200)}…' : one; + } +} diff --git a/lib/export/svg_writer.dart b/lib/export/svg_writer.dart new file mode 100644 index 0000000..1c2a96a --- /dev/null +++ b/lib/export/svg_writer.dart @@ -0,0 +1,333 @@ +/// SVG 导出写入器。 +/// +/// 职责:把当前 [Project] 序列化为独立、可缩放、带语义标注的 SVG 文档, +/// 用于归档、打印,或与前端 / EDA 工具交换。 +/// +/// 架构位置: +/// - 与渲染层 `BarPainter`/`CircularPainter` 共用 [BarLayout]/[CircularLayout] +/// 的几何算法,确保屏幕显示与导出结果一致。 +/// - 颜色取自 [Tokens],并通过 [_hex] 转为 `#rrggbb`。 +/// - 每个逻辑分组写成 ``(背景、标尺、动作、标签、依赖、图例), +/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。 +/// +/// 输出约定: +/// - 画布固定 2560×1440,通过 `viewBox` 支持无损缩放。 +/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../model/units.dart'; +import '../theme/tokens.dart'; + +/// SVG 文档写入器。 +/// +/// 通过内部 [StringBuffer] 逐段拼接字符串,最终由 [build] 返回完整文档。 +class SvgWriter { + /// 创建 SVG 写入器。 + /// + /// 参数: + /// - [project]:数据源(动作、依赖、视图开关、单位)。 + /// - [tokens]:配色令牌。 + /// - [mode]:视图模式,决定生成条形还是圆形布局。 + /// + /// 构造时不生成任何内容;调用 [build] 才写出 SVG。 + SvgWriter({required this.project, required this.tokens, required this.mode}); + + /// 数据源工程。 + final Project project; + /// 配色令牌。 + final Tokens tokens; + /// 导出所用的视图模式。 + final ViewMode mode; + + /// 输出缓冲区,累积 SVG 文本片段。 + final StringBuffer _b = StringBuffer(); + /// 统一字体栈常量。 + static const String _font = "'Microsoft YaHei','Noto Sans SC','Segoe UI',sans-serif"; + + /// 生成完整 SVG 文档字符串。 + /// + /// 返回:以 `` 开头、`` 结尾的字符串。 + /// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区, + /// 因此约定每次导出都新建一个 [SvgWriter] 实例。 + String build() { + // 固定逻辑画布尺寸;viewBox 与 width/height 相同,缩放时几何不失真。 + final double w = 2560; + final double h = 1440; + _b.write(''); + // 先写箭头 marker 定义,供后续依赖路径引用。 + _defs(); + // 背景层:铺满整张画布。 + _b.write(''); + _rect(0, 0, w, h, fill: _hex(tokens.bg)); + _b.write(''); + // 按当前视图模式生成主体内容。 + if (mode == ViewMode.bar) { + _barView(Size(w, h)); + } else { + _circularView(Size(w, h)); + } + // 图例始终绘制在最上层。 + _legend(w, h); + _b.write(''); + return _b.toString(); + } + + /// 写入 `` 段,定义 FS / SS 两种箭头 marker。 + /// + /// marker 通过 id `arrow-fs`、`arrow-ss` 被依赖路径的 `marker-end` 引用; + /// `orient="auto"` 使箭头自动跟随路径末端方向。 + void _defs() { + _b.write(''); + _b.write('' + ''); + _b.write('' + ''); + _b.write(''); + } + + /// 生成条形视图的 SVG 内容。 + /// + /// 参数 [size] 用于构建与屏幕一致的 [BarLayout]。 + /// 依次输出四个分组: + /// - `g#ruler`:角度/时间双轴标尺(`data-axis="angle"`)。 + /// - `g#actions`:每个动作一个 `g`,带 `data-action/start/duration/layer/station`。 + /// - `g#labels`:左侧动作标识与工位/驱动文本。 + /// - `g#dependencies`(可选):依赖正交折线。 + void _barView(Size size) { + final BarLayout layout = BarLayout(project, size); + final UnitSettings u = project.units; + final double cycle = project.cycle.durationMs; + final double top = BarLayout.topPad - 62; + + // 标尺分组:下排为相位角,上排为等价时间;data-axis 标记角度轴语义。 + _b.write(''); + _rect(layout.plotLeft, top, layout.span, 26, fill: _hex(tokens.accent), opacity: 0.07); + for (int d = 0; d <= 360; d += 30) { + final double x = layout.xFor(d.toDouble()); + _line(x, top + 26, x, top + 44, stroke: _hex(tokens.line2), sw: 1); + _text(x, top - 10, tvalStr(d / 360 * cycle, u, dec: 1), color: _hex(tokens.dim), size: 11, anchor: 'middle'); + _text(x, top + 58, pfmt(d.toDouble(), u, dec: 0), color: _hex(tokens.accent), size: 11, anchor: 'middle'); + } + _b.write(''); + + // 动作分组:每个动作一个 ,附带 data-* 语义属性,便于下游解析。 + _b.write(''); + final List ordered = layout.ordered; + for (int i = 0; i < ordered.length; i++) { + final Action a = ordered[i]; + final Rect r = layout.rectFor(a); + final Color c = Color(a.color); + _b.write(''); + _rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 7, opacity: 0.92); + _text(r.left + 8, r.center.dy + 4, '${a.name} ${tfmt(a.durationAngle / 360 * cycle, u)}', + color: _hex(tokens.arcText), size: 12, weight: '700'); + _b.write(''); + } + _b.write(''); + + // 标签分组:左侧动作标识与工位/驱动信息。 + _b.write(''); + for (int i = 0; i < ordered.length; i++) { + final Action a = ordered[i]; + final double y = layout.yFor(i); + _text(BarLayout.leftGutter + 6, y + 8, '${a.id} ${a.name}', color: _hex(tokens.text), size: 13, weight: '600'); + _text(BarLayout.leftGutter + 6, y + 24, '${a.stationId} · ${a.driver}', color: _hex(tokens.dim), size: 10.5); + } + _b.write(''); + + // 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移角语义。 + if (project.viewState.showDeps) { + _b.write(''); + final Map index = {}; + for (int i = 0; i < ordered.length; i++) { + index[ordered[i].id] = i; + } + for (final Action to in ordered) { + for (final Dependency d in to.deps) { + final Action? from = project.actionById(d.fromId); + if (from == null) continue; + final Rect ra = layout.rectFor(from); + final Rect rb = layout.rectFor(to); + final bool fs = d.type == DepType.fs; + final Color col = fs ? tokens.fs : tokens.ss; + final double sx = fs ? ra.right : ra.left; + final double sy = ra.center.dy; + final double tx = rb.left + 12; + final double ty = rb.center.dy - 10; + final String dPath = 'M $sx $sy L $sx ${(sy + ty) / 2} L $tx ${(sy + ty) / 2} L $tx $ty'; + _b.write(''); + } + } + _b.write(''); + } + } + + /// 生成圆形视图的 SVG 内容。 + /// + /// 参数 [size] 用于构建 [CircularLayout]。 + /// 依次输出: + /// - `g#layers`:同心圆环背景(奇偶层交替着色)。 + /// - `g#ruler`:每 30° 的刻度与度数。 + /// - `g#actions`:动作弧,跨循环动作经 [splitArcs] 拆成多段。 + /// - `g#dependencies`(可选):沿半径与圆弧的依赖路径。 + void _circularView(Size size) { + final CircularLayout layout = CircularLayout(project, size); + final Offset c = layout.center; + final double th = layout.th; + + // 圆环层背景分组。 + _b.write(''); + for (int i = 0; i <= project.maxLayer; i++) { + final double r = layout.radiusFor(i); + _circle(c.dx, c.dy, r, stroke: _hex(i.isEven ? tokens.ringA : tokens.ringB), sw: th); + } + _b.write(''); + + // 角度刻度分组,data-axis 标记角度轴语义。 + _b.write(''); + for (int d = 0; d < 360; d += 30) { + final Offset p1 = polar(c, layout.tickR, d.toDouble()); + final Offset p2 = polar(c, layout.tickR + 16, d.toDouble()); + _line(p1.dx, p1.dy, p2.dx, p2.dy, stroke: _hex(tokens.line2), sw: 1); + final Offset lp = polar(c, layout.tickR + 34, d.toDouble()); + _text(lp.dx, lp.dy, '$d°', color: _hex(tokens.sub), size: 11, anchor: 'middle'); + } + _b.write(''); + + // 动作弧分组:跨循环动作由 splitArcs 拆段,逐段写 。 + _b.write(''); + for (final Action a in project.actions) { + final double r = layout.radiusFor(a.layer); + final Color col = Color(a.color); + _b.write(''); + for (final List s in splitArcs(a.startAngle, a.endAngle)) { + final String d = _arc(c, r, s[0], s[1]); + _b.write(''); + } + final Offset mp = polar(c, r, (a.startAngle + a.endAngle) / 2); + _text(mp.dx, mp.dy, '${a.id} ${a.name}', color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700'); + _b.write(''); + } + _b.write(''); + + // 依赖分组:路径由“半径 → 圆弧 → 半径”三段构成,与屏幕渲染一致。 + if (project.viewState.showDeps) { + _b.write(''); + for (final Action to in project.actions) { + for (final Dependency d in to.deps) { + final Action? A = project.actionById(d.fromId); + final Action? B = project.actionById(d.toId); + if (A == null || B == null) continue; + final double rA = layout.radiusFor(A.layer); + final double rB = layout.radiusFor(B.layer); + final double aEnd = math.min(A.endAngle, 360); + final double aStart = B.startAngle; + final bool skip = (A.layer - B.layer).abs() > 1; + final double rC = skip ? layout.rMax + 24 : (rA + rB) / 2; + final Offset p0 = polar(c, rA, aEnd); + final Offset p1 = polar(c, rC, aEnd); + final Offset p2 = polar(c, rC, aStart); + final double rTip = rC < rB ? rB - th / 2 - 4 : rB + th / 2 + 4; + final Offset p3 = polar(c, rTip, aStart); + final bool fs = d.type == DepType.fs; + final Color col = fs ? tokens.fs : tokens.ss; + final String dd = 'M ${p0.dx.toStringAsFixed(1)} ${p0.dy.toStringAsFixed(1)} ' + 'L ${p1.dx.toStringAsFixed(1)} ${p1.dy.toStringAsFixed(1)} ' + 'A $rC $rC 0 0 ${aStart >= aEnd ? 1 : 0} ${p2.dx.toStringAsFixed(1)} ${p2.dy.toStringAsFixed(1)} ' + 'L ${p3.dx.toStringAsFixed(1)} ${p3.dy.toStringAsFixed(1)}'; + _b.write(''); + } + } + _b.write(''); + } + } + + /// 写入图例分组,展示工程名、循环时长与 360° 的等价关系。 + /// + /// 参数 [w]/[h] 为画布宽高,用于定位到左下角。 + void _legend(double w, double h) { + _b.write(''); + _text(24, h - 28, '时序图工作台 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°', + color: _hex(tokens.sub), size: 13); + _b.write(''); + } + + /// 生成一段圆弧的 SVG `d` 路径字符串。 + /// + /// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。 + /// 通过 [polar] 求端点,按跨度是否大于 180° 设置 large-arc 标志, + /// sweep 固定为 1(顺时针)。 + String _arc(Offset c, double r, double a0, double a1) { + final Offset s = polar(c, r, a0); + final Offset e = polar(c, r, a1); + final int large = (a1 - a0) > 180 ? 1 : 0; + return 'M ${s.dx.toStringAsFixed(1)} ${s.dy.toStringAsFixed(1)} ' + 'A ${r.toStringAsFixed(1)} ${r.toStringAsFixed(1)} 0 $large 1 ${e.dx.toStringAsFixed(1)} ${e.dy.toStringAsFixed(1)}'; + } + + /// 写入一个 `` 元素。 + /// + /// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。 + void _rect(double x, double y, double w, double h, + {String? fill, double rx = 0, double opacity = 1}) { + _b.write(''); + } + + /// 写入一个 `` 元素。 + /// + /// 参数 [cx]/[cy] 圆心、[r] 半径;可选 [stroke] 描边色、[fill] 填充色、 + /// [sw] 描边宽度。 + void _circle(double cx, double cy, double r, {String? stroke, String? fill, double sw = 1}) { + _b.write(''); + } + + /// 写入一个 `` 元素。 + /// + /// 参数为两端点坐标;可选 [stroke] 描边色、[sw] 描边宽度。 + void _line(double x1, double y1, double x2, double y2, {String? stroke, double sw = 1}) { + _b.write(''); + } + + /// 写入一个 `` 元素。 + /// + /// 参数 [x]/[y] 锚点坐标、[s] 文本内容(会经 [_esc] 转义); + /// 可选 [color] 颜色、[size] 字号、[anchor] 水平锚点、[weight] 字重。 + /// 垂直方向统一使用 `dominant-baseline="middle"` 居中。 + void _text(double x, double y, String s, + {String? color, double size = 12, String anchor = 'start', String weight = '400'}) { + _b.write('${_esc(s)}'); + } + + /// 把 Flutter [Color] 转为 `#rrggbb` 字符串。 + /// + /// 忽略 alpha 通道;各通道四舍五入并补零到两位十六进制。 + static String _hex(Color c) { + final int r = (c.r * 255).round(); + final int g = (c.g * 255).round(); + final int b = (c.b * 255).round(); + return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}'; + } + + /// 转义 XML 文本中的特殊字符(`&`、`<`、`>`、`"`),防止破坏 SVG 结构。 + static String _esc(String s) => s + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); +} diff --git a/lib/layout/layout.dart b/lib/layout/layout.dart new file mode 100644 index 0000000..86ca928 --- /dev/null +++ b/lib/layout/layout.dart @@ -0,0 +1,264 @@ +/// 几何布局层:把领域模型 [Project] 映射为屏幕坐标,供绘制与命中测试使用。 +/// +/// 本层不持有任何可变状态、不修改模型,属于纯计算: +/// - 顶层的极坐标/角度/圆弧工具函数服务于圆周视图; +/// - [BarLayout] 负责条形(甘特)视图的行与列定位; +/// - [CircularLayout] 负责圆周视图的同心环定位与命中测试。 +/// 视图层根据这些坐标进行绘制与交互命中判断。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import '../model/models.dart'; + +/// 极坐标转直角坐标:以 [c] 为圆心、[r] 为半径、[deg] 为角度(0° 指向正上方)。 +Offset polar(Offset c, double r, double deg) { + final double t = (deg - 90) * math.pi / 180; + return Offset(c.dx + r * math.cos(t), c.dy + r * math.sin(t)); +} + +/// 已知圆心 [c] 与点 [p],求该点相对圆心的角度(度,0° 为正上方,范围 [0,360))。 +double angleOf(Offset c, Offset p) { + final double a = math.atan2(p.dy - c.dy, p.dx - c.dx) * 180 / math.pi + 90; + return a < 0 ? a + 360 : a; +} + +/// 构造从角度 [a0] 到 [a1] 的圆弧路径。 +/// +/// 参数 [c]:圆心;[r]:半径;[a0]/[a1]:起止角(度)。 +/// 返回:以起点 moveTo、经 arcToPoint 连接终点的 [Path];根据扫过角度决定 +/// 是否使用 largeArc,并根据扫角正负决定顺时针方向。 +Path arcPath(Offset c, double r, double a0, double a1) { + final Path p = Path(); + final Offset s = polar(c, r, a0); + final Offset e = polar(c, r, a1); + p.moveTo(s.dx, s.dy); + final double sweep = a1 - a0; + final int large = sweep.abs() > 180 ? 1 : 0; + p.arcToPoint( + e, + radius: Radius.circular(r), + largeArc: large == 1, + clockwise: sweep >= 0, + ); + return p; +} + +/// 将跨越 360° 的区间拆分为两段,便于分别绘制。 +/// +/// 若 [a1] <= 360 直接返回 `[[a0, a1]]`;否则返回 `[[a0, 360], [0, a1-360]]`。 +List> splitArcs(double a0, double a1) { + if (a1 <= 360) return >[[a0, a1]]; + return >[ + [a0, 360], + [0, a1 - 360], + ]; +} + +/// 计算动作在条形视图中的行顺序。 +/// +/// 规则: +/// 1. 先按「工位 order → 起始角 → id」得到**自动顺序**; +/// 2. 若存在显式行序(`Action.row >= 0`),则显式行序优先,其余按自动顺序追加。 +/// +/// 这样一旦用户上下拖拽过行,行位置就固定下来,**不会再随相位变化而跳动**, +/// 依赖箭头也就不会在水平拖动时乱跳。 +List orderActions(Project project) { + final List list = List.of(project.actions); + list.sort((Action a, Action b) { + final int sa = project.stationById(a.stationId)?.order ?? 0; + final int sb = project.stationById(b.stationId)?.order ?? 0; + if (sa != sb) return sa.compareTo(sb); + final int c = a.startAngle.compareTo(b.startAngle); + if (c != 0) return c; + return a.id.compareTo(b.id); + }); + final bool hasExplicit = list.any((Action a) => a.row >= 0); + if (hasExplicit) { + final List explicit = list.where((Action a) => a.row >= 0).toList() + ..sort((Action a, Action b) => a.row.compareTo(b.row)); + final List auto = list.where((Action a) => a.row < 0).toList(); + list + ..clear() + ..addAll(explicit) + ..addAll(auto); + } + return list; +} + +/// 条形(甘特)视图布局。 +/// +/// 横轴为相位角(0°–360°),纵轴为动作行。行顺序由 [ordered] 决定, +/// 行高 [pitch] 会根据可用高度自适应(限制在 46–66 之间)。 +class BarLayout { + /// 构造条形布局并计算行高。 + /// + /// 参数 [project]:项目数据;[size]:可用画布尺寸。 + /// 副作用:初始化 [pitch]。 + BarLayout(this.project, this.size) { + // 可用高度 = 总高 - 顶部留白 - 底部预留;按动作数均分并夹取到 [46, 66]。 + final int n = project.actions.length; + final double usable = size.height - topPad - bottomReserve; + pitch = n == 0 ? 66 : (usable / n).clamp(46, 66); + } + + /// 布局所依据的项目数据。 + final Project project; + + /// 可用画布尺寸。 + final Size size; + + /// 左侧标签栏宽度(像素):紧贴图表,避免动作名离图太远。 + static const double leftGutter = 210; + + /// 顶部留白(为标题/刻度等预留)。 + static const double topPad = 210; + + /// 单个动作条的高度(像素):与 11–13px 文字匹配,避免过厚。 + static const double barH = 26; + + /// 行的视觉参考高度(像素)。 + static const double rowVisual = 40; + + /// 底部预留空间(像素)。 + static const double bottomReserve = 350; + + /// 相邻动作行之间的垂直距离(像素)。 + late final double pitch; + + /// 绘图区左边界。 + double get plotLeft => leftGutter; + + /// 绘图区右边界(右侧留 56px)。 + double get plotRight => size.width - 56; + + /// 绘图区横向跨度(像素)。 + double get span => plotRight - plotLeft; + + /// 决定行先后的动作列表;见顶层函数 [orderActions]。 + List get ordered => orderActions(project); + + /// 相位角(度)转横坐标;角度先钳制到 `[0, 360]`。 + double xFor(double deg) => plotLeft + (deg.clamp(0, 360) / 360) * span; + + /// 行索引转纵坐标(该行顶部 y)。 + double yFor(int index) => topPad + index * pitch; + + /// 计算动作 [a] 的条形矩形。 + /// + /// 宽度至少为 3px,避免极短动作不可见;跨圈部分会被截断到 360°。 + Rect rectFor(Action a) { + final int i = ordered.indexOf(a); + final double y = yFor(i); + final double x0 = xFor(a.startAngle); + final double x1 = xFor(math.min(a.endAngle, 360)); + return Rect.fromLTWH(x0, y, math.max(x1 - x0, 3), barH); + } + + /// 命中测试:返回坐标 [p] 处最上层的动作,未命中返回 null。 + /// + /// 从后往前遍历(后绘制的在上层),并向外膨胀 4px 提升可点性。 + Action? hitTest(Offset p) { + for (int i = ordered.length - 1; i >= 0; i--) { + final Action a = ordered[i]; + final Rect r = rectFor(a).inflate(4); + if (r.contains(p)) return a; + } + return null; + } + + /// 横坐标反算相位角(度),结果钳制在 `[0, 360]`。 + double angleAt(double x) => ((x - plotLeft) / span * 360).clamp(0, 360); +} + +/// 圆周(环形)视图布局。 +/// +/// 每个动作的层 [Action.layer] 决定其所在同心环的半径,角度区间决定环上的弧段。 +class CircularLayout { + /// 构造圆周布局并计算圆心、环间距与环宽。 + /// + /// 参数 [project]:项目数据;[size]:可用画布尺寸。 + /// 副作用:初始化 [center]、[pitch]、[ringWidth]。 + CircularLayout(this.project, this.size) { + // 圆心略微下移 18px 以平衡顶部刻度标签的视觉重心。 + center = Offset(size.width / 2, size.height / 2 + 18); + final int layers = project.maxLayer + 1; + // 最大半径受较短边约束,减去 74px 留给刻度与边距。 + final double maxR = math.min(size.width, size.height) / 2 - 74; + // 在 r0 与 maxR 之间均分各层,环间距夹取到 [24, 46]。 + pitch = layers <= 1 ? 40 : ((maxR - r0) / (layers - 1)).clamp(24, 46); + // 动作环带宽度:相对行距收窄(约 0.56),并夹取到 [12, 26], + // 让环与环之间留出呼吸空间、文字仍能容纳。 + ringWidth = (pitch * 0.56).clamp(12, 26); + } + + /// 布局所依据的项目数据。 + final Project project; + + /// 可用画布尺寸。 + final Size size; + + /// 最内层(第 0 层)半径(像素)。 + static const double r0 = 58; + + /// 圆心坐标。 + late final Offset center; + + /// 相邻层之间的半径差(像素)。 + late final double pitch; + + /// 环的视觉宽度(像素)。 + late final double ringWidth; + + /// 第 [layer] 层对应的环半径。 + double radiusFor(int layer) => r0 + layer * pitch; + + /// 最外层半径。 + double get rMax => radiusFor(project.maxLayer); + + /// 刻度标签所在的半径(最外层再向外偏移)。 + /// 刻度环半径:在外层动作环之外留出足够间距, + /// 供相位分区带独立占位(不与动作环挤在一起)。 + double get tickR => rMax + ringWidth / 2 + 38; + + /// 环宽别名,供绘制代码使用。 + double get th => ringWidth; + + /// 命中测试:返回坐标 [p] 命中的动作,未命中返回 null。 + /// + /// 算法:计算点相对圆心的距离 [d] 与角度 [a];遍历所有动作,先按径向 + /// 距离过滤(与所在环的偏差不超过半个环宽 + 3px),再判断角度是否落在 + /// 该动作弧段内;在候选中取径向偏差最小者。 + Action? hitTest(Offset p) { + final double d = (p - center).distance; + final double a = angleOf(center, p); + Action? best; + double bestDelta = double.infinity; + for (final Action a2 in project.actions) { + final double r = radiusFor(a2.layer); + if ((d - r).abs() > ringWidth / 2 + 3) continue; + if (_inArc(a2, a)) { + final double delta = (d - r).abs(); + if (delta < bestDelta) { + bestDelta = delta; + best = a2; + } + } + } + return best; + } + + /// 判断角度 [deg] 是否落在动作 [a] 的弧段内(含 0.5° 容差)。 + /// + /// 当动作不跨圈(endAngle <= 360)时为普通区间判断;跨圈时区间回绕, + /// 条件变为 `n >= start-0.5 或 n <= (end-360)+0.5`。 + bool _inArc(Action a, double deg) { + final double e = a.endAngle; + final double n = deg % 360; + if (e <= 360) { + return n >= a.startAngle - 0.5 && n <= e + 0.5; + } + return n >= a.startAngle - 0.5 || n <= (e - 360) + 0.5; + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..1ccefc7 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,161 @@ +// 应用入口:负责初始化持久化存储、启动 Flutter 应用,并承载全局的 +// 应用控制器(AppController)与应用生命周期管理。 +// +// 架构位置:本文件位于最外层,向下装配 AppShell(UI 外壳)与 +// Storage(本地持久化),并通过 AppController 向整个 UI 层提供状态与 +// 业务动作。启动后还会检查是否存在异常退出遗留的自动快照,并引导用户 +// 选择恢复方式。 +import 'dart:ui' show AppExitResponse; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'model/models.dart'; +import 'persistence/storage.dart'; +import 'state/app_controller.dart'; +import 'theme/tokens.dart'; +import 'ui/app_shell.dart'; + +// ===================== 应用启动与生命周期 ===================== + +/// 应用引导入口:确保 Flutter 绑定初始化完成、加载本地存储, +/// 然后启动根组件 [SequenceDiagramApp]。 +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await Storage.instance.init(); + runApp(const SequenceDiagramApp()); +} + +/// 应用根组件:创建并持有全局 [AppController],挂接应用生命周期监听, +/// 并在首帧渲染完成后触发未保存会话的恢复检查。 +class SequenceDiagramApp extends StatefulWidget { + /// 创建应用根组件。 + const SequenceDiagramApp({super.key}); + + /// 创建根组件对应的状态对象。 + @override + State createState() => _SequenceDiagramAppState(); +} + +/// 根组件状态:负责控制器的创建/释放、退出前的快照标记, +/// 以及启动阶段的恢复流程。 +class _SequenceDiagramAppState extends State { + /// 全局应用控制器,负责项目状态与所有业务操作。 + late final AppController _controller; + + /// 应用生命周期监听器,用于在系统请求退出时先把快照标记为干净。 + AppLifecycleListener? _lifecycle; + + /// 初始化控制器、注册退出回调,并在首帧后检查恢复快照。 + @override + void initState() { + super.initState(); + _controller = AppController()..start(); + _controller.addListener(_updateWindowTitle); + _lifecycle = AppLifecycleListener( + onExitRequested: () async { + await _controller.markCleanOnExit(); + return AppExitResponse.exit; + }, + ); + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateWindowTitle(); + _checkRecovery(); + }); + } + + /// 原生窗口标题通道(在 Windows runner 中实现 SetWindowText)。 + static const MethodChannel _windowChannel = MethodChannel('seqstudio/window'); + + /// 更新原生窗口标题为「时序图工作台 - <文件名 | 未命名文件>」, + /// 有未保存修改时追加 ` *`。 + void _updateWindowTitle() { + final String name = _controller.filePath == null + ? '未命名文件' + : _controller.filePath!.split(RegExp(r'[\\/]')).last; + final String dirty = _controller.dirty ? ' *' : ''; + _windowChannel + .invokeMethod('setTitle', '时序图工作台 - $name$dirty') + .catchError((Object _) {}); + } + + /// 释放生命周期监听器与控制器资源。 + @override + void dispose() { + _controller.removeListener(_updateWindowTitle); + _lifecycle?.dispose(); + _controller.dispose(); + super.dispose(); + } + + /// 检查上次运行遗留的自动快照,弹出对话框让用户选择: + /// 恢复自动快照、从 .bak 备份恢复,或忽略并删除快照。 + Future _checkRecovery() async { + final RecoveryInfo? info = await Storage.instance.checkRecovery(); + if (info == null || !mounted) return; + final int? choice = await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext ctx) { + return AlertDialog( + title: const Text('检测到未正常退出的会话'), + content: SizedBox( + width: 460, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('上次运行没有正常退出,已找到自动保存的快照。'), + const SizedBox(height: 8), + Text('快照时间:${info.updatedAt.toLocal().toString().substring(0, 19)}'), + Text('原始文件:${info.projectPath ?? '(未保存到文件)'}'), + if (info.bakContent != null) + Text('.bak 备份:${info.bakPath}', style: const TextStyle(fontSize: 11)), + const SizedBox(height: 12), + const Text('请选择要恢复的内容:'), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, 2), child: const Text('忽略并删除快照')), + if (info.bakContent != null) + OutlinedButton(onPressed: () => Navigator.pop(ctx, 1), child: const Text('从 .bak 恢复')), + FilledButton(onPressed: () => Navigator.pop(ctx, 0), child: const Text('恢复自动快照')), + ], + ); + }, + ); + // 用户取消或选择忽略:直接清除快照,不恢复任何内容。 + if (choice == null || choice == 2) { + await Storage.instance.clearRecovery(); + return; + } + // 恢复流程:choice == 1 走 .bak 备份,否则走自动快照;解码失败时静默忽略。 + try { + if (choice == 1 && info.bakContent != null) { + _controller.loadProject(Project.decode(info.bakContent!), path: info.projectPath, dirty: true); + } else { + _controller.loadProject(Project.decode(info.content), path: info.projectPath, dirty: true); + } + _controller.setStatus('已恢复未保存的会话'); + } catch (_) {} + } + + /// 构建 [MaterialApp]:监听控制器变化,按当前主题亮度装配配色, + /// 统一收紧文本缩放比例后加载 [AppShell]。 + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (BuildContext context, Widget? child) { + final Tokens tokens = Tokens.of(_controller.brightness); + return MaterialApp( + title: '时序图工作台 · Sequence Diagram Studio', + debugShowCheckedModeBanner: false, + theme: buildTheme(tokens), + home: AppShell(controller: _controller), + ); + }, + ); + } +} diff --git a/lib/model/models.dart b/lib/model/models.dart new file mode 100644 index 0000000..478c6b2 --- /dev/null +++ b/lib/model/models.dart @@ -0,0 +1,937 @@ +/// 数据模型层:定义序列图(Sequence Diagram)的领域模型与序列化协议。 +/// +/// 本文件是整个应用的“单一事实来源”,不依赖任何 UI 或持久化实现, +/// 由 layout / state / persistence 等上层模块共同引用: +/// - [Project] 聚合工位、动作、节拍、单位与视图状态; +/// - 所有模型均提供 copyWith / toJson / fromJson,保证不可变更新与 +/// JSON 往返(round-trip)序列化; +/// - 动作之间的时序约束由 [Dependency] 描述,供关键路径计算使用。 +library; + +import 'dart:convert'; + +/// 主视图模式。 +enum ViewMode { + /// 条形(甘特式)节拍视图。 + bar, + + /// 圆周(环形)节拍视图。 + circular, +} + +/// 时间单位。 +enum TimeUnit { + /// 毫秒。 + ms, + + /// 秒。 + s, + + /// 分钟。 + min, +} + +/// 相位单位。 +enum PhaseUnit { + /// 角度(度)。 + deg, + + /// 百分比(相对整圈 360° 的比例)。 + percent, +} + +/// 动作依赖类型(前驱/后继的开始或结束关系)。 +enum DepType { + /// Finish-to-Start:前驱结束之后,后继才能开始。 + fs, + + /// Start-to-Start:前驱开始之后,后继才能开始。 + ss, + + /// Finish-to-Finish:前驱结束后,后继才能结束。 + ff, + + /// Start-to-Finish:前驱开始后,后继才能结束。 + sf, +} + +/// 圆周视图的旋转方向。 +enum CycleDirection { + /// 顺时针。 + cw, + + /// 逆时针。 + ccw, +} + +/// 圆周视图的 0° 起始位置。 +enum CycleOrigin { + /// 十二点钟方向为起点。 + twelve, + + /// 三点钟方向为起点。 + three, +} + +/// 修改循环时长时对动作相位的处理策略。 +enum CycleInputPolicy { + /// 保持角度不变(仅改变时长与时间换算)。 + keepAngle, + + /// 保持时间不变(按比例缩放角度)。 + keepTime, +} + +/// 新增动作时循环取用的默认配色板(ARGB 颜色值)。 +const List kActionPalette = [ + 0xFF4CC9F0, + 0xFF7BD88F, + 0xFFFFD166, + 0xFFFF8A5C, + 0xFFF472B6, + 0xFFA78BFA, + 0xFF38BDF8, + 0xFF34D399, +]; + +/// 将 ARGB 整数颜色序列化为 `#rrggbb` 十六进制字符串(丢弃透明度通道)。 +/// +/// 参数 [argb]:32 位 ARGB 颜色值。 +/// 返回:形如 `#4cc9f0` 的字符串,用于 JSON 持久化。 +String colorToHex(int argb) { + final int rgb = argb & 0xFFFFFF; + return '#${rgb.toRadixString(16).padLeft(6, '0')}'; +} + +/// 将 `#rrggbb`(可带 `#`,大小写均可)解析为不透明的 ARGB 整数。 +/// +/// 参数 [hex]:十六进制颜色字符串。 +/// 返回:`0xFF000000 | rgb`;解析失败时回退到默认色 `0x4CC9F0`。 +int hexToColor(String hex) { + final String h = hex.replaceAll('#', '').trim(); + final int rgb = int.tryParse(h, radix: 16) ?? 0x4CC9F0; + return 0xFF000000 | (rgb & 0xFFFFFF); +} + +/// 动作之间的时序依赖:由 [fromId] 指向 [toId],描述二者的开始/结束约束。 +/// +/// 依赖会被关键路径算法(见 AppController._recomputeCritical)用来计算 +/// 各动作的最早开始时间,并高亮关键链。 +class Dependency { + /// 构造一条依赖。 + /// + /// 参数 [fromId]:前驱动作 id;[toId]:后继动作 id; + /// [type]:依赖类型,默认 [DepType.fs];[offsetAngle]:附加相位偏移(度)。 + const Dependency({ + required this.fromId, + required this.toId, + this.type = DepType.fs, + this.offsetAngle = 0, + }); + + /// 前驱动作 id。 + final String fromId; + + /// 后继动作 id。 + final String toId; + + /// 依赖类型(FS/SS/FF/SF)。 + final DepType type; + + /// 依赖的附加角度偏移,单位:度。 + final double offsetAngle; + + /// 基于当前实例创建副本,未提供的参数保持原值。 + Dependency copyWith({ + String? fromId, + String? toId, + DepType? type, + double? offsetAngle, + }) { + return Dependency( + fromId: fromId ?? this.fromId, + toId: toId ?? this.toId, + type: type ?? this.type, + offsetAngle: offsetAngle ?? this.offsetAngle, + ); + } + + /// 序列化为 JSON;依赖类型以大写形式(如 `FS`)写出,便于跨版本读取。 + Map toJson() => { + 'fromId': fromId, + 'toId': toId, + 'type': type.name.toUpperCase(), + 'offsetAngle': offsetAngle, + }; + + /// 从 JSON 反序列化;缺失字段使用安全默认值,保证旧文件可加载。 + static Dependency fromJson(Map j) { + return Dependency( + fromId: j['fromId'] as String? ?? '', + toId: j['toId'] as String? ?? '', + type: _depTypeFrom(j['type'] as String?), + offsetAngle: (j['offsetAngle'] as num?)?.toDouble() ?? 0, + ); + } + + /// 将字符串(不区分大小写)解析为 [DepType],无法识别时回退为 FS。 + static DepType _depTypeFrom(String? s) { + switch ((s ?? 'FS').toUpperCase()) { + case 'SS': + return DepType.ss; + case 'FF': + return DepType.ff; + case 'SF': + return DepType.sf; + default: + return DepType.fs; + } + } +} + +/// 单个动作(工序):序列图的核心实体,用角度表示其在节拍周期内的区间。 +/// +/// 不变式:`0 <= startAngle`,`durationAngle > 0`,且二者共同构成一个 +/// 角度区间 `[startAngle, startAngle + durationAngle]`;当结束角超过 360° +/// 时视为跨圈(见 [wrap])。 +class Action { + /// 构造一个动作。 + /// + /// 参数 [id]:唯一标识;[name]:显示名称;[stationId]:所属工位; + /// [driver]:执行元件/驱动描述;[startAngle]/[durationAngle]:起始角与持续角; + /// [layer]:圆周视图中的层(半径序号);[color]:ARGB 颜色; + /// [deps]:该动作作为后继的依赖列表(即指向本动作的边)。 + const Action({ + required this.id, + required this.name, + required this.stationId, + required this.driver, + required this.startAngle, + required this.durationAngle, + required this.layer, + required this.color, + this.row = -1, + this.deps = const [], + }); + + /// 动作唯一标识,如 `A1`。 + final String id; + + /// 动作显示名称。 + final String name; + + /// 所属工位 id,对应 [Station.id]。 + final String stationId; + + /// 执行元件/驱动的描述文本。 + final String driver; + + /// 起始相位角,单位:度。 + final double startAngle; + + /// 持续相位角(区间宽度),单位:度。 + final double durationAngle; + + /// 圆周视图中的层号(越大半径越大)。 + final int layer; + + /// 动作颜色(ARGB)。 + final int color; + + /// 条形视图中的行序(自上而下,从 0 开始)。 + /// + /// `-1` 表示“未指定”,此时由 [BarLayout] 按工位与起始角自动排序; + /// 一旦用户上下拖拽过行,就写入显式行序,行位置不再随相位变化而跳动。 + final int row; + + /// 指向本动作的依赖集合(本动作作为后继)。 + final List deps; + + /// 结束相位角 = 起始角 + 持续角,单位:度。 + double get endAngle => startAngle + durationAngle; + + /// 是否跨圈(结束角超过 360°,预留微小浮点容差)。 + bool get wrap => endAngle > 360.0001; + + /// 基于当前实例创建副本,未提供的参数保持原值。 + Action copyWith({ + String? id, + String? name, + String? stationId, + String? driver, + double? startAngle, + double? durationAngle, + int? layer, + int? color, + int? row, + List? deps, + }) { + return Action( + id: id ?? this.id, + name: name ?? this.name, + stationId: stationId ?? this.stationId, + driver: driver ?? this.driver, + startAngle: startAngle ?? this.startAngle, + durationAngle: durationAngle ?? this.durationAngle, + layer: layer ?? this.layer, + color: color ?? this.color, + row: row ?? this.row, + deps: deps ?? this.deps, + ); + } + + /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存,依赖递归序列化。 + Map toJson() => { + 'id': id, + 'name': name, + 'stationId': stationId, + 'driver': driver, + 'startAngle': startAngle, + 'durationAngle': durationAngle, + 'layer': layer, + 'color': colorToHex(color), + 'row': row, + 'deps': deps.map((Dependency d) => d.toJson()).toList(), + }; + + /// 从 JSON 反序列化;字段缺失或类型异常时使用默认值以保证健壮性。 + static Action fromJson(Map j) { + return Action( + id: j['id'] as String? ?? 'A?', + name: j['name'] as String? ?? '动作', + stationId: j['stationId'] as String? ?? 'ST1', + driver: j['driver'] as String? ?? '', + startAngle: (j['startAngle'] as num?)?.toDouble() ?? 0, + durationAngle: (j['durationAngle'] as num?)?.toDouble() ?? 0, + layer: (j['layer'] as num?)?.toInt() ?? 0, + color: hexToColor(j['color'] as String? ?? '#4cc9f0'), + row: (j['row'] as num?)?.toInt() ?? -1, + deps: ((j['deps'] as List?) ?? []) + .map((dynamic e) => Dependency.fromJson(e as Map)) + .toList(), + ); + } +} + +/// 工位:动作的归属单元,决定条形视图中动作的分组与排序。 +class Station { + /// 构造一个工位。 + /// + /// 参数 [id]:唯一标识;[name]:显示名称;[order]:排序权重(越小越靠前); + /// [color]:ARGB 颜色。 + const Station({ + required this.id, + required this.name, + required this.order, + required this.color, + }); + + /// 工位唯一标识,如 `ST1`。 + final String id; + + /// 工位显示名称。 + final String name; + + /// 排序权重,用于条形视图对动作排序。 + final int order; + + /// 工位颜色(ARGB)。 + final int color; + + /// 基于当前实例创建副本,未提供的参数保持原值。 + Station copyWith({String? id, String? name, int? order, int? color}) { + return Station( + id: id ?? this.id, + name: name ?? this.name, + order: order ?? this.order, + color: color ?? this.color, + ); + } + + /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存。 + Map toJson() => { + 'id': id, + 'name': name, + 'order': order, + 'color': colorToHex(color), + }; + + /// 从 JSON 反序列化;缺失字段使用默认值。 + static Station fromJson(Map j) { + return Station( + id: j['id'] as String? ?? 'ST1', + name: j['name'] as String? ?? '工位', + order: (j['order'] as num?)?.toInt() ?? 0, + color: hexToColor(j['color'] as String? ?? '#4cc9f0'), + ); + } +} + +/// 节拍(循环)参数:定义整圈对应的时长、起始角、旋转方向与吸附精度。 +/// +/// 不变式:`durationMs > 0`,`snapDeg >= 0`(为 0 表示不吸附)。 +class Cycle { + /// 构造节拍参数。 + /// + /// 参数 [durationMs]:整圈时长(毫秒),默认 2400;[startAngle]:起始相位角; + /// [direction]:旋转方向;[origin]:0° 基准位置;[snapDeg]:角度吸附步长(度)。 + const Cycle({ + this.durationMs = 2400, + this.startAngle = 0, + this.direction = CycleDirection.cw, + this.origin = CycleOrigin.twelve, + this.snapDeg = 1, + }); + + /// 整圈对应的时长,单位:毫秒。 + final double durationMs; + + /// 循环起始相位角,单位:度。 + final double startAngle; + + /// 旋转方向(顺/逆时针)。 + final CycleDirection direction; + + /// 0° 基准位置。 + final CycleOrigin origin; + + /// 角度吸附步长,单位:度;0 表示禁用吸附。 + final double snapDeg; + + /// 基于当前实例创建副本,未提供的参数保持原值。 + Cycle copyWith({ + double? durationMs, + double? startAngle, + CycleDirection? direction, + CycleOrigin? origin, + double? snapDeg, + }) { + return Cycle( + durationMs: durationMs ?? this.durationMs, + startAngle: startAngle ?? this.startAngle, + direction: direction ?? this.direction, + origin: origin ?? this.origin, + snapDeg: snapDeg ?? this.snapDeg, + ); + } + + /// 序列化为 JSON;枚举以 name 字符串保存。 + Map toJson() => { + 'durationMs': durationMs, + 'startAngle': startAngle, + 'direction': direction.name, + 'origin': origin.name, + 'snapDeg': snapDeg, + }; + + /// 从 JSON 反序列化;未知枚举值回退为默认(顺时针、十二点钟方向)。 + static Cycle fromJson(Map j) { + return Cycle( + durationMs: (j['durationMs'] as num?)?.toDouble() ?? 2400, + startAngle: (j['startAngle'] as num?)?.toDouble() ?? 0, + direction: (j['direction'] as String?) == 'ccw' + ? CycleDirection.ccw + : CycleDirection.cw, + origin: (j['origin'] as String?) == '3o' + ? CycleOrigin.three + : CycleOrigin.twelve, + snapDeg: (j['snapDeg'] as num?)?.toDouble() ?? 1, + ); + } +} + +/// 单位与显示设置:控制时间/相位的显示格式、吸附步长与网格行为。 +/// +/// 该设置属于项目数据的一部分,会随项目一起持久化。 +class UnitSettings { + /// 构造单位设置。 + /// + /// 参数 [timeUnit]/[phaseUnit]:时间与相位单位;[precision]:小数位数, + /// 负数表示自动;[snapAngle]/[snapTime]:角度与时间吸附步长; + /// [cycleInputPolicy]:修改循环时长时保持角度还是保持时间; + /// [showGrid]/[snapGrid]:网格显示与吸附开关;[autoSplitWrap]:跨圈自动拆分; + /// [preset]:预设方案标识。 + const UnitSettings({ + this.timeUnit = TimeUnit.s, + this.phaseUnit = PhaseUnit.deg, + this.precision = -1, + this.snapAngle = 1, + this.snapTime = 0.1, + this.cycleInputPolicy = CycleInputPolicy.keepAngle, + this.showGrid = true, + this.snapGrid = true, + this.autoSplitWrap = true, + this.preset = 'assembly', + }); + + /// 时间显示单位。 + final TimeUnit timeUnit; + + /// 相位显示单位。 + final PhaseUnit phaseUnit; + + /// 小数位数;负数表示按单位自动决定(见 units.dart 的 `_dec`)。 + final int precision; + + /// 角度吸附步长,单位:度。 + final double snapAngle; + + /// 时间吸附步长,单位:毫秒(由调用方换算)。 + final double snapTime; + + /// 修改循环时长时对动作相位的处理策略。 + final CycleInputPolicy cycleInputPolicy; + + /// 是否显示网格。 + final bool showGrid; + + /// 是否吸附到网格。 + final bool snapGrid; + + /// 跨圈动作是否自动拆分显示。 + final bool autoSplitWrap; + + /// 当前单位预设标识。 + final String preset; + + /// 基于当前实例创建副本,未提供的参数保持原值。 + UnitSettings copyWith({ + TimeUnit? timeUnit, + PhaseUnit? phaseUnit, + int? precision, + double? snapAngle, + double? snapTime, + CycleInputPolicy? cycleInputPolicy, + bool? showGrid, + bool? snapGrid, + bool? autoSplitWrap, + String? preset, + }) { + return UnitSettings( + timeUnit: timeUnit ?? this.timeUnit, + phaseUnit: phaseUnit ?? this.phaseUnit, + precision: precision ?? this.precision, + snapAngle: snapAngle ?? this.snapAngle, + snapTime: snapTime ?? this.snapTime, + cycleInputPolicy: cycleInputPolicy ?? this.cycleInputPolicy, + showGrid: showGrid ?? this.showGrid, + snapGrid: snapGrid ?? this.snapGrid, + autoSplitWrap: autoSplitWrap ?? this.autoSplitWrap, + preset: preset ?? this.preset, + ); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'timeUnit': timeUnit.name, + 'phaseUnit': phaseUnit.name, + 'precision': precision, + 'snapAngle': snapAngle, + 'snapTime': snapTime, + 'cycleInputPolicy': cycleInputPolicy.name, + 'showGrid': showGrid, + 'snapGrid': snapGrid, + 'autoSplitWrap': autoSplitWrap, + 'preset': preset, + }; + + /// 从 JSON 反序列化;枚举按 name 匹配,无法匹配时回退到默认值。 + static UnitSettings fromJson(Map j) { + return UnitSettings( + timeUnit: TimeUnit.values.firstWhere( + (TimeUnit u) => u.name == j['timeUnit'], + orElse: () => TimeUnit.s, + ), + phaseUnit: PhaseUnit.values.firstWhere( + (PhaseUnit u) => u.name == j['phaseUnit'], + orElse: () => PhaseUnit.deg, + ), + precision: (j['precision'] as num?)?.toInt() ?? -1, + snapAngle: (j['snapAngle'] as num?)?.toDouble() ?? 1, + snapTime: (j['snapTime'] as num?)?.toDouble() ?? 0.1, + cycleInputPolicy: (j['cycleInputPolicy'] as String?) == 'keepTime' + ? CycleInputPolicy.keepTime + : CycleInputPolicy.keepAngle, + showGrid: j['showGrid'] as bool? ?? true, + snapGrid: j['snapGrid'] as bool? ?? true, + autoSplitWrap: j['autoSplitWrap'] as bool? ?? true, + preset: j['preset'] as String? ?? 'assembly', + ); + } +} + +/// 视图状态:记录当前视图模式、缩放/平移以及各类显示开关和选中项。 +/// +/// 不变式:[zoom] 由 AppController.setZoom 限制在 `[0.25, 4.0]`; +/// [selectedId] 为 null 表示无选中。该状态随项目持久化,但不参与业务计算。 +class ViewState { + /// 构造视图状态。 + /// + /// 参数 [mode]:视图模式;[zoom]:缩放系数;[panX]/[panY]:平移量; + /// [showDeps]/[showRuler]/[showPhaseBands]/[showRingBg]/[showLayerLabels]: + /// 各类显示开关;[selectedId]:当前选中动作 id。 + const ViewState({ + this.mode = ViewMode.bar, + this.zoom = 1.0, + this.panX = 0, + this.panY = 0, + this.showDeps = true, + this.showRuler = true, + this.showPhaseBands = true, + this.showRingBg = true, + this.showLayerLabels = true, + this.selectedIds = const [], + }); + + /// 当前视图模式(条形/圆周)。 + final ViewMode mode; + + /// 缩放系数。 + final double zoom; + + /// 水平平移量(像素)。 + final double panX; + + /// 垂直平移量(像素)。 + final double panY; + + /// 是否显示依赖连线。 + final bool showDeps; + + /// 是否显示刻度尺。 + final bool showRuler; + + /// 是否显示相位分区色带。 + final bool showPhaseBands; + + /// 是否显示圆周背景环。 + final bool showRingBg; + + /// 是否显示层标签。 + final bool showLayerLabels; + + /// 当前选中的动作 id 列表(支持 Ctrl 多选);空表示无选中。 + /// + /// 约定:**第一个元素为主选中项**(右侧属性面板展示它)。 + final List selectedIds; + + /// 主选中动作 id(列表首项);空表示无选中。 + String? get selectedId => selectedIds.isEmpty ? null : selectedIds.first; + + /// 判断动作 [id] 是否被选中。 + bool isSelected(String id) => selectedIds.contains(id); + + /// 基于当前实例创建副本。 + ViewState copyWith({ + ViewMode? mode, + double? zoom, + double? panX, + double? panY, + bool? showDeps, + bool? showRuler, + bool? showPhaseBands, + bool? showRingBg, + bool? showLayerLabels, + List? selectedIds, + }) { + return ViewState( + mode: mode ?? this.mode, + zoom: zoom ?? this.zoom, + panX: panX ?? this.panX, + panY: panY ?? this.panY, + showDeps: showDeps ?? this.showDeps, + showRuler: showRuler ?? this.showRuler, + showPhaseBands: showPhaseBands ?? this.showPhaseBands, + showRingBg: showRingBg ?? this.showRingBg, + showLayerLabels: showLayerLabels ?? this.showLayerLabels, + selectedIds: selectedIds ?? this.selectedIds, + ); + } + + /// 序列化为 JSON;平移量以二元数组 `[panX, panY]` 保存。 + Map toJson() => { + 'mode': mode.name, + 'zoom': zoom, + 'pan': [panX, panY], + 'showDeps': showDeps, + 'showRuler': showRuler, + 'showPhaseBands': showPhaseBands, + 'showRingBg': showRingBg, + 'showLayerLabels': showLayerLabels, + 'selectedIds': selectedIds, + }; + + /// 从 JSON 反序列化;选中项用于界面恢复,缺失时默认无选中。 + static ViewState fromJson(Map j) { + final List pan = (j['pan'] as List?) ?? [0, 0]; + final List sel = (j['selectedIds'] as List?) ?? []; + return ViewState( + mode: (j['mode'] as String?) == 'circular' ? ViewMode.circular : ViewMode.bar, + zoom: (j['zoom'] as num?)?.toDouble() ?? 1, + panX: (pan.isNotEmpty ? (pan[0] as num?)?.toDouble() : 0) ?? 0, + panY: (pan.length > 1 ? (pan[1] as num?)?.toDouble() : 0) ?? 0, + showDeps: j['showDeps'] as bool? ?? true, + showRuler: j['showRuler'] as bool? ?? true, + showPhaseBands: j['showPhaseBands'] as bool? ?? true, + showRingBg: j['showRingBg'] as bool? ?? true, + showLayerLabels: j['showLayerLabels'] as bool? ?? true, + selectedIds: sel.map((dynamic e) => e as String).toList(), + ); + } +} + +/// 相位分区:循环内的一个命名角度区间(例如“上料相位 0°–70°”)。 +/// +/// 用于在条形节拍视图顶部绘制工艺阶段标注带,也用于属性面板的“相位归属”判断。 +/// 区间允许 [endAngle] 超过 360° 以表示跨循环(例如“下料相位 335°–385°”)。 +class PhaseZone { + /// 构造相位分区。 + const PhaseZone({ + required this.name, + required this.startAngle, + required this.endAngle, + }); + + /// 分区名称(如“加工相位”)。 + final String name; + + /// 起始相位角(度,0° = 12 点钟方向)。 + final double startAngle; + + /// 结束相位角(度,可大于 360° 表示跨圈)。 + final double endAngle; + + /// 该分区的角度跨度。 + double get span => endAngle - startAngle; + + /// 判断给定角度 [deg] 是否落在本分区内(自动处理跨圈)。 + bool contains(double deg) { + final double n = deg % 360; + if (endAngle <= 360) { + return n >= startAngle - 0.001 && n <= endAngle + 0.001; + } + return n >= startAngle - 0.001 || n <= (endAngle - 360) + 0.001; + } + + /// 创建副本,未提供的参数保持原值。 + PhaseZone copyWith({String? name, double? startAngle, double? endAngle}) { + return PhaseZone( + name: name ?? this.name, + startAngle: startAngle ?? this.startAngle, + endAngle: endAngle ?? this.endAngle, + ); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'name': name, + 'startAngle': startAngle, + 'endAngle': endAngle, + }; + + /// 从 JSON 反序列化。 + static PhaseZone fromJson(Map j) { + return PhaseZone( + name: j['name'] as String? ?? '相位分区', + startAngle: (j['startAngle'] as num?)?.toDouble() ?? 0, + endAngle: (j['endAngle'] as num?)?.toDouble() ?? 0, + ); + } + + /// 默认相位分区:四等分的通用分区(分区 1–4)。 + /// + /// 用户可在工艺参数中改名、改起止角、增删数量,也可在条形图顶部直接拖拽边界。 + static const List defaults = [ + PhaseZone(name: '分区 1', startAngle: 0, endAngle: 90), + PhaseZone(name: '分区 2', startAngle: 90, endAngle: 180), + PhaseZone(name: '分区 3', startAngle: 180, endAngle: 270), + PhaseZone(name: '分区 4', startAngle: 270, endAngle: 360), + ]; +} + +/// 项目根聚合:包含节拍、工位、动作、单位与视图状态,是保存/加载的整体单元。 +/// +/// 不变式:[actions] 中的 id 唯一;动作的 [Action.stationId] 通常应存在于 +/// [stations] 中;依赖的 fromId/toId 应指向存在的动作。 +class Project { + /// 构造项目。 + /// + /// 参数 [name]:项目名称;[schema]:数据协议版本标识; + /// [cycle]:节拍参数;[stations]:工位列表;[actions]:动作列表; + /// [units]:单位设置;[viewState]:视图状态。 + const Project({ + required this.name, + this.schema = 'seqdiagram/1.2', + required this.cycle, + required this.stations, + required this.actions, + required this.units, + required this.viewState, + this.phaseZones = PhaseZone.defaults, + }); + + /// 项目名称。 + final String name; + + /// 数据协议版本标识,用于兼容性判断。 + final String schema; + + /// 节拍参数。 + final Cycle cycle; + + /// 工位列表。 + final List stations; + + /// 动作列表。 + final List actions; + + /// 单位与显示设置。 + final UnitSettings units; + + /// 视图状态。 + final ViewState viewState; + + /// 相位分区(命名角度区间),用于条形视图顶部工艺阶段标注。 + final List phaseZones; + + /// 按 id 查找动作;[id] 为 null 或未找到时返回 null。 + Action? actionById(String? id) { + if (id == null) return null; + for (final Action a in actions) { + if (a.id == id) return a; + } + return null; + } + + /// 按 id 查找工位;未找到时返回 null。 + Station? stationById(String id) { + for (final Station s in stations) { + if (s.id == id) return s; + } + return null; + } + + /// 所有动作中的最大层号;无动作时返回 0。 + int get maxLayer { + int m = 0; + for (final Action a in actions) { + if (a.layer > m) m = a.layer; + } + return m; + } + + /// 基于当前实例创建副本,未提供的参数保持原值。 + Project copyWith({ + String? name, + String? schema, + Cycle? cycle, + List? stations, + List? actions, + UnitSettings? units, + ViewState? viewState, + List? phaseZones, + }) { + return Project( + name: name ?? this.name, + schema: schema ?? this.schema, + cycle: cycle ?? this.cycle, + stations: stations ?? this.stations, + actions: actions ?? this.actions, + units: units ?? this.units, + viewState: viewState ?? this.viewState, + phaseZones: phaseZones ?? this.phaseZones, + ); + } + + /// 序列化为 JSON。外层包含 `schema` 版本号,实际数据位于 `project` 子对象。 + Map toJson() => { + 'schema': schema, + 'project': { + 'name': name, + 'units': units.toJson(), + 'cycle': cycle.toJson(), + 'stations': stations.map((Station s) => s.toJson()).toList(), + 'actions': actions.map((Action a) => a.toJson()).toList(), + 'viewState': viewState.toJson(), + 'phaseZones': phaseZones.map((PhaseZone z) => z.toJson()).toList(), + }, + }; + + /// 序列化为带两空格缩进的 JSON 文本,便于人工阅读与 diff。 + String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); + + /// 从 JSON 反序列化。 + /// + /// 兼容两种结构:带 `project` 子对象的正式格式,以及直接平铺的旧格式 + /// (当不存在 `project` 键时把根对象当作数据体)。 + static Project fromJson(Map j) { + final Map p = + (j['project'] as Map?) ?? j; + final List st = (p['stations'] as List?) ?? []; + final List ac = (p['actions'] as List?) ?? []; + final List pz = (p['phaseZones'] as List?) ?? []; + return Project( + name: p['name'] as String? ?? '未命名', + schema: j['schema'] as String? ?? 'seqdiagram/1.2', + cycle: Cycle.fromJson((p['cycle'] as Map?) ?? {}), + stations: st.map((dynamic e) => Station.fromJson(e as Map)).toList(), + actions: ac.map((dynamic e) => Action.fromJson(e as Map)).toList(), + units: UnitSettings.fromJson((p['units'] as Map?) ?? {}), + viewState: ViewState.fromJson((p['viewState'] as Map?) ?? {}), + phaseZones: pz.isEmpty + ? PhaseZone.defaults + : pz.map((dynamic e) => PhaseZone.fromJson(e as Map)).toList(), + ); + } + + /// 从 JSON 文本解码为 [Project]。 + static Project decode(String source) { + return Project.fromJson(jsonDecode(source) as Map); + } + + /// 构造内置演示项目(装配线节拍方案)。 + /// + /// 返回一个包含 2 个工位、2 个动作(动作 1 / 动作 2)的示例 [Project], + /// 用于首次启动展示。刻意保持精简,避免预设内容过多干扰用户。 + static Project demo() { + final List stations = [ + const Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0), + const Station(id: 'ST2', name: '工位 2', order: 1, color: 0xFFFFD166), + ]; + final List actions = [ + Action( + id: 'A1', + name: '动作 1', + stationId: 'ST1', + driver: '气缸 Y1', + startAngle: 0, + durationAngle: 70, + layer: 0, + row: 0, + color: kActionPalette[0], + ), + Action( + id: 'A2', + name: '动作 2', + stationId: 'ST2', + driver: '气缸 Y2', + startAngle: 80, + durationAngle: 60, + layer: 1, + row: 1, + color: kActionPalette[1], + deps: const [ + Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs), + ], + ), + ]; + return Project( + name: '未命名节拍', + cycle: const Cycle(durationMs: 2400), + stations: stations, + actions: actions, + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar, selectedIds: ['A1']), + ); + } +} diff --git a/lib/model/units.dart b/lib/model/units.dart new file mode 100644 index 0000000..a12ea49 --- /dev/null +++ b/lib/model/units.dart @@ -0,0 +1,151 @@ +/// 单位换算与格式化工具层。 +/// +/// 本文件集中处理“毫秒/角度”与用户可读文本之间的转换,供 UI 与控制器复用: +/// - 时间单位与相位单位的显示标签; +/// - 时间/角度数值格式化(含小数位策略); +/// - 用户输入文本的解析(`120ms`、`1.5s`、`30%`、`45°` 等); +/// - 数值钳制、吸附与角度归一化等通用数学工具。 +library; + +import 'models.dart'; + +/// 各时间单位相对毫秒的换算系数:`时间值 = 毫秒 / kTimeDiv[unit]`。 +const Map kTimeDiv = { + TimeUnit.ms: 1, + TimeUnit.s: 1000, + TimeUnit.min: 60000, +}; + +/// 各时间单位的默认小数位数,用于自动精度模式。 +const Map kTimeDec = { + TimeUnit.ms: 0, + TimeUnit.s: 3, + TimeUnit.min: 4, +}; + +/// 返回时间单位的显示标签(`ms` / `s` / `min`)。 +String timeUnitLabel(TimeUnit u) { + switch (u) { + case TimeUnit.ms: + return 'ms'; + case TimeUnit.s: + return 's'; + case TimeUnit.min: + return 'min'; + } +} + +/// 返回相位单位的显示标签(角度 `°` 或百分比 `%`)。 +String phaseUnitLabel(PhaseUnit u) => u == PhaseUnit.deg ? '°' : '%'; + +/// 将毫秒换算为指定时间单位的数值。 +double timeValue(double ms, TimeUnit u) => ms / kTimeDiv[u]!; + +/// 计算应保留的小数位数。 +/// +/// 优先级:[override](调用方显式指定)> [UnitSettings.precision](>=0 时) +/// > 该时间单位的默认精度。 +int _dec(UnitSettings u, int? override) { + if (override != null) return override; + if (u.precision >= 0) return u.precision; + return kTimeDec[u.timeUnit]!; +} + +/// 将毫秒格式化为带单位后缀的显示文本,如 `1.500 s`。 +/// +/// 参数 [ms]:毫秒值;[u]:单位设置;[dec]:可选的小数位覆盖。 +String tfmt(double ms, UnitSettings u, {int? dec}) { + return '${timeValue(ms, u.timeUnit).toStringAsFixed(_dec(u, dec))} ${timeUnitLabel(u.timeUnit)}'; +} + +/// 将毫秒格式化为仅含数值、不含单位的字符串,用于输入框回填。 +String tvalStr(double ms, UnitSettings u, {int dec = 1}) { + return timeValue(ms, u.timeUnit).toStringAsFixed(dec); +} + +/// 自动选择合适单位的毫秒格式化(不依赖 [UnitSettings])。 +/// +/// 规则:<100ms 用毫秒(1 位小数),<1000ms 用整数毫秒, +/// <60s 用秒(<10s 保留 3 位、否则 2 位),其余用分钟(3 位)。 +String tfmtAuto(double ms) { + if (ms < 100) return '${ms.toStringAsFixed(1)} ms'; + if (ms < 1000) return '${ms.round()} ms'; + if (ms < 60000) return '${(ms / 1000).toStringAsFixed(ms < 10000 ? 3 : 2)} s'; + return '${(ms / 60000).toStringAsFixed(3)} min'; +} + +/// 将角度格式化为显示文本。 +/// +/// 当单位为百分比时按 `deg / 3.6` 换算并保留 2 位小数;否则按角度显示。 +String pfmt(double deg, UnitSettings u, {int dec = 1}) { + if (u.phaseUnit == PhaseUnit.percent) { + return '${(deg / 3.6).toStringAsFixed(2)}%'; + } + return '${deg.toStringAsFixed(dec)}°'; +} + +/// 将相位角换算为时间并格式化为文本。 +/// +/// 参数 [deg]:角度;[u]:单位设置;[cycleMs]:整圈时长(毫秒); +/// [dec]:可选小数位覆盖。 +String deg2msStr(double deg, UnitSettings u, double cycleMs, {int? dec}) { + return tfmt(deg / 360 * cycleMs, u, dec: dec); +} + +/// 解析用户输入的时长文本,返回毫秒;无法解析时返回 null。 +/// +/// 支持后缀 `ms` / `s` / `min`(不区分大小写,可省略则按 [u] 的当前时间单位); +/// 例如 `120ms`、`1.5s`、`2 min`。 +double? parseDuration(String text, UnitSettings u) { + final String s = text.trim().toLowerCase(); + if (s.isEmpty) return null; + double factor = kTimeDiv[u.timeUnit]!; + String numPart = s; + // 依次识别时间后缀并确定换算系数;注意先匹配 `ms`/`min` 再匹配 `s`。 + if (s.endsWith('ms')) { + factor = 1; + numPart = s.substring(0, s.length - 2); + } else if (s.endsWith('min')) { + factor = 60000; + numPart = s.substring(0, s.length - 3); + } else if (s.endsWith('s')) { + factor = 1000; + numPart = s.substring(0, s.length - 1); + } + final double? v = double.tryParse(numPart.trim()); + if (v == null) return null; + return v * factor; +} + +/// 解析用户输入的相位文本,返回角度;无法解析时返回 null。 +/// +/// 支持 `%`(按 `v * 3.6` 换算为角度)与 `°` 后缀,无后缀时按角度解析。 +double? parsePhase(String text) { + final String s = text.trim(); + if (s.isEmpty) return null; + if (s.endsWith('%')) { + final double? v = double.tryParse(s.substring(0, s.length - 1).trim()); + if (v == null) return null; + return v * 3.6; + } + final String num = s.endsWith('°') ? s.substring(0, s.length - 1).trim() : s; + return double.tryParse(num); +} + +/// 将 [v] 限制在闭区间 `[lo, hi]` 内。 +double clamp(double v, double lo, double hi) => v < lo ? lo : (v > hi ? hi : v); + +/// 将 [value] 吸附到 [step] 的整数倍。 +/// +/// 当 [step] <= 0 时表示禁用吸附,直接返回原值。 +double snapTo(double value, double step) { + if (step <= 0) return value; + return (value / step).roundToDouble() * step; +} + +/// 将角度归一化到 `[0, 360)` 区间。 +double normalizeAngle(double deg) { + double a = deg % 360; + if (a < 0) a += 360; + return a; +} diff --git a/lib/persistence/storage.dart b/lib/persistence/storage.dart new file mode 100644 index 0000000..37ae2ef --- /dev/null +++ b/lib/persistence/storage.dart @@ -0,0 +1,235 @@ +/// 持久化层:负责项目文件的读写、自动保存与崩溃恢复。 +/// +/// 存储布局(位于用户 AppData/LocalAppData 下的 `SequenceDiagramStudio`): +/// - `autosave/current.seq.json`:最近一次项目快照; +/// - `autosave/session.json`:会话元数据(来源路径、是否干净、更新时间); +/// - `<项目路径>.bak`:保存前自动生成的备份。 +/// +/// 与上层关系:AppController 通过单例 [Storage.instance] 调用自动保存与保存; +/// 本层只依赖模型层,不感知 UI。 +library; + +import 'dart:convert'; +import 'dart:io'; + +import '../model/models.dart'; + +/// 崩溃恢复信息:描述一次可恢复的自动保存会话。 +class RecoveryInfo { + /// 构造恢复信息。 + /// + /// 参数 [content]:自动保存的项目 JSON 文本;[updatedAt]:快照时间; + /// [projectPath]:原始文件路径(可空);[bakPath]/[bakContent]:备份文件 + /// 路径与其内容(可空,仅在备份存在且可解析时提供)。 + RecoveryInfo({ + required this.content, + required this.updatedAt, + this.projectPath, + this.bakPath, + this.bakContent, + }); + + /// 自动保存的项目 JSON 文本。 + final String content; + + /// 自动保存时间。 + final DateTime updatedAt; + + /// 原项目文件路径;null 表示该项目从未保存过。 + final String? projectPath; + + /// 备份文件路径。 + final String? bakPath; + + /// 备份文件内容(已通过解析校验)。 + final String? bakContent; +} + +/// 持久化单例:封装应用目录、自动保存文件与项目读写逻辑。 +class Storage { + /// 私有构造,强制通过 [instance] 访问。 + Storage._(); + + /// 全局唯一实例。 + static final Storage instance = Storage._(); + + /// 应用数据根目录。 + late final Directory appDir; + + /// 自动保存目录。 + late final Directory autosaveDir; + + /// 当前项目快照文件(`current.seq.json`)。 + late final File currentFile; + + /// 会话元数据文件(`session.json`)。 + late final File sessionFile; + + /// 是否已完成初始化,避免重复创建目录。 + bool _inited = false; + + /// 初始化存储目录与文件引用(幂等)。 + /// + /// 目录优先级:`APPDATA` > `LOCALAPPDATA` > 系统临时目录;随后创建 + /// `autosave` 子目录。副作用:设置 [appDir]/[autosaveDir]/[currentFile]/ + /// [sessionFile] 并置 [_inited]。 + Future init() async { + if (_inited) return; + final String base = Platform.environment['APPDATA'] ?? + Platform.environment['LOCALAPPDATA'] ?? + Directory.systemTemp.path; + appDir = Directory('$base${Platform.pathSeparator}SequenceDiagramStudio'); + autosaveDir = Directory('${appDir.path}${Platform.pathSeparator}autosave'); + currentFile = File('${autosaveDir.path}${Platform.pathSeparator}current.seq.json'); + sessionFile = File('${autosaveDir.path}${Platform.pathSeparator}session.json'); + if (!await autosaveDir.exists()) { + await autosaveDir.create(recursive: true); + } + _inited = true; + } + + /// 写入自动保存快照与会话元数据。 + /// + /// 参数 [project]:项目;[projectPath]:来源文件路径;[clean]:是否已正常 + /// 保存(true 表示下次启动无需恢复)。 + /// 副作用:覆盖写入 [currentFile] 与 [sessionFile],均 flush 到磁盘。 + Future writeAutosave( + Project project, { + String? projectPath, + bool clean = false, + }) async { + await init(); + // 先写项目快照,再写元数据,尽量保证二者一致。 + await currentFile.writeAsString(project.encode(), flush: true); + final Map meta = { + 'projectPath': projectPath, + 'clean': clean, + 'updatedAt': DateTime.now().toIso8601String(), + }; + await sessionFile.writeAsString(jsonEncode(meta), flush: true); + } + + /// 将会话标记为“干净”(已正常保存/退出),保留原有元数据。 + /// + /// 参数 [projectPath]:可选,更新记录的文件路径。 + /// 若元数据文件缺失或损坏则使用空对象重建。 + Future markClean({String? projectPath}) async { + await init(); + // 尝试读取现有元数据,失败时回退为空对象。 + Map meta = {}; + if (await sessionFile.exists()) { + try { + meta = jsonDecode(await sessionFile.readAsString()) as Map; + } catch (_) { + meta = {}; + } + } + meta['projectPath'] = projectPath ?? meta['projectPath']; + meta['clean'] = true; + meta['updatedAt'] = DateTime.now().toIso8601String(); + await sessionFile.writeAsString(jsonEncode(meta), flush: true); + } + + /// 检查是否存在需要恢复的未保存会话。 + /// + /// 返回:可恢复时返回 [RecoveryInfo];以下任一情况返回 null: + /// 快照/元数据文件不存在、元数据标记为 clean、元数据或快照无法解析。 + /// 若存在对应 `.bak` 备份且可解析,会一并读入 [RecoveryInfo.bakContent]。 + Future checkRecovery() async { + await init(); + // 前置条件:快照与元数据文件都必须存在。 + if (!await currentFile.exists() || !await sessionFile.exists()) return null; + Map meta; + try { + meta = jsonDecode(await sessionFile.readAsString()) as Map; + } catch (_) { + return null; + } + // 已标记干净:无需恢复。 + if (meta['clean'] == true) return null; + // 校验快照内容可解析,避免恢复出损坏数据。 + String content; + try { + content = await currentFile.readAsString(); + Project.decode(content); + } catch (_) { + return null; + } + // 若记录了来源路径,尝试读取并校验对应的 .bak 备份。 + final String? path = meta['projectPath'] as String?; + String? bakContent; + if (path != null) { + final File bak = File('$path.bak'); + if (await bak.exists()) { + try { + bakContent = await bak.readAsString(); + Project.decode(bakContent); + } catch (_) { + bakContent = null; + } + } + } + // 解析更新时间;无法解析时回退为当前时间。 + DateTime updated = DateTime.now(); + final String? ts = meta['updatedAt'] as String?; + if (ts != null) { + updated = DateTime.tryParse(ts) ?? updated; + } + return RecoveryInfo( + content: content, + updatedAt: updated, + projectPath: path, + bakPath: path != null ? '$path.bak' : null, + bakContent: bakContent, + ); + } + + /// 清除恢复数据:删除快照文件并把会话标记为干净。 + Future clearRecovery() async { + await init(); + if (await currentFile.exists()) await currentFile.delete(); + await markClean(); + } + + /// 返回给定项目路径对应的备份文件句柄(`.bak`)。 + static File bakFor(String path) => File('$path.bak'); + + /// 若 [path] 处已存在文件,则复制一份为 `.bak`。 + /// + /// 复制失败时静默忽略(备份失败不应阻断保存流程)。 + Future backupExisting(String path) async { + final File target = File(path); + if (await target.exists()) { + try { + await target.copy('$path.bak'); + } catch (_) {} + } + } + + /// 将项目保存到 [path]。 + /// + /// 流程:初始化 -> 备份已有文件 -> 确保父目录存在 -> 写入项目 JSON -> + /// 同步写自动保存(标记为干净)。返回保存路径。 + Future saveProject(String path, Project project) async { + await init(); + // 1) 覆盖前先备份,防止写坏原文件。 + await backupExisting(path); + final File target = File(path); + final Directory parent = target.parent; + // 2) 父目录不存在时递归创建。 + if (!await parent.exists()) { + await parent.create(recursive: true); + } + // 3) 写入项目并 flush;随后把自动保存标记为干净。 + await target.writeAsString(project.encode(), flush: true); + await writeAutosave(project, projectPath: path, clean: true); + return path; + } + + /// 读取文本文件;文件不存在时返回 null。 + Future readFile(String path) async { + final File f = File(path); + if (!await f.exists()) return null; + return f.readAsString(); + } +} diff --git a/lib/render/bar_painter.dart b/lib/render/bar_painter.dart new file mode 100644 index 0000000..29c50a2 --- /dev/null +++ b/lib/render/bar_painter.dart @@ -0,0 +1,549 @@ +/// 条形(时间轴)视图绘制器。 +/// +/// 职责:把 [Project] 中的动作按“双轴”条形图渲染到 Flutter 画布上—— +/// 横轴同时表达相位角度与等价的绝对时间,纵轴按工位顺序排列动作行。 +/// +/// 架构位置: +/// - 全部几何计算委托给 [BarLayout](`lib/layout/layout.dart`), +/// 本绘制器只负责取几何结果并落笔,不自行推导坐标。 +/// - 颜色一律取自 [Tokens],因此与圆形视图及 SVG 导出保持同一视觉体系。 +/// - 关键路径信息([criticalActions]、[criticalDeps])由上层分析后传入, +/// 本类不参与计算,仅负责高亮呈现。 +/// +/// 绘制顺序(见 [paint]): +/// 相位带 → 时间/相位标尺 → 循环边界 → 动作行 → 依赖连线。 +library; + +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart' hide Action; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../model/units.dart'; +import '../theme/tokens.dart'; + +/// 条形时间轴视图的 [CustomPainter] 实现。 +/// +/// 坐标约定:横轴 `x` 表示 0°–360° 相位(并线性映射到 0–cycle 时间), +/// 纵轴 `y` 表示动作行。角度到像素的换算由 [BarLayout.xFor] 完成。 +class BarPainter extends CustomPainter { + /// 创建条形视图绘制器。 + /// + /// 参数: + /// - [project]:待绘制的工程数据(动作、工位、依赖、视图开关)。 + /// - [tokens]:当前主题令牌,决定所有颜色。 + /// - [criticalActions]:关键路径上的动作 id 集合,用于描边高亮。 + /// - [criticalDeps]:关键路径上的依赖集合,键格式 `fromId->toId`。 + /// - [selectedId]:当前选中动作 id,可为空。 + /// + /// 无副作用;实例不缓存布局,每次 [paint] 都重新计算。 + BarPainter({ + required this.project, + required this.tokens, + required this.criticalActions, + required this.criticalDeps, + required this.selectedIds, + this.guideAngle, + }); + + /// 待绘制的工程数据源。 + final Project project; + /// 当前主题令牌。 + final Tokens tokens; + /// 关键路径上的动作 id 集合。 + final Set criticalActions; + /// 关键路径上的依赖边集合,元素格式为 `fromId->toId`。 + final Set criticalDeps; + /// 当前选中的动作 id 集合(支持多选)。 + final Set selectedIds; + + /// 拖拽相位分区边界时的参考角(度);非空时绘制一条竖直虚线参考。 + final double? guideAngle; + + /// 标尺横线所在的 y 坐标(画布坐标)。 + static const double axisTop = 138; + /// 相位色带的顶部 y 坐标。 + static const double phaseBandTop = 92; + + /// 绘制整张条形视图。 + /// + /// 参数 [canvas]:目标画布;[size]:可用尺寸(用于构建 [BarLayout])。 + /// 副作用:向 [canvas] 写入若干图元,不修改任何模型状态。 + /// 图层顺序遵循“先背景后前景”:相位带、标尺、边界、动作行、依赖。 + @override + void paint(Canvas canvas, Size size) { + final BarLayout layout = BarLayout(project, size); + final UnitSettings u = project.units; + final double cycle = project.cycle.durationMs; + + if (project.viewState.showPhaseBands) _phaseBands(canvas, layout); + if (project.viewState.showRuler) _ruler(canvas, layout, u, cycle); + _boundaries(canvas, layout); + _rows(canvas, layout, u, cycle); + if (project.viewState.showDeps) _deps(canvas, layout, u); + // 分区拖拽参考线绘制在最上层,保证清晰可见。 + if (guideAngle != null) _guide(canvas, layout, u); + } + + /// 绘制相位分区拖拽时的竖直虚线参考线,并在顶部标注当前角度。 + void _guide(Canvas canvas, BarLayout layout, UnitSettings u) { + final double deg = guideAngle!; + final double x = layout.xFor(deg.clamp(0, 360)); + final double bottom = layout.yFor(layout.ordered.length) - 4; + final Paint p = Paint() + ..color = tokens.accent + ..strokeWidth = 1.4; + // 虚线:从相位带一直画到图表底部。 + const double dash = 6; + const double gap = 6; + double y = phaseBandTop - 8; + while (y < bottom) { + canvas.drawLine(Offset(x, y), Offset(x, math.min(y + dash, bottom)), p); + y += dash + gap; + } + _text(canvas, '${deg.toStringAsFixed(1)}°', Offset(x, phaseBandTop - 18), + color: tokens.accent, size: 11, align: TextAlign.center, weight: FontWeight.w700); + } + + /// 过滤出有效(跨度 > 0)的相位分区。 + /// + /// 相位分区来自 [Project.phaseZones],可在工艺参数面板中编辑; + /// 这里只做基本合法性过滤,保证异常数据不会画出负宽度色带。 + List _phaseZones() { + return project.phaseZones.where((PhaseZone z) => z.endAngle > z.startAngle).toList(); + } + + /// 绘制相位色带。 + /// + /// 算法:把每个相位分区映射到横轴像素,绘制一个圆角矩形,填充强调色的 + /// 低透明度版本并描边;宽度足够(> 64px)时居中标注分区名称。 + /// 若分区跨越 360°(结束角 > 360),则在左侧补画从 0° 起的续段, + /// 对应“跨循环”语义。 + void _phaseBands(Canvas canvas, BarLayout layout) { + for (final PhaseZone z in _phaseZones()) { + final double x0 = layout.xFor(z.startAngle); + final double x1 = layout.xFor(z.endAngle); + final Rect r = Rect.fromLTWH(x0, phaseBandTop, math.max(x1 - x0, 2), 32); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(6)), + Paint()..color = tokens.accent.withValues(alpha: 0.08), + ); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(6)), + Paint() + ..style = PaintingStyle.stroke + ..color = tokens.line2, + ); + // 名称居中且按色带宽度截断,保证不越出色块。 + if (r.width > 26) { + _textClipped(canvas, z.name, Offset(r.center.dx, r.center.dy), r.width - 10, + color: tokens.sub, size: 11); + } + if (z.endAngle > 360) { + final double wx = layout.xFor(z.endAngle - 360) - layout.plotLeft; + canvas.drawRRect( + RRect.fromRectAndRadius(Rect.fromLTWH(layout.plotLeft, phaseBandTop, wx, 32), const Radius.circular(6)), + Paint()..color = tokens.accent.withValues(alpha: 0.08), + ); + } + } + } + + /// 绘制双轴标尺。 + /// + /// 每 15° 一个刻度,30° 为主刻度(更长);每 60° 标注文字: + /// 下排为相位(度,强调色),上排为等价的绝对时间(由 [tvalStr] 格式化)。 + /// 参数 [u] 提供单位设置,[cycle] 为一个完整循环的毫秒数。 + void _ruler(Canvas canvas, BarLayout layout, UnitSettings u, double cycle) { + canvas.drawLine(Offset(layout.plotLeft, axisTop), Offset(layout.plotRight, axisTop), + Paint()..color = tokens.line2..strokeWidth = 1); + for (int d = 0; d <= 360; d += 15) { + final double x = layout.xFor(d.toDouble()); + final bool major = d % 30 == 0; + canvas.drawLine( + Offset(x, axisTop), + Offset(x, axisTop + (major ? 28 : 14)), + Paint() + ..color = major ? tokens.line2 : tokens.line + ..strokeWidth = 1, + ); + if (d % 60 == 0) { + _text(canvas, pfmt(d.toDouble(), u, dec: 0), Offset(x, axisTop + 44), + color: tokens.accent, size: 10, align: TextAlign.center); + _text(canvas, tvalStr(d / 360 * cycle, u, dec: u.timeUnit == TimeUnit.ms ? 0 : 1), + Offset(x, axisTop + 22), color: tokens.dim, size: 10, align: TextAlign.center); + } + } + _text(canvas, '时间 / ${timeUnitLabel(u.timeUnit)}', Offset(layout.plotLeft - 14, axisTop + 22), + color: tokens.dim, size: 10, align: TextAlign.right); + _text(canvas, '相位 / ${phaseUnitLabel(u.phaseUnit)}', Offset(layout.plotLeft - 14, axisTop + 44), + color: tokens.accent, size: 10, align: TextAlign.right); + } + + /// 绘制循环起止边界线(0° 与 360°)。 + /// + /// 0° 使用 [Tokens.ok]、360° 使用 [Tokens.warn] 的虚线竖线表示, + /// 并在下方标注“循环开始 / 循环结束”。虚线由 [_dashedLine] 手工分段绘制。 + void _boundaries(Canvas canvas, BarLayout layout) { + for (final double d in [0, 360]) { + final double x = layout.xFor(d); + final Color col = d == 0 ? tokens.ok : tokens.warn; + final Paint p = Paint() + ..color = col.withValues(alpha: 0.7) + ..strokeWidth = 1.4; + _dashedLine(canvas, Offset(x, axisTop + 28), Offset(x, layout.yFor(layout.ordered.length) - 4), p); + _text( + canvas, + d == 0 ? '循环开始 0°' : '循环结束 360°', + Offset(d == 0 ? x + 8 : x - 8, axisTop + 62), + color: col, + size: 10, + align: d == 0 ? TextAlign.left : TextAlign.right, + ); + } + } + + /// 在两点之间绘制固定 dash/gap 的虚线。 + /// + /// 参数 [a]/[b]:线段端点;[p]:画笔(颜色与线宽由调用方决定)。 + /// 通过沿单位方向向量步进生成短线段,不依赖 dashPathEffect。 + void _dashedLine(Canvas canvas, Offset a, Offset b, Paint p) { + const double dash = 6; + const double gap = 6; + final double total = (b - a).distance; + final Offset dir = (b - a) / total; + double t = 0; + while (t < total) { + final double end = math.min(t + dash, total); + canvas.drawLine(a + dir * t, a + dir * end, p); + t = end + gap; + } + } + + /// 绘制所有动作行。 + /// + /// 每行包含: + /// - 隔行背景(偶数行填充 [Tokens.panel2] 半透明色,便于横向阅读); + /// - 左侧序号色块,以及 `序号. id 名称`、`工位 · 驱动` 文本; + /// - 行底分隔线; + /// - 主条块(带阴影、选中描边、关键路径描边); + /// - 跨循环延续段(当 [Action.wrap] 且开启自动拆分时); + /// - 条块内或条块外的名称与时长标注。 + /// + /// 参数 [layout] 提供行列几何,[u]/[cycle] 用于时长文本换算。 + void _rows(Canvas canvas, BarLayout layout, UnitSettings u, double cycle) { + final List ordered = layout.ordered; + for (int i = 0; i < ordered.length; i++) { + final Action a = ordered[i]; + final double y = layout.yFor(i); + // 隔行背景色带,弱化行边界。 + if (i.isEven) { + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(20, y - 8, layout.plotRight - 20, BarLayout.rowVisual), + const Radius.circular(10), + ), + Paint()..color = tokens.panel2.withValues(alpha: 0.5), + ); + } + // 左侧序号徽标:动作自身颜色作底,叠加白色序号。 + final Station? st = project.stationById(a.stationId); + final Color c = Color(a.color); + canvas.drawRRect( + RRect.fromRectAndRadius(Rect.fromLTWH(32, y + 8, 18, 18), const Radius.circular(5)), + Paint()..color = c, + ); + _text(canvas, '${i + 1}', Offset(41, y + 17), + color: tokens.chip, size: 10, align: TextAlign.center, weight: FontWeight.w700); + // 动作标识与工位/驱动信息(两行文本)。 + // 标题列文字按列宽截断,避免越界压到图表。 + final double labelMax = BarLayout.leftGutter - 68; + _textMax(canvas, '${i + 1}. ${a.id} ${a.name}', Offset(60, y + 6), labelMax, + color: tokens.text, size: 12, weight: FontWeight.w600); + _textMax(canvas, '${st?.name ?? a.stationId} · ${a.driver}', Offset(60, y + 21), labelMax, + color: tokens.dim, size: 10); + + // 行底分隔线,颜色较淡。 + canvas.drawLine( + Offset(layout.plotLeft, y + BarLayout.rowVisual - 4), + Offset(layout.plotRight, y + BarLayout.rowVisual - 4), + Paint() + ..color = tokens.line.withValues(alpha: 0.5) + ..strokeWidth = 1, + ); + + // 动作条块:先投影,再填充,最后描边。 + final Rect r = layout.rectFor(a); + final bool sel = selectedIds.contains(a.id); + final bool crit = criticalActions.contains(a.id); + canvas.drawRRect( + RRect.fromRectAndRadius(r.shift(const Offset(1.5, 2)), const Radius.circular(8)), + Paint()..color = tokens.shadow.withValues(alpha: tokens.shadowOp), + ); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(8)), + Paint()..color = c.withValues(alpha: 0.92), + ); + // 选中描边:选中时更亮,未选中时仅保留很淡的轮廓。 + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(8)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = tokens.selOutline.withValues(alpha: sel ? 0.9 : 0.25), + ); + // 关键路径条块额外叠加一圈加粗高亮描边。 + if (crit) { + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(8)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = tokens.crit, + ); + } + + // 跨循环延续:把 360° 之后的部分回绕到左侧 0° 起绘制, + // 使用 [Tokens.tailOp] 透明度淡化以区别于主体。 + if (a.wrap && u.autoSplitWrap) { + final double wx = layout.xFor(a.endAngle - 360) - layout.plotLeft; + final Rect tail = Rect.fromLTWH(layout.plotLeft, r.top, math.max(wx, 2), r.height); + canvas.drawRRect( + RRect.fromRectAndRadius(tail, const Radius.circular(8)), + Paint()..color = c.withValues(alpha: tokens.tailOp), + ); + _text(canvas, '跨循环延续 ${(a.endAngle - 360).toStringAsFixed(0)}°', + Offset(layout.plotLeft + wx + 18, r.center.dy), color: tokens.warn, size: 10); + } + + // 文字放置策略:条块足够宽时内置名称与时长;否则视右侧剩余空间 + // 决定放到条块左侧还是右侧,避免文字越出绘图区。 + final double durMs = a.durationAngle / 360 * cycle; + if (r.width > 150) { + _text(canvas, a.name, Offset(r.left + 10, r.center.dy - 5), + color: tokens.arcText, size: 11, weight: FontWeight.w700); + _text(canvas, tfmt(durMs, u), Offset(r.left + 10, r.center.dy + 7), + color: tokens.arcText.withValues(alpha: 0.8), size: 10); + } else if (r.right + 170 > layout.plotRight) { + _text(canvas, '${a.name} ${tfmt(durMs, u)}', Offset(r.left - 10, r.center.dy), + color: c, size: 11, weight: FontWeight.w600, align: TextAlign.right); + } else { + _text(canvas, '${a.name} ${tfmt(durMs, u)}', Offset(r.right + 10, r.center.dy), + color: c, size: 11, weight: FontWeight.w600); + } + _text(canvas, 'Δ${a.durationAngle.toStringAsFixed(0)}°', Offset(layout.plotRight - 4, r.center.dy), + color: tokens.dim, size: 10, align: TextAlign.right); + } + } + + /// 绘制动作依赖连线(正交折线)。 + /// + /// 算法要点: + /// - 建立“动作 id → 行号”索引,用于判断两行相对位置。 + /// - FS 依赖从源条块右端出发;SS 依赖从源条块左端出发。 + /// - 相邻行(行距 ≤ 1)走短折线;跨多行时在行区间外侧选一条“泳道” + /// 作为竖直通道,泳道位置按区间内条块的最右/最左边界外扩, + /// 并叠加 `(k % 3) * 16` 的错位,避免多条线完全重叠。 + /// - 关键路径依赖先画一层加粗低透明度的“光晕”,再画主线。 + /// - 末端绘制箭头与类型标签(FS 顺序 / SS +偏移角)。 + /// + /// 参数 [layout] 提供条块矩形;[u] 当前未直接使用,保留以对齐调用接口。 + void _deps(Canvas canvas, BarLayout layout, UnitSettings u) { + final List ordered = layout.ordered; + final Map index = {}; + for (int i = 0; i < ordered.length; i++) { + index[ordered[i].id] = i; + } + int k = 0; + for (final Action to in ordered) { + for (final Dependency d in to.deps) { + final Action? from = project.actionById(d.fromId); + if (from == null) continue; + final int ia = index[from.id] ?? 0; + final int ib = index[to.id] ?? 0; + final Color col = d.type == DepType.fs ? tokens.fs : tokens.ss; + final bool crit = criticalDeps.contains('${d.fromId}->${d.toId}'); + final Rect ra = layout.rectFor(from); + final Rect rb = layout.rectFor(to); + final double sy = ra.center.dy; + final double ty = rb.center.dy; + final double sx = d.type == DepType.fs ? ra.right : ra.left; + final double ex = d.type == DepType.fs ? sx - 9 : sx + 9; + final double tx = rb.left + 14; + final double dir = ty > sy ? 1 : -1; + final double gapY = ty - dir * 23; + final double tipY = ty - dir * 15; + + final Path p = Path(); + double chipX; + final double chipY = gapY; + // 相邻行:短折线,直接从源端折向目标条块上方。 + if ((ib - ia).abs() <= 1) { + p.moveTo(ex, sy + dir * 13); + p.lineTo(ex, gapY); + p.lineTo(tx, gapY); + p.lineTo(tx, tipY - dir * 12); + chipX = (ex + tx) / 2; + } else { + // 跨多行:扫描区间内所有条块边界,据此在外侧选一条竖直泳道。 + double maxRight = 0; + double minLeft = double.infinity; + for (int r = math.min(ia, ib) + 1; r < math.max(ia, ib); r++) { + final Rect rr = layout.rectFor(ordered[r]); + maxRight = math.max(maxRight, rr.right); + minLeft = math.min(minLeft, rr.left); + } + double lane = math.max(math.max(sx, tx), maxRight) + 28 + (k % 3) * 16; + if (lane > layout.plotRight - 16) { + lane = math.min(math.min(sx, tx), minLeft) - 28 - (k % 3) * 16; + } + final double srcGapY = sy + dir * 27; + p.moveTo(ex, sy + dir * 13); + p.lineTo(ex, srcGapY); + p.lineTo(lane, srcGapY); + p.lineTo(lane, gapY); + p.lineTo(tx, gapY); + p.lineTo(tx, tipY - dir * 12); + chipX = (lane + tx) / 2; + } + // 关键路径依赖:先铺一层加粗低透明度光晕,再画主线。 + if (crit) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 9 + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.18), + ); + } + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = crit ? 2.2 : 1.7 + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.95), + ); + _arrow(canvas, Offset(tx, tipY), Offset(0, dir), col); + final String label = d.type == DepType.fs ? 'FS 顺序' : 'SS +${d.offsetAngle.toStringAsFixed(0)}°'; + _chip(canvas, Offset(chipX, chipY), label, col, crit); + k++; + } + } + } + + /// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。 + /// + /// 参数 [col] 为填充色;[dir] 只需提供方向(本函数不归一化,直接按分量使用)。 + void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) { + const double s = 13; + final Offset b = tip - dir * s; + final Offset n = Offset(-dir.dy, dir.dx) * s * 0.5; + final Path p = Path() + ..moveTo(tip.dx, tip.dy) + ..lineTo(b.dx + n.dx, b.dy + n.dy) + ..lineTo(b.dx - n.dx, b.dy - n.dy) + ..close(); + canvas.drawPath(p, Paint()..color = col); + } + + /// 绘制依赖类型标签胶囊。 + /// + /// 参数 [center]:胶囊中心;[label]:文字;[col]:边框与文字色; + /// [crit]:为真时在左侧追加星形关键标记,并把胶囊加宽。 + void _chip(Canvas canvas, Offset center, String label, Color col, bool crit) { + final TextPainter tp = _tp(label, 10.5, col, FontWeight.w600); + final double w = tp.width + 18 + (crit ? 18 : 0); + const double h = 18; + final Rect r = Rect.fromCenter(center: center, width: w, height: h); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(6)), + Paint()..color = tokens.chip, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(6)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = col, + ); + if (crit) { + canvas.drawCircle(Offset(r.left + 9, center.dy), 7, Paint()..color = tokens.crit); + _text(canvas, '★', Offset(r.left + 9, center.dy), color: tokens.onAccent, size: 10, align: TextAlign.center); + tp.paint(canvas, Offset(r.left + 20, center.dy - tp.height / 2)); + } else { + tp.paint(canvas, Offset(r.left + 9, center.dy - tp.height / 2)); + } + } + + /// 构造并布局一个 [TextPainter]。 + /// + /// 统一使用微软雅黑字体;参数 [s] 文本、[size] 字号、[color] 颜色、 + /// [weight] 字重、[align] 对齐方式。返回已完成 layout 的实例。 + TextPainter _tp(String s, double size, Color color, FontWeight weight, {TextAlign align = TextAlign.left}) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle(color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + textAlign: align, + )..layout(); + return tp; + } + + /// 便捷文本绘制。 + /// + /// 在 [at] 处按 [align] 对齐绘制字符串 [s](默认左对齐、垂直居中)。 + /// [color] 缺省时使用 [Tokens.text]。 + /// 在 [at] 处绘制左对齐的单行文字,并按 [maxWidth] 截断(超出显示省略号)。 + void _textMax(Canvas canvas, String s, Offset at, double maxWidth, + {Color? color, double size = 12, FontWeight weight = FontWeight.normal}) { + if (maxWidth <= 4) return; + final TextPainter tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle(color: color ?? tokens.text, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: maxWidth); + tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2)); + } + + /// 在 [center] 处绘制居中的单行文字,并按 [maxWidth] 截断(超出显示省略号)。 + void _textClipped(Canvas canvas, String s, Offset center, double maxWidth, + {Color? color, double size = 11, FontWeight weight = FontWeight.w600}) { + if (maxWidth <= 4) return; + final TextPainter tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle(color: color ?? tokens.text, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: maxWidth); + tp.paint(canvas, Offset(center.dx - tp.width / 2, center.dy - tp.height / 2)); + } + + void _text(Canvas canvas, String s, Offset at, + {Color? color, double size = 12, FontWeight weight = FontWeight.normal, TextAlign align = TextAlign.left}) { + final TextPainter tp = _tp(s, size, color ?? tokens.text, weight, align: align); + double dx = at.dx; + if (align == TextAlign.center) dx -= tp.width / 2; + if (align == TextAlign.right) dx -= tp.width; + tp.paint(canvas, Offset(dx, at.dy - tp.height / 2)); + } + + /// 始终返回 `true`。 + /// + /// 绘制完全依赖每次重建的布局与外部状态,且本绘制器不做缓存, + /// 因此保守地要求每次重绘。 + @override + bool shouldRepaint(covariant BarPainter old) => true; +} diff --git a/lib/render/circular_painter.dart b/lib/render/circular_painter.dart new file mode 100644 index 0000000..dceb831 --- /dev/null +++ b/lib/render/circular_painter.dart @@ -0,0 +1,591 @@ +/// 圆形(极坐标)视图绘制器。 +/// +/// 职责:把 [Project] 中的动作绘制为同心圆环——角度表示相位 +/// (0° 位于 12 点钟方向,顺时针递增),半径表示动作所属层级(layer)。 +/// +/// 架构位置: +/// - 几何换算(圆心、各层半径、刻度半径)来自 [CircularLayout]; +/// 极坐标换算复用 `layout.dart` 中的 [polar] 与 [arcPath]。 +/// - 颜色取自 [Tokens],与条形视图及 SVG 导出保持同一视觉体系。 +/// - 跨循环动作通过 [splitArcs] 拆成两段弧绘制,保证角度连续、视觉闭合。 +library; + +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart' hide Action; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../theme/tokens.dart'; + +/// 圆形视图的 [CustomPainter] 实现。 +/// +/// 所有角度以“12 点钟为 0°、顺时针为正”为约定,由 [polar] 完成换算。 +class CircularPainter extends CustomPainter { + /// 创建圆形视图绘制器。 + /// + /// 参数: + /// - [project]:待绘制的工程数据(动作、依赖、视图开关)。 + /// - [tokens]:当前主题令牌,决定所有颜色。 + /// - [criticalActions]:关键路径上的动作 id 集合。 + /// - [criticalDeps]:关键路径上的依赖集合,键格式 `fromId->toId`。 + /// - [selectedId]:当前选中动作 id,可为空。 + /// + /// 无副作用;实例不缓存布局,每次 [paint] 都重新计算。 + CircularPainter({ + required this.project, + required this.tokens, + required this.criticalActions, + required this.criticalDeps, + required this.selectedIds, + }); + + /// 待绘制的工程数据源。 + final Project project; + /// 当前主题令牌。 + final Tokens tokens; + /// 关键路径上的动作 id 集合。 + final Set criticalActions; + /// 关键路径上的依赖边集合,元素格式为 `fromId->toId`。 + final Set criticalDeps; + /// 当前选中的动作 id 集合(支持多选)。 + final Set selectedIds; + + /// 绘制整个圆形视图。 + /// + /// 参数 [canvas]/[size] 遵循 Flutter 绘制约定。 + /// 图层顺序:表盘底 → 圆环背景 → 象限线 → 层号 → 依赖 → 动作弧 + /// → 起点标记 / 方向箭头 / 刻度。 + @override + void paint(Canvas canvas, Size size) { + final CircularLayout layout = CircularLayout(project, size); + final UnitSettings u = project.units; + final Offset c = layout.center; + final double th = layout.th; + final double tickR = layout.tickR; + + // 表盘底板:半径略大于最外圈刻度,形成一圈底色与边框。 + canvas.drawCircle(c, tickR + 10, Paint()..color = tokens.dial); + canvas.drawCircle( + c, + tickR + 10, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 + ..color = tokens.line2, + ); + + // 圆环背景:每层用一条粗描边构成环带,奇偶层交替着色, + // 并在环带内外沿各画一条细描边作为边界。 + final int layers = project.maxLayer + 1; + if (project.viewState.showRingBg) { + for (int i = 0; i < layers; i++) { + final double r = layout.radiusFor(i); + canvas.drawCircle( + c, + r, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = th + ..color = i.isEven ? tokens.ringA : tokens.ringB, + ); + canvas.drawCircle( + c, + r - th / 2, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = tokens.ringEdge, + ); + canvas.drawCircle( + c, + r + th / 2, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = tokens.ringEdge, + ); + } + } + canvas.drawCircle(c, math.max(CircularLayout.r0 - th / 2, 8), Paint()..color = tokens.dial); + + // 相位分区环:在最外动作环与刻度环之间画一圈分区色带并标注名称。 + if (project.viewState.showPhaseBands) _phaseRing(canvas, layout); + + // 象限辅助线(0°/90°/180°/270°)。 + _quadrants(canvas, c, layout); + + // 层号标签:为每层挑选一个空位角度,避免压住该层的动作弧。 + if (project.viewState.showLayerLabels) { + for (int i = 0; i < layers; i++) { + final double r = layout.radiusFor(i); + final double free = _freeAngle(i); + final Offset lp = polar(c, r, free); + _text(canvas, 'L${i + 1}', lp, color: tokens.ringLabel, size: 10, align: TextAlign.center, weight: FontWeight.w700); + } + } + + // 依赖连线先于动作弧绘制,使其位于弧之下、不被遮挡。 + if (project.viewState.showDeps) { + for (final Action to in project.actions) { + for (final Dependency d in to.deps) { + _dep(canvas, layout, d); + } + } + } + + // 逐个绘制动作弧。 + for (final Action a in project.actions) { + _action(canvas, layout, a, u); + } + + // 起点标记、顺时针方向提示与外围刻度。 + _startMarker(canvas, layout); + _cwArrow(canvas, layout); + if (project.viewState.showRuler) _ticks(canvas, layout); + } + + /// 绘制相位分区环:在最外动作环与刻度环之间画一圈分区色带,标注分区名称, + /// 并在每条边界处画一条径向虚线,便于与条形视图的分区对应。 + void _phaseRing(Canvas canvas, CircularLayout layout) { + final List zones = + project.phaseZones.where((PhaseZone z) => z.endAngle > z.startAngle).toList(); + if (zones.isEmpty) return; + final Offset c = layout.center; + // 加宽分区带(16px);tickR 已在外层动作环之外留出更大间距,避免挤在一起。 + final double rBand = layout.tickR - 16; + const double bandW = 16; + + // 底环,作为分区的“轨道”。 + canvas.drawCircle( + c, + rBand, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = bandW + ..color = tokens.track, + ); + + // 分区配色(循环取用强调色系)。 + const List pal = [ + Color(0xFF4CC9F0), + Color(0xFF7C5CFF), + Color(0xFF34D399), + Color(0xFFFFD166), + Color(0xFFF472B6), + ]; + + for (int i = 0; i < zones.length; i++) { + final PhaseZone z = zones[i]; + final Color col = pal[i % pal.length]; + // 分区色带(跨圈会拆成两段)。 + for (final List s in splitArcs(z.startAngle, z.endAngle)) { + canvas.drawPath( + arcPath(c, rBand, s[0], s[1]), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = bandW + ..color = col.withValues(alpha: 0.85), + ); + } + // 名称沿圆弧排列(切向),并按弧长截断,保证不超出色带。 + final double mid = ((z.startAngle + z.endAngle) / 2) % 360; + final double span = (z.endAngle - z.startAngle).clamp(0, 360); + final double arcLen = 2 * math.pi * rBand * (span / 360); + _arcLabel(canvas, c, rBand, mid, z.name, tokens.arcText, 11, math.max(arcLen - 10, 22)); + // 边界径向虚线。 + for (final double b in [z.startAngle, z.endAngle]) { + final Offset p1 = polar(c, rBand - bandW / 2 - 5, b); + final Offset p2 = polar(c, rBand + bandW / 2 + 5, b); + _dashed(canvas, p1, p2, col.withValues(alpha: 0.9)); + } + } + } + + /// 在两点之间画一条虚线(用于分区边界参考)。 + void _dashed(Canvas canvas, Offset a, Offset b, Color col) { + const double dash = 3; + const double gap = 3; + final double total = (b - a).distance; + if (total <= 0) return; + final Offset dir = (b - a) / total; + double t = 0; + final Paint paint = Paint() + ..color = col + ..strokeWidth = 1.4 + ..strokeCap = StrokeCap.round; + while (t < total) { + final double end = math.min(t + dash, total); + canvas.drawLine(a + dir * t, a + dir * end, paint); + t = end + gap; + } + } + + /// 沿圆弧切向绘制文字,并按 [maxWidth] 截断,保证不超出色带。 + /// + /// 文字位于半径 [r]、角度 [midDeg] 处,旋转到该点的切线方向; + /// 当文字位于左半圈(90°–270°)时翻转 180°,避免倒置。 + void _arcLabel(Canvas canvas, Offset c, double r, double midDeg, String text, Color col, double size, double maxWidth) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: text, + style: TextStyle(color: col, fontSize: size, fontWeight: FontWeight.w700, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: maxWidth); + final Offset pos = polar(c, r, midDeg); + final double rad = midDeg * math.pi / 180; + final bool flip = midDeg > 90 && midDeg < 270; + canvas.save(); + canvas.translate(pos.dx, pos.dy); + canvas.rotate(flip ? rad + math.pi : rad); + tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2)); + canvas.restore(); + } + + /// 为指定 [layer] 选一个尽量不被动作弧覆盖的角度,用于放置层号“L1/L2…”。 + /// + /// 从候选角列表(围绕正上方 270° 左右摆动)中挑选第一个与本层任何 + /// 动作弧都不重叠的角度;若全部冲突则回退到 270°。 + double _freeAngle(int layer) { + const List cands = [270, 278, 262, 286, 254, 294, 246, 302, 238, 310]; + final List inLayer = project.actions.where((Action a) => a.layer == layer).toList(); + for (final double cand in cands) { + bool ok = true; + for (final Action a in inLayer) { + if (_inArc(a, cand)) { + ok = false; + break; + } + } + if (ok) return cand; + } + return 270; + } + + /// 判断角度 [deg] 是否落在动作 [a] 的弧范围内。 + /// + /// 处理两类情况:普通动作(结束角 ≤ 360)用闭区间判定; + /// 跨循环动作(结束角 > 360)用“大于起点 或 小于回绕终点”的并集判定。 + /// 两侧各留 0.5° 容差以吸收浮点误差。 + bool _inArc(Action a, double deg) { + final double n = deg % 360; + if (a.endAngle <= 360) return n >= a.startAngle - 0.5 && n <= a.endAngle + 0.5; + return n >= a.startAngle - 0.5 || n <= (a.endAngle - 360) + 0.5; + } + + /// 绘制 0°/90°/180°/270° 四条象限辅助线(从内圈延伸到刻度环)。 + void _quadrants(Canvas canvas, Offset c, CircularLayout layout) { + for (final double d in [0, 90, 180, 270]) { + final Offset p1 = polar(c, 30, d); + final Offset p2 = polar(c, layout.tickR + 4, d); + canvas.drawLine( + p1, + p2, + Paint() + ..color = tokens.line2.withValues(alpha: 0.7) + ..strokeWidth = 1, + ); + } + } + + /// 绘制单个动作弧。 + /// + /// 算法: + /// - 通过 [splitArcs] 把可能跨循环的动作拆成一到两段,逐段绘制。 + /// - 每段先画加宽阴影弧,再画本体弧;跨循环的“尾巴”段(第二段) + /// 以 [Tokens.tailOp] 淡化,并额外叠一层高透明度描边以示区分。 + /// - 关键动作沿弧画 [Tokens.crit] 描边;选中动作在外侧画强调色细弧。 + /// - 在弧中点附近放置 `序号. id 名称` 与起止角度文本; + /// 短弧(时长 < 38°)使用更小字号并收紧行距。 + /// + /// 参数 [u] 为当前单位设置(保留以对齐调用接口,当前未直接使用)。 + void _action(Canvas canvas, CircularLayout layout, Action a, UnitSettings u) { + final Offset c = layout.center; + final double r = layout.radiusFor(a.layer); + final double th = layout.th; + final Color col = Color(a.color); + final bool sel = selectedIds.contains(a.id); + final bool crit = criticalActions.contains(a.id); + // 跨循环动作会被拆成 [a0,360] 与 [0,a1-360] 两段。 + final List> segs = splitArcs(a.startAngle, a.endAngle); + + for (int k = 0; k < segs.length; k++) { + // 第二段且为跨循环时视为“尾巴”,需淡化处理。 + final bool tail = a.wrap && k == 1; + final Path p = arcPath(c, r, segs[k][0], segs[k][1]); + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = th + 7 + ..strokeCap = a.wrap ? StrokeCap.butt : StrokeCap.round + ..color = tokens.shadow.withValues(alpha: tokens.shadowOp), + ); + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = th + ..strokeCap = a.wrap ? StrokeCap.butt : StrokeCap.round + ..color = col.withValues(alpha: tail ? tokens.tailOp : 1), + ); + if (tail) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = th + ..strokeCap = StrokeCap.butt + ..color = col.withValues(alpha: 0.9), + ); + } + } + if (crit) { + for (final List s in segs) { + canvas.drawPath( + arcPath(c, r, s[0], s[1]), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = tokens.crit, + ); + } + } + if (sel) { + for (final List s in segs) { + canvas.drawPath( + arcPath(c, r + th / 2 + 8, s[0], s[1]), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6 + ..color = tokens.accent, + ); + } + } + + // 文字沿圆弧排列并按弧长截断,保证始终位于动作色带之内。 + final double mid = (a.startAngle + a.endAngle) / 2; + final int step = project.actions.indexOf(a) + 1; + final double span = a.wrap ? (360 - a.startAngle) : a.durationAngle; + final double arcLen = 2 * math.pi * r * (span.clamp(0, 360) / 360); + _arcLabel(canvas, c, r, mid, '$step. ${a.id} ${a.name}', tokens.arcText, 11, math.max(arcLen - 12, 20)); + } + + /// 绘制圆形视图中的依赖连线。 + /// + /// 路径由四段组成:从源弧末端沿半径到中间半径 [rC] → 沿圆弧走到目标弧 + /// 起点角度 → 再沿半径落到目标弧表面([rTip])→ 末端加箭头。 + /// - 相邻层取两层半径均值作为 [rC];层差大于 1 时改用最外圈 `rMax+24` 绕行。 + /// - [large]/[cw] 决定圆弧走大弧还是小弧、顺时针还是逆时针。 + /// - 关键依赖先画低透明度粗描边,再画主线,最后放置 `A→B 类型` 胶囊。 + void _dep(Canvas canvas, CircularLayout layout, Dependency d) { + final Action? A = project.actionById(d.fromId); + final Action? B = project.actionById(d.toId); + if (A == null || B == null) return; + final Offset c = layout.center; + final double rA = layout.radiusFor(A.layer); + final double rB = layout.radiusFor(B.layer); + final double aEnd = math.min(A.endAngle, 360); + final double aStart = B.startAngle; + // 层差大于 1 时从最外圈绕行,避免穿过中间层弧线。 + final bool skip = (A.layer - B.layer).abs() > 1; + final double rC = skip ? layout.rMax + 24 : (rA + rB) / 2; + final bool cw = aStart >= aEnd; + final int large = (aStart - aEnd).abs() > 180 ? 1 : 0; + final Offset p0 = polar(c, rA, aEnd); + final Offset p1 = polar(c, rC, aEnd); + final Offset p2 = polar(c, rC, aStart); + final double rTip = rC < rB ? rB - layout.th / 2 - 4 : rB + layout.th / 2 + 4; + final Offset p3 = polar(c, rTip, aStart); + final Color col = d.type == DepType.fs ? tokens.fs : tokens.ss; + final bool crit = criticalDeps.contains('${d.fromId}->${d.toId}'); + + final Path p = Path() + ..moveTo(p0.dx, p0.dy) + ..lineTo(p1.dx, p1.dy) + ..arcToPoint(p2, radius: Radius.circular(rC), largeArc: large == 1, clockwise: cw) + ..lineTo(p3.dx, p3.dy); + + if (crit) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 9 + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.2), + ); + } + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = crit ? 3 : (d.type == DepType.fs ? 2.4 : 2) + ..strokeCap = StrokeCap.round + ..color = col, + ); + _arrow(canvas, p3, p3 - p2, col); + + // 标签胶囊放置在连线中段:跨层时贴最外圈,短跨度时外移避免压线。 + final double theta = (aEnd + aStart) / 2; + final double span = (aStart - aEnd).abs(); + final double rChip = skip ? rC : (span < 30 ? rB + layout.th / 2 + 10 : rC); + final Offset mid = polar(c, rChip, theta); + String label = d.type == DepType.fs ? 'FS' : 'SS+${d.offsetAngle.toStringAsFixed(0)}°'; + if (d.type == DepType.ff) label = 'FF'; + if (d.type == DepType.sf) label = 'SF'; + _chip(canvas, mid, '${A.id}→${B.id} $label', col, crit); + } + + /// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。 + /// + /// 与条形视图不同,这里会先把 [dir] 归一化;长度过短时直接返回。 + void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) { + final double len = dir.distance; + if (len < 0.001) return; + final Offset u = dir / len; + const double s = 12; + final Offset b = tip - u * s; + final Offset n = Offset(-u.dy, u.dx) * s * 0.5; + final Path p = Path() + ..moveTo(tip.dx, tip.dy) + ..lineTo(b.dx + n.dx, b.dy + n.dy) + ..lineTo(b.dx - n.dx, b.dy - n.dy) + ..close(); + canvas.drawPath(p, Paint()..color = col); + } + + /// 绘制依赖标签胶囊。 + /// + /// 参数 [center]:胶囊中心;[label]:文字;[col]:边框与文字色; + /// [crit]:为真时在左侧追加星形关键标记并加宽胶囊。 + void _chip(Canvas canvas, Offset center, String label, Color col, bool crit) { + final TextPainter tp = _tp(label, 10, col, FontWeight.w600); + final double w = tp.width + 16 + (crit ? 18 : 0); + final Rect r = Rect.fromCenter(center: center, width: w, height: 17); + canvas.drawRRect(RRect.fromRectAndRadius(r, const Radius.circular(6)), Paint()..color = tokens.chip); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(6)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = col, + ); + double tx = r.left + 8; + if (crit) { + canvas.drawCircle(Offset(r.left + 8, center.dy), 6.5, Paint()..color = tokens.crit); + _text(canvas, '★', Offset(r.left + 8, center.dy), color: tokens.onAccent, size: 10, align: TextAlign.center); + tx = r.left + 18; + } + tp.paint(canvas, Offset(tx, center.dy - tp.height / 2)); + } + + /// 绘制 0° 起点标记:顶部朝下的三角与“0° · 12 点钟”文字。 + void _startMarker(Canvas canvas, CircularLayout layout) { + final Offset c = layout.center; + final double r = layout.tickR + 12; + final Offset tip = Offset(c.dx, c.dy - r - 22); + final Path p = Path() + ..moveTo(tip.dx, tip.dy) + ..lineTo(tip.dx - 9, tip.dy - 15) + ..lineTo(tip.dx + 9, tip.dy - 15) + ..close(); + canvas.drawPath(p, Paint()..color = tokens.accent); + _text(canvas, '0° · 12 点钟', Offset(c.dx, tip.dy - 30), + color: tokens.accent, size: 11, align: TextAlign.center, weight: FontWeight.w600); + } + + /// 绘制顺时针方向指示:一段外圈圆弧、箭头与“顺时针 CW”文字。 + void _cwArrow(Canvas canvas, CircularLayout layout) { + final Offset c = layout.center; + // 放在刻度环之外,避免“冲进”视图内部。 + final double r = layout.tickR + 16; + final Path p = arcPath(c, r, 20, 70); + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.4 + ..strokeCap = StrokeCap.round + ..color = tokens.accent2, + ); + final Offset t1 = polar(c, r, 74); + final Offset t2 = polar(c, r + 14, 68); + final Offset t3 = polar(c, r - 14, 66); + final Path a = Path() + ..moveTo(t1.dx, t1.dy) + ..lineTo(t2.dx, t2.dy) + ..lineTo(t3.dx, t3.dy) + ..close(); + canvas.drawPath(a, Paint()..color = tokens.accent2); + final Offset label = polar(c, r + 30, 45); + _text(canvas, '顺时针 CW', label, color: tokens.accent2, size: 11, align: TextAlign.center, weight: FontWeight.w600); + } + + /// 绘制外围角度刻度。 + /// + /// 每 5° 一个刻度,10° 为中刻度,30° 为主刻度并标注度数; + /// 90° 的整数倍使用强调色加粗,便于快速定位象限。 + void _ticks(Canvas canvas, CircularLayout layout) { + final Offset c = layout.center; + final double r = layout.tickR; + for (int d = 0; d < 360; d += 5) { + final bool major = d % 30 == 0; + final bool mid = d % 10 == 0; + final Offset p1 = polar(c, r, d.toDouble()); + final Offset p2 = polar(c, r + (major ? 20 : (mid ? 13 : 7)), d.toDouble()); + canvas.drawLine( + p1, + p2, + Paint() + ..strokeWidth = major ? 1.4 : 1 + ..color = major ? tokens.line2 : tokens.line, + ); + if (major) { + final Offset lp = polar(c, r + 38, d.toDouble()); + _text(canvas, '$d°', lp, + color: d % 90 == 0 ? tokens.accent : tokens.sub, + size: 10, + align: TextAlign.center, + weight: d % 90 == 0 ? FontWeight.w700 : FontWeight.normal); + } + } + } + + /// 构造并布局一个 [TextPainter]。 + /// + /// 统一使用微软雅黑字体;返回已完成 layout 的实例。 + TextPainter _tp(String s, double size, Color color, FontWeight weight) { + return TextPainter( + text: TextSpan( + text: s, + style: TextStyle(color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + )..layout(); + } + + /// 便捷文本绘制。 + /// + /// 在 [at] 处按 [align] 对齐绘制字符串 [s](默认左对齐、垂直居中)。 + /// [color] 缺省时使用 [Tokens.text]。 + void _text(Canvas canvas, String s, Offset at, + {Color? color, double size = 12, FontWeight weight = FontWeight.normal, TextAlign align = TextAlign.left}) { + final TextPainter tp = _tp(s, size, color ?? tokens.text, weight); + double dx = at.dx; + if (align == TextAlign.center) dx -= tp.width / 2; + if (align == TextAlign.right) dx -= tp.width; + tp.paint(canvas, Offset(dx, at.dy - tp.height / 2)); + } + + /// 始终返回 `true`。 + /// + /// 绘制完全依赖每次重建的布局与外部状态,且本绘制器不做缓存, + /// 因此保守地要求每次重绘。 + @override + bool shouldRepaint(covariant CircularPainter old) => true; +} diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart new file mode 100644 index 0000000..3b2d370 --- /dev/null +++ b/lib/state/app_controller.dart @@ -0,0 +1,836 @@ +/// 应用状态控制器:连接模型层、持久化层与 UI 的中枢。 +/// +/// 作为 [ChangeNotifier],它持有当前 [Project]、撤销/重做栈、脏标记、自动保存 +/// 定时器与关键路径缓存;所有修改项目的方法最终都会经由 [_mutate] 或显式 +/// [notifyListeners] 触发界面刷新。 +/// +/// 架构位置:UI 只读取本控制器暴露的状态并调用其方法,不直接修改模型; +/// 持久化通过 [Storage] 单例完成;关键路径由 [_recomputeCritical] 计算。 +library; + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart' hide Action; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../model/units.dart'; +import '../persistence/storage.dart'; + +/// 全局应用控制器(继承 [ChangeNotifier])。 +class AppController extends ChangeNotifier { + /// 构造控制器。 + /// + /// 参数 [project]:初始项目;为 null 时使用 [Project.demo] 并标记为已修改 + /// (因为演示数据尚未保存到文件)。 + AppController({Project? project}) + : _project = project ?? Project.demo(), + _dirty = project == null; + + /// 当前项目数据(唯一可变引用,替换时整体赋值)。 + Project _project; + + /// 当前主题亮度(默认浅色 / 白底)。 + Brightness _brightness = Brightness.light; + + /// 当前项目对应的文件路径;null 表示尚未保存。 + String? _filePath; + + /// 是否有未保存修改。 + bool _dirty; + + /// 画布视口尺寸(由 [CanvasView] 在布局阶段回填)。 + /// + /// 用于把「缩放锚点」定位到视口中心、以及 [fitView] 计算适配比例; + /// 属于纯测量值,变更时**不**触发 [notifyListeners],避免重建循环。 + Size _viewport = Size.zero; + + /// 当前画布视口尺寸(逻辑像素)。 + Size get viewport => _viewport; + + /// 由画布回填视口尺寸(不通知监听者)。 + void setViewport(Size s) { + _viewport = s; + } + + /// 撤销栈(保存历史项目快照,最多 200 条)。 + final List _undo = []; + + /// 重做栈。 + final List _redo = []; + + /// 周期自动保存定时器。 + Timer? _autosaveTimer; + + /// 状态栏文本。 + String _status = '就绪'; + + /// 最近一次保存时间。 + DateTime? _lastSavedAt; + + /// 关键路径上的动作 id 集合。 + Set _criticalActions = {}; + + /// 关键路径上的依赖边集合(形如 `from->to`)。 + Set _criticalDeps = {}; + + /// 当前项目。 + Project get project => _project; + + /// 当前主题亮度。 + Brightness get brightness => _brightness; + + /// 当前文件路径。 + String? get filePath => _filePath; + + /// 是否存在未保存修改。 + bool get dirty => _dirty; + + /// 是否可撤销。 + bool get canUndo => _undo.isNotEmpty; + + /// 是否可重做。 + bool get canRedo => _redo.isNotEmpty; + + /// 状态栏文本。 + String get status => _status; + + /// 最近保存时间。 + DateTime? get lastSavedAt => _lastSavedAt; + + /// 关键路径动作集合(只读)。 + Set get criticalActions => _criticalActions; + + /// 关键路径依赖集合(只读)。 + Set get criticalDeps => _criticalDeps; + + /// 当前选中动作 id 列表(支持 Ctrl 多选)。 + List get selectedIds => _project.viewState.selectedIds; + + /// 主选中动作 id(列表首项)。 + String? get selectedId => _project.viewState.selectedId; + + /// 判断动作 [id] 是否被选中。 + bool isSelected(String id) => _project.viewState.isSelected(id); + + /// 主选中动作对象;无选中时为 null。 + Action? get selected => _project.actionById(selectedId); + + /// 当前选中的动作对象列表。 + List get selectedActions => + _project.viewState.selectedIds.map(_project.actionById).whereType().toList(); + + /// 启动控制器:先计算关键路径,再启动每 5 秒一次的自动保存。 + void start() { + _recomputeCritical(); + _autosaveTimer = Timer.periodic(const Duration(seconds: 5), (_) => _autosave()); + } + + /// 释放资源:取消自动保存定时器并调用父类 dispose。 + @override + void dispose() { + _autosaveTimer?.cancel(); + super.dispose(); + } + + /// 自动保存当前项目(内部方法,异常静默忽略以避免打断编辑)。 + Future _autosave() async { + try { + await Storage.instance.writeAutosave( + _project, + projectPath: _filePath, + clean: !_dirty, + ); + } catch (_) {} + } + + /// 退出前将自动保存标记为“干净”,表示已正常关闭无需恢复。 + Future markCleanOnExit() async { + try { + await Storage.instance.writeAutosave( + _project, + projectPath: _filePath, + clean: true, + ); + } catch (_) {} + } + + /// 更新状态栏文本并刷新界面。 + void setStatus(String s) { + _status = s; + notifyListeners(); + } + + /// 以 [next] 替换当前项目并记录一次可撤销的历史。 + /// + /// 副作用:压入 [_undo](超出 200 条丢弃最旧)、清空 [_redo]、置脏标记、 + /// 可选更新 [status]、重算关键路径并通知监听者。 + void _mutate(Project next, {String? status}) { + _undo.add(_project); + if (_undo.length > 200) _undo.removeAt(0); + _redo.clear(); + _project = next; + _dirty = true; + if (status != null) _status = status; + _recomputeCritical(); + notifyListeners(); + } + + /// 撤销:弹出 [_undo] 顶部的快照并压入 [_redo],重算关键路径后刷新。 + void undo() { + if (_undo.isEmpty) return; + _redo.add(_project); + _project = _undo.removeLast(); + _dirty = true; + _status = '撤销'; + _recomputeCritical(); + notifyListeners(); + } + + /// 重做:与 [undo] 对称,从 [_redo] 恢复快照。 + void redo() { + if (_redo.isEmpty) return; + _undo.add(_project); + _project = _redo.removeLast(); + _dirty = true; + _status = '重做'; + _recomputeCritical(); + notifyListeners(); + } + + /// 在深色/浅色主题之间切换并刷新界面。 + void toggleTheme() { + _brightness = _brightness == Brightness.dark ? Brightness.light : Brightness.dark; + notifyListeners(); + } + + /// 新建项目:清空历史,构造一个含两个工位、两个动作(动作 1 / 动作 2)的初始项目。 + /// + /// 副作用:重置文件路径、置脏、更新状态并重算关键路径。 + void newProject() { + _undo.clear(); + _redo.clear(); + _project = Project( + name: '未命名节拍', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0), + Station(id: 'ST2', name: '工位 2', order: 1, color: 0xFFFFD166), + ], + actions: [ + Action(id: 'A1', name: '动作 1', stationId: 'ST1', driver: '气缸 Y1', startAngle: 0, durationAngle: 70, layer: 0, row: 0, color: kActionPalette[0]), + Action( + id: 'A2', + name: '动作 2', + stationId: 'ST2', + driver: '气缸 Y2', + startAngle: 80, + durationAngle: 60, + layer: 1, + row: 1, + color: kActionPalette[1], + deps: const [Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)], + ), + ], + units: _project.units, + viewState: ViewState(mode: _project.viewState.mode, selectedIds: const ['A1']), + ); + _filePath = null; + _dirty = true; + _status = '新建项目'; + _recomputeCritical(); + notifyListeners(); + } + + /// 载入一个项目(打开文件或恢复自动保存时使用)。 + /// + /// 参数 [p]:项目数据;[path]:来源文件路径;[dirty]:载入后是否标记为脏 + /// (如自动恢复场景)。副作用:清空撤销/重做栈、重算关键路径并刷新。 + void loadProject(Project p, {String? path, bool dirty = false}) { + _undo.clear(); + _redo.clear(); + _project = p; + _filePath = path; + _dirty = dirty; + _status = path == null ? '已载入' : '已打开 ${_baseName(path)}'; + _recomputeCritical(); + notifyListeners(); + } + + /// 另存为:将当前项目写入 [path] 并更新文件路径、脏标记与保存时间。 + Future saveAs(String path) async { + await Storage.instance.saveProject(path, _project); + _filePath = path; + _dirty = false; + _lastSavedAt = DateTime.now(); + _status = '已保存 ${_baseName(path)}'; + notifyListeners(); + } + + /// 保存到当前路径;无路径时返回 false(需要调用方改用 [saveAs])。 + Future save() async { + if (_filePath == null) return false; + await saveAs(_filePath!); + return true; + } + + /// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。 + static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last; + + /// 切换视图模式并更新状态栏文本。 + void setViewMode(ViewMode mode) { + _project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode)); + _status = mode == ViewMode.bar ? '条形节拍视图' : '圆周节拍视图'; + notifyListeners(); + } + + /// 选中指定动作([id] 为 null 表示清空选中)并刷新。 + /// + /// [toggle] 为 true 时(Ctrl/Shift 点击)在选中集合中切换该动作, + /// 从而实现多选;否则替换为单选。选中仅改变视图状态,不影响脏标记。 + void select(String? id, {bool toggle = false}) { + final List cur = List.of(_project.viewState.selectedIds); + if (id == null) { + cur.clear(); + } else if (toggle) { + if (cur.contains(id)) { + cur.remove(id); + } else { + cur.add(id); + } + } else { + cur + ..clear() + ..add(id); + } + _project = _project.copyWith(viewState: _project.viewState.copyWith(selectedIds: cur)); + notifyListeners(); + } + + /// 直接设置缩放系数,自动钳制到 `[0.25, 4.0]`。 + void setZoom(double z) { + final double v = z.clamp(0.25, 4.0); + _project = _project.copyWith(viewState: _project.viewState.copyWith(zoom: v)); + notifyListeners(); + } + + /// 以视口坐标 [focal] 为锚点缩放,保证锚点下的内容不漂移。 + /// + /// 屏幕坐标与逻辑坐标关系为 `screen = logical × zoom + pan`; + /// 令锚点处的逻辑点保持不变,可解得新的平移量: + /// `pan' = focal − (focal − pan) × (zoom' / zoom)`。 + void zoomAt(double factor, Offset focal) { + final ViewState v = _project.viewState; + final double nz = (v.zoom * factor).clamp(0.25, 4.0); + if ((nz - v.zoom).abs() < 0.0001) return; + final double k = nz / v.zoom; + final double px = focal.dx - (focal.dx - v.panX) * k; + final double py = focal.dy - (focal.dy - v.panY) * k; + _project = _project.copyWith( + viewState: v.copyWith(zoom: nz, panX: px, panY: py), + ); + notifyListeners(); + } + + /// 以视口中心为锚点缩放(工具栏 ± 按钮使用)。 + void zoomBy(double factor) { + final Size vp = _viewport; + final Offset focal = vp.isEmpty ? Offset.zero : Offset(vp.width / 2, vp.height / 2); + zoomAt(factor, focal); + } + + /// 按偏移量 [d] 平移视图。 + void panBy(Offset d) { + _project = _project.copyWith( + viewState: _project.viewState.copyWith( + panX: _project.viewState.panX + d.dx, + panY: _project.viewState.panY + d.dy, + ), + ); + notifyListeners(); + } + + /// 复位视图:缩放归 1、平移归零(回到布局默认的居中状态)。 + void resetView() { + _project = _project.copyWith(viewState: _project.viewState.copyWith(zoom: 1, panX: 0, panY: 0)); + _status = '复位视图'; + notifyListeners(); + } + + /// 切换依赖连线的显示/隐藏。 + void toggleDeps() { + _project = _project.copyWith( + viewState: _project.viewState.copyWith(showDeps: !_project.viewState.showDeps), + ); + notifyListeners(); + } + + /// 批量设置视图显示开关;传入 null 的项保持原值。 + void setViewFlag({ + bool? showDeps, + bool? showRuler, + bool? showPhaseBands, + bool? showRingBg, + bool? showLayerLabels, + }) { + _project = _project.copyWith( + viewState: _project.viewState.copyWith( + showDeps: showDeps, + showRuler: showRuler, + showPhaseBands: showPhaseBands, + showRingBg: showRingBg, + showLayerLabels: showLayerLabels, + ), + ); + notifyListeners(); + } + + /// 适应窗口:按当前视图内容计算缩放与平移,使其完整可见。 + /// + /// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放, + /// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。 + /// - 条形视图:布局本身按视口高度自适应,直接回到 `zoom = 1`。 + void fitView() { + final Size vp = _viewport; + if (vp.width <= 0 || vp.height <= 0) { + resetView(); + return; + } + double z = 1; + double px = 0; + double py = 0; + if (_project.viewState.mode == ViewMode.circular) { + final CircularLayout l = CircularLayout(_project, vp); + // 半径需覆盖:刻度文字(tickR + ~50)、顺时针箭头(rMax + ~70)、 + // 12 点钟起点标记(tickR + ~70),再留 20px 余量,避免任何标注被裁掉。 + final double contentR = math.max(l.tickR + 90, l.rMax + 100); + // 顶部为标题浮层预留约 60px,底部留 60px。 + final double availW = vp.width - 40; + final double availH = vp.height - 120; + z = (math.min(availW, availH) / (contentR * 2)).clamp(0.25, 4.0); + final Offset center = l.center; + px = vp.width / 2 - center.dx * z; + py = vp.height / 2 - center.dy * z; + } else { + final BarLayout l = BarLayout(_project, vp); + final double contentW = l.plotRight + 60; + final double contentH = l.yFor(l.ordered.length) + 40; + z = math.min(vp.width / contentW, vp.height / contentH).clamp(0.25, 1.0); + px = 0; + py = 0; + } + _project = _project.copyWith( + viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py), + ); + _status = '适应窗口'; + notifyListeners(); + } + + /// 替换相位分区列表(名称 / 起止角 / 数量均可改,允许区间重叠)。 + void setPhaseZones(List zones, {String? status}) { + _project = _project.copyWith(phaseZones: zones); + _dirty = true; + _status = status ?? '相位分区已更新'; + notifyListeners(); + } + + /// 更新项目名称并标记为脏。 + void setProjectName(String name) { + _project = _project.copyWith(name: name); + _dirty = true; + _status = '项目名称已更新'; + notifyListeners(); + } + + /// 替换单位设置并标记为脏;[status] 可自定义状态栏文本。 + void setUnits(UnitSettings u, {String? status}) { + _project = _project.copyWith(units: u); + _dirty = true; + _status = status ?? '单位设置已更新'; + notifyListeners(); + } + + /// 修改循环时长(毫秒)。 + /// + /// 参数 [keepAngle]:为 true 时保持各动作角度不变;为 false 时按 + /// `旧时长 / 新时长` 缩放所有动作的起始角与持续角,从而保持其时间不变。 + /// 副作用:通过 [_mutate] 记录历史并重算关键路径。 + void setCycleDuration(double ms, {bool keepAngle = true}) { + // 计算角度缩放比例:keepAngle 时保持 1;否则按旧/新时长比例缩放。 + double angleScale = 1; + if (!keepAngle && _project.cycle.durationMs > 0) { + angleScale = _project.cycle.durationMs / ms; + } + List actions = _project.actions; + if (angleScale != 1) { + actions = actions + .map((Action a) => a.copyWith( + startAngle: a.startAngle * angleScale, + durationAngle: a.durationAngle * angleScale, + )) + .toList(); + } + _mutate(_project.copyWith(cycle: _project.cycle.copyWith(durationMs: ms), actions: actions), + status: '循环时长 ${ms.toStringAsFixed(0)} ms'); + } + + /// 新增一个动作,并将其置于最外层。 + /// + /// 参数 [startAngle]:可选起始角(钳制到 `[0, 359]`,默认 0); + /// [stationId]:可选归属工位(默认第一个工位)。 + /// 副作用:生成不冲突的 id、选中新动作、记录历史并重算关键路径。 + void addAction({double? startAngle, String? stationId}) { + // 生成唯一 id:从 A{n} 起,若冲突则递增 guard 直到不重复。 + final int n = _project.actions.length + 1; + String id = 'A$n'; + int guard = n; + while (_project.actionById(id) != null) { + guard++; + id = 'A$guard'; + } + final int layer = _project.maxLayer + 1; + // 新动作默认排在最后一行(显式行序),避免其相位变化导致行位置跳动。 + final int row = _project.actions.length; + final double start = (startAngle ?? 0).clamp(0, 359); + final Action a = Action( + id: id, + name: '动作 $n', + stationId: stationId ?? (_project.stations.isNotEmpty ? _project.stations.first.id : 'ST1'), + driver: '', + startAngle: start, + durationAngle: 45, + layer: layer, + color: kActionPalette[(_project.actions.length) % kActionPalette.length], + row: row, + ); + _mutate( + _project.copyWith( + actions: [..._project.actions, a], + viewState: _project.viewState.copyWith(selectedIds: [a.id]), + ), + status: '新增 $id(最外层 L${layer + 1})', + ); + } + + /// 删除指定动作,并清理其它动作中指向/来自它的依赖。 + /// + /// 若 [id] 不存在则直接返回(不产生历史记录)。副作用:若被删动作处于选中 + /// 状态则清除选中,记录历史并重算关键路径。 + void deleteAction(String id) { + // 过滤掉目标动作,并从其余动作的依赖中移除与目标相关的边。 + final List actions = _project.actions + .where((Action a) => a.id != id) + .map((Action a) => a.copyWith( + deps: a.deps.where((Dependency d) => d.fromId != id && d.toId != id).toList(), + )) + .toList(); + if (actions.length == _project.actions.length) return; + _mutate( + _project.copyWith( + actions: actions, + viewState: _project.viewState.copyWith( + selectedIds: _project.viewState.selectedIds.where((String s) => s != id).toList(), + ), + ), + status: '删除 $id', + ); + } + + /// 复制当前选中的动作。 + /// + /// 副本起始角相对原动作 +10°(钳制到 `[0, 359]`)、置于最外层、且不继承依赖。 + /// 副作用:选中新副本、记录历史并重算关键路径;无选中时不做任何事。 + void duplicateSelected() { + final Action? src = selected; + if (src == null) return; + // 生成不冲突的新 id。 + final int n = _project.actions.length + 1; + String id = 'A$n'; + int guard = n; + while (_project.actionById(id) != null) { + guard++; + id = 'A$guard'; + } + final Action a = src.copyWith( + id: id, + name: '${src.name} 副本', + startAngle: (src.startAngle + 10).clamp(0, 359), + layer: _project.maxLayer + 1, + row: _project.actions.length, + deps: const [], + ); + _mutate( + _project.copyWith( + actions: [..._project.actions, a], + viewState: _project.viewState.copyWith(selectedIds: [a.id]), + ), + status: '复制 $id', + ); + } + + /// 以函数式方式更新动作:对 id 匹配的动作应用 [fn],其余保持不变。 + /// + /// 参数 [id]:目标动作;[fn]:变换函数;[status]:可选状态栏文本。 + /// 副作用:经 [_mutate] 记录历史、重算关键路径并刷新。 + void updateAction(String id, Action Function(Action) fn, {String? status}) { + final List actions = _project.actions + .map((Action a) => a.id == id ? fn(a) : a) + .toList(); + _mutate(_project.copyWith(actions: actions), status: status); + } + + /// 按角度增量 [deltaAngle] 移动动作起点。 + /// + /// 参数 [snap]:是否按 [Cycle.snapDeg] 吸附。 + /// 起点会被钳制到 `[0, 360 - durationAngle]`,保证动作不越界。 + void moveAction(String id, double deltaAngle, {bool snap = true}) { + final Action? a = _project.actionById(id); + if (a == null) return; + final double step = snap ? _project.cycle.snapDeg : 0; + double ns = a.startAngle + deltaAngle; + ns = ns.clamp(0, 360 - a.durationAngle); + if (step > 0) ns = snapTo(ns, step); + updateAction(id, (Action x) => x.copyWith(startAngle: ns)); + } + + /// 直接设置动作起始角(可吸附)。 + /// + /// 起点钳制到 `[0, 360 - durationAngle]`,避免超出整圈。 + void setActionStart(String id, double start, {bool snap = true}) { + final Action? a = _project.actionById(id); + if (a == null) return; + final double step = snap ? _project.cycle.snapDeg : 0; + double ns = start.clamp(0, 360 - a.durationAngle); + if (step > 0) ns = snapTo(ns, step); + updateAction(id, (Action x) => x.copyWith(startAngle: ns)); + } + + /// 设置动作持续角(可吸附)。 + /// + /// 持续角先钳制到 `[5, 360]`;若 `start + duration > 360` 则压缩为 + /// `360 - start`,保证动作不跨出整圈。 + void setActionDuration(String id, double duration, {bool snap = true}) { + final Action? a = _project.actionById(id); + if (a == null) return; + final double step = snap ? _project.cycle.snapDeg : 0; + double nd = duration.clamp(5, 360); + if (step > 0) nd = snapTo(nd, step); + if (a.startAngle + nd > 360) nd = 360 - a.startAngle; + updateAction(id, (Action x) => x.copyWith(durationAngle: nd)); + } + + /// 按增量 [delta] 调整动作层号,结果钳制到 `[0, 63]`;无变化时不记录历史。 + void changeLayer(String id, int delta) { + final Action? a = _project.actionById(id); + if (a == null) return; + final int nl = (a.layer + delta).clamp(0, 63); + if (nl == a.layer) return; + updateAction(id, (Action x) => x.copyWith(layer: nl), status: '层 L${nl + 1}'); + } + + /// 直接设置动作层号(钳制到 `[0, 63]`)。 + void setLayer(String id, int layer) { + final int nl = layer.clamp(0, 63); + updateAction(id, (Action x) => x.copyWith(layer: nl), status: '层 L${nl + 1}'); + } + + /// 将动作 [id] 移动到条形视图的第 [targetIndex] 行(上下拖拽排序)。 + /// + /// 会把所有动作的显式行序 `row` 重写为紧凑的 `0..n-1`,从而**固定行位置**, + /// 之后水平拖动只改相位、不再改变行。 + void moveActionRow(String id, int targetIndex) { + final Action? moving = _project.actionById(id); + if (moving == null) return; + final List list = orderActions(_project); + final int from = list.indexWhere((Action a) => a.id == id); + if (from < 0) return; + final Action a = list.removeAt(from); + final int to = targetIndex.clamp(0, list.length); + if (to == from) { + // 行序未变,但如果此前没有显式行序,则补齐一次。 + final bool already = _project.actions.every((Action x) => x.row >= 0); + if (already) return; + } + list.insert(to, a); + final Map rowById = { + for (int i = 0; i < list.length; i++) list[i].id: i, + }; + final List actions = _project.actions + .map((Action x) => x.copyWith(row: rowById[x.id] ?? x.row)) + .toList(); + _mutate(_project.copyWith(actions: actions), status: '调整 $id 行序'); + } + + /// 移动某个相位分区的一条边界(用于在条形图顶部直接拖拽分区)。 + /// + /// 参数 [index]:分区下标;[isStart]:true 改起始角,false 改结束角; + /// [angle]:目标角度(度)。结束角允许大于 360° 表示跨圈。 + void movePhaseZoneBoundary(int index, bool isStart, double angle) { + if (index < 0 || index >= _project.phaseZones.length) return; + final PhaseZone z = _project.phaseZones[index]; + final double a = angle.clamp(0, 400); + final PhaseZone nz = isStart ? z.copyWith(startAngle: a) : z.copyWith(endAngle: a); + final List zones = List.of(_project.phaseZones)..[index] = nz; + setPhaseZones(zones, status: '调整相位分区'); + } + + /// 对齐相位:把所有选中动作的起始角对齐到**主选中项**的起始角。 + /// + /// 支持 Ctrl 多选后一次对齐多个动作;只有一个选中时等价于对齐到自身(无变化), + /// 若主选中项起始角为 0 则等价于“对齐到 0°”。 + void alignPhase() { + final List ids = _project.viewState.selectedIds; + if (ids.isEmpty) return; + final Action? ref = _project.actionById(ids.first); + if (ref == null) return; + final double target = ref.startAngle; + final List actions = _project.actions.map((Action a) { + if (!ids.contains(a.id)) return a; + final double ns = target.clamp(0, 360 - a.durationAngle); + return a.copyWith(startAngle: ns); + }).toList(); + _mutate(_project.copyWith(actions: actions), status: '对齐相位(${ids.length} 个动作)'); + } + + /// 添加/覆盖一条依赖:在 [toId] 上记录来自 [fromId] 的依赖。 + /// + /// 参数 [fromId]/[toId]:前驱/后继动作;[type]:依赖类型;[offset]:角度偏移。 + /// 自依赖(fromId == toId)或后继不存在时忽略。若同一前驱已存在则先移除再添加。 + void addDependency(String fromId, String toId, DepType type, double offset) { + if (fromId == toId) return; + final Action? to = _project.actionById(toId); + if (to == null) return; + updateAction( + toId, + (Action x) => x.copyWith( + deps: [ + ...x.deps.where((Dependency d) => d.fromId != fromId), + Dependency(fromId: fromId, toId: toId, type: type, offsetAngle: offset), + ], + ), + status: '添加依赖 $fromId→$toId', + ); + } + + /// 移除 [toId] 上来自 [fromId] 的依赖。 + void removeDependency(String fromId, String toId) { + updateAction( + toId, + (Action x) => x.copyWith( + deps: x.deps.where((Dependency d) => d.fromId != fromId).toList(), + ), + status: '删除依赖 $fromId→$toId', + ); + } + + /// 计算关键路径并更新 [_criticalActions] / [_criticalDeps]。 + /// + /// 采用“最早开始时间(EST)+ 拓扑排序 + 反向回溯”的经典方法: + /// 1. 依据依赖边构建前驱计数(indeg)与后继邻接表(succ); + /// 2. Kahn 算法拓扑排序;若存在环导致排序不完整,则退化为原始顺序; + /// 3. 按拓扑序计算每个动作的最早开始时间,并记录贡献最大约束的前驱; + /// 4. 找出结束时间最晚的动作,沿 prev 反向回溯得到关键动作与关键依赖。 + /// + /// 副作用:替换 [_criticalActions] 与 [_criticalDeps];不触发通知。 + void _recomputeCritical() { + // 步骤 0:建立 id -> Action 索引,便于 O(1) 查询。 + final Map byId = { + for (final Action a in _project.actions) a.id: a, + }; + final Map earliest = {}; + final Map prev = {}; + final List order = _project.actions.map((Action a) => a.id).toList(); + final Map indeg = {for (final String id in order) id: 0}; + final Map> succ = >{}; + // 步骤 1:遍历依赖边,统计入度并构建后继邻接表(忽略悬空引用)。 + for (final Action a in _project.actions) { + for (final Dependency d in a.deps) { + if (byId.containsKey(d.fromId) && indeg.containsKey(a.id)) { + indeg[a.id] = indeg[a.id]! + 1; + succ.putIfAbsent(d.fromId, () => []).add(a.id); + } + } + } + // 步骤 2:Kahn 拓扑排序,从入度为 0 的节点开始。 + final List queue = order.where((String id) => indeg[id] == 0).toList(); + for (final String id in order) { + earliest[id] = 0; + prev[id] = null; + } + final List topo = []; + while (queue.isNotEmpty) { + final String id = queue.removeAt(0); + topo.add(id); + for (final String s in succ[id] ?? []) { + indeg[s] = indeg[s]! - 1; + if (indeg[s] == 0) queue.add(s); + } + } + // 若排序结果不完整(存在环),退化为原始动作顺序,保证算法仍可推进。 + if (topo.length != order.length) { + topo + ..clear() + ..addAll(order); + } + // 步骤 3:按拓扑序求最早开始时间,记录产生该时间的“关键前驱”。 + for (final String id in topo) { + final Action a = byId[id]!; + double est = 0; + String? p; + for (final Dependency d in a.deps) { + final Action? pred = byId[d.fromId]; + if (pred == null) continue; + final double predEnd = (earliest[pred.id] ?? 0) + pred.durationAngle; + double cand; + // 按依赖类型计算约束候选值: + // FS:前驱结束后开始(predEnd + offset) + // SS:前驱开始后开始(predStart + offset) + // FF:前驱结束后结束(predEnd + offset - 本动作时长) + // SF:前驱开始后结束(predStart + offset - 本动作时长) + switch (d.type) { + case DepType.fs: + cand = predEnd + d.offsetAngle; + break; + case DepType.ss: + cand = (earliest[pred.id] ?? 0) + d.offsetAngle; + break; + case DepType.ff: + cand = predEnd + d.offsetAngle - a.durationAngle; + break; + case DepType.sf: + cand = (earliest[pred.id] ?? 0) + d.offsetAngle - a.durationAngle; + break; + } + if (cand > est) { + est = cand; + p = pred.id; + } + } + earliest[id] = est; + prev[id] = p; + } + // 步骤 4a:找到结束时间最晚的动作作为关键路径终点。 + String? last; + double bestEnd = -1; + for (final Action a in _project.actions) { + final double end = (earliest[a.id] ?? 0) + a.durationAngle; + if (end > bestEnd) { + bestEnd = end; + last = a.id; + } + } + // 步骤 4b:沿 prev 链反向回溯,收集关键动作与关键依赖边。 + final Set critA = {}; + final Set critD = {}; + String? cur = last; + while (cur != null) { + critA.add(cur); + final String? p = prev[cur]; + if (p != null) critD.add('$p->$cur'); + cur = p; + } + _criticalActions = critA; + _criticalDeps = critD; + } +} diff --git a/lib/theme/tokens.dart b/lib/theme/tokens.dart new file mode 100644 index 0000000..d930d43 --- /dev/null +++ b/lib/theme/tokens.dart @@ -0,0 +1,333 @@ +/// 主题设计令牌(Design Tokens)模块。 +/// +/// 职责:集中定义整个产品的语义化视觉基础——颜色、阴影透明度、亮度等, +/// 并把它们接入 Flutter 的主题扩展机制,供界面、画布渲染与 SVG 导出共用。 +/// +/// 架构位置: +/// - 渲染层(`lib/render/`)与导出层(`lib/export/`)都通过 [Tokens] 读取颜色, +/// 从而保证画布绘制、SVG 导出与 Material 界面三者配色完全一致。 +/// - 深色与浅色两套令牌分别以 [Tokens.dark]、[Tokens.light] 常量提供, +/// 由 [Tokens.of] 按 [Brightness] 选择。 +/// - [buildTheme] 将令牌转换为 [ThemeData],并通过 [TokensTheme] 注入, +/// 自绘组件可经 [TokensX] 扩展读取。 +library; + +import 'package:flutter/material.dart'; + +/// 应用统一的语义化主题令牌集合。 +/// +/// 所有字段均为不可变的颜色或数值,实例以 const 构造,因此可用于编译期常量 +/// (如静态的 [dark]、[light])。令牌本身不包含任何绘制逻辑, +/// 只描述“语义角色 → 具体颜色/数值”的映射。 +class Tokens { + /// 创建令牌集合,所有字段均为必填。 + /// + /// 参数即各语义颜色/数值本身;构造过程无副作用。 + const Tokens({ + required this.bg, + required this.canvas1, + required this.canvas2, + required this.chrome, + required this.panel, + required this.panel2, + required this.dialog, + required this.line, + required this.line2, + required this.text, + required this.text2, + required this.sub, + required this.dim, + required this.accent, + required this.accent2, + required this.ok, + required this.warn, + required this.danger, + required this.fs, + required this.ss, + required this.crit, + required this.chip, + required this.dial, + required this.arcText, + required this.onAccent, + required this.ringA, + required this.ringB, + required this.ringEdge, + required this.ringLabel, + required this.info, + required this.track, + required this.sel, + required this.grid, + required this.shadow, + required this.shadowOp, + required this.selOutline, + required this.overlay, + required this.tailOp, + required this.brightness, + }); + + // ── 基础背景与容器 ────────────────────────────────────────────── + /// 应用最底层背景色(窗口/页面底色)。 + final Color bg; + /// 画布渐变起始色(较亮端)。 + final Color canvas1; + /// 画布渐变结束色(较暗端)。 + final Color canvas2; + /// 工具栏、标题栏等窗口外框颜色。 + final Color chrome; + /// 主面板背景色。 + final Color panel; + /// 次级面板 / 行交替背景色。 + final Color panel2; + /// 对话框背景色。 + final Color dialog; + + // ── 线条与文本 ────────────────────────────────────────────────── + /// 细分割线颜色。 + final Color line; + /// 强分割线 / 描边颜色。 + final Color line2; + /// 主文本颜色。 + final Color text; + /// 次级文本颜色。 + final Color text2; + /// 辅助说明文本颜色。 + final Color sub; + /// 最弱 / 占位文本颜色。 + final Color dim; + + // ── 强调与状态 ────────────────────────────────────────────────── + /// 主强调色(选中、相位轴、主操作)。 + final Color accent; + /// 次强调色(例如顺时针方向提示)。 + final Color accent2; + /// 成功 / 正常状态色。 + final Color ok; + /// 警告 / 跨循环提示色。 + final Color warn; + /// 危险 / 错误状态色。 + final Color danger; + + // ── 时序语义色 ────────────────────────────────────────────────── + /// Finish-to-Start(FS)依赖连线颜色。 + final Color fs; + /// Start-to-Start(SS)依赖连线颜色。 + final Color ss; + /// 关键路径高亮色。 + final Color crit; + /// 标签胶囊背景色。 + final Color chip; + + // ── 圆形视图专用 ──────────────────────────────────────────────── + /// 表盘 / 圆环内部底色。 + final Color dial; + /// 动作条块 / 圆弧上的文字颜色(需与动作底色形成对比)。 + final Color arcText; + /// 强调色之上的文字颜色。 + final Color onAccent; + /// 圆环层偶数行的背景色。 + final Color ringA; + /// 圆环层奇数行的背景色。 + final Color ringB; + /// 圆环边界描边色。 + final Color ringEdge; + /// 圆环层号(L1、L2…)文字色。 + final Color ringLabel; + + // ── 其它控件与装饰 ────────────────────────────────────────────── + /// 信息提示条背景色。 + final Color info; + /// 轨道 / 滑块底色。 + final Color track; + /// 选中项背景色。 + final Color sel; + /// 网格线颜色。 + final Color grid; + /// 阴影颜色(配合 [shadowOp] 使用)。 + final Color shadow; + /// 阴影不透明度;绘制投影时与该值相乘。 + final double shadowOp; + /// 选中描边颜色。 + final Color selOutline; + /// 遮罩层颜色。 + final Color overlay; + /// 跨循环延续段的透明度(小于 1 表示淡化)。 + final double tailOp; + /// 令牌所属亮度模式,用于与 Material 主题保持一致。 + final Brightness brightness; + + /// 当前令牌是否属于深色模式。 + /// + /// 返回 `true` 表示 [brightness] 为 [Brightness.dark]。 + bool get isDark => brightness == Brightness.dark; + + /// 深色模式令牌常量。 + /// + /// 各颜色以 ARGB 十六进制字面量给出,供渲染与导出层直接引用。 + static const Tokens dark = Tokens( + bg: Color(0xFF0B1018), + canvas1: Color(0xFF0E1520), + canvas2: Color(0xFF0A0F18), + chrome: Color(0xFF0F1622), + panel: Color(0xFF121A28), + panel2: Color(0xFF0F1723), + dialog: Color(0xFF101827), + line: Color(0xFF1F2C40), + line2: Color(0xFF2A3A52), + text: Color(0xFFE8EEFC), + text2: Color(0xFFCFD9EA), + sub: Color(0xFF8EA0BD), + dim: Color(0xFF5C6F8C), + accent: Color(0xFF4CC9F0), + accent2: Color(0xFF7C5CFF), + ok: Color(0xFF34D399), + warn: Color(0xFFFFD166), + danger: Color(0xFFFF6B6B), + fs: Color(0xFF4ADE80), + ss: Color(0xFFFFD166), + crit: Color(0xFF4CC9F0), + chip: Color(0xFF0B1018), + dial: Color(0xFF0C1320), + arcText: Color(0xFF0A0F18), + onAccent: Color(0xFF04121B), + ringA: Color(0xFF18222F), + ringB: Color(0xFF121A28), + ringEdge: Color(0xFF26374F), + ringLabel: Color(0xFF42597A), + info: Color(0xFF131D2E), + track: Color(0xFF1B2740), + sel: Color(0xFF182437), + grid: Color(0xFF1C2940), + shadow: Color(0xFF000000), + shadowOp: 0.32, + selOutline: Color(0xFFFFFFFF), + overlay: Color(0xFF04080F), + tailOp: 0.45, + brightness: Brightness.dark, + ); + + /// 浅色模式令牌常量。 + /// + /// 与 [dark] 一一对应,仅取值不同;语义角色完全一致。 + static const Tokens light = Tokens( + bg: Color(0xFFEAEFF6), + canvas1: Color(0xFFFFFFFF), + canvas2: Color(0xFFF5F8FC), + chrome: Color(0xFFFFFFFF), + panel: Color(0xFFFFFFFF), + panel2: Color(0xFFF6F9FC), + dialog: Color(0xFFFFFFFF), + line: Color(0xFFE4EAF3), + line2: Color(0xFFC9D6E5), + text: Color(0xFF1B2740), + text2: Color(0xFF334155), + sub: Color(0xFF4A5A72), + dim: Color(0xFF8FA0B8), + accent: Color(0xFF0284C7), + accent2: Color(0xFF7C3AED), + ok: Color(0xFF059669), + warn: Color(0xFFC2740A), + danger: Color(0xFFDC2626), + fs: Color(0xFF15803D), + ss: Color(0xFFB45309), + crit: Color(0xFF0284C7), + chip: Color(0xFFFFFFFF), + dial: Color(0xFFEEF3F9), + // 动作色块/圆弧上的文字:调色板始终是亮色,故两套主题都用深色字, + // 保证“白底/黑底”下都能看清。 + arcText: Color(0xFF0B1018), + onAccent: Color(0xFFFFFFFF), + ringA: Color(0xFFE8EFF8), + ringB: Color(0xFFDBE5F1), + ringEdge: Color(0xFFC2D2E4), + ringLabel: Color(0xFF8FA3BC), + info: Color(0xFFF3F7FB), + track: Color(0xFFDFE8F2), + sel: Color(0xFFDCEFFF), + grid: Color(0xFFD6E0EC), + shadow: Color(0xFF7C8FA6), + shadowOp: 0.16, + selOutline: Color(0xFF0F172A), + overlay: Color(0xFF0F172A), + tailOp: 0.55, + brightness: Brightness.light, + ); + + /// 按亮度选择对应的令牌集合。 + /// + /// 参数 [b] 为 [Brightness.dark] 时返回 [dark],否则返回 [light]。 + /// 纯函数,无副作用。 + static Tokens of(Brightness b) => b == Brightness.dark ? dark : light; +} + +/// [BuildContext] 便捷扩展:从主题扩展中读取 [Tokens]。 +extension TokensX on BuildContext { + /// 返回当前上下文所注册的令牌集合。 + /// + /// 依赖 [TokensTheme] 已由 [buildTheme] 注入主题; + /// 若该扩展缺失会触发空断言错误。 + Tokens get tok => Theme.of(this).extension()!.tokens; +} + +/// 把 [Tokens] 挂载到 Flutter [ThemeExtension] 机制上的包装类。 +/// +/// 使令牌能够随主题一起参与 [lerp] 过渡与 [copyWith] 复制。 +class TokensTheme extends ThemeExtension { + /// 使用给定令牌创建主题扩展。 + const TokensTheme(this.tokens); + + /// 被包装的令牌集合。 + final Tokens tokens; + + /// 返回替换 [tokens] 后的新实例(其余保持不变)。 + @override + TokensTheme copyWith({Tokens? tokens}) => TokensTheme(tokens ?? this.tokens); + + /// 在两套令牌之间做插值。 + /// + /// 由于 [Tokens] 不支持逐字段插值,这里采用阶跃过渡: + /// `t < 0.5` 时保留旧值,否则切换到新值。 + @override + TokensTheme lerp(ThemeExtension? other, double t) { + if (other is! TokensTheme) return this; + return t < 0.5 ? this : other; + } +} + +/// 依据给定令牌构建全局 [ThemeData]。 +/// +/// 参数 [t]:要应用的设计令牌。 +/// 返回:启用 Material 3、并配置了配色方案、字体与文本主题的 [ThemeData]。 +/// 副作用:无外部副作用;但会把 [TokensTheme] 注册进 `extensions`, +/// 供 [TokensX] 在组件树中读取。 +/// 不变式:[ColorScheme.fromSeed] 的种子色取自 [Tokens.accent], +/// 以保证 Material 组件与自绘组件使用同一强调色。 +ThemeData buildTheme(Tokens t) { + // 以强调色为种子生成配色,再用令牌覆盖关键角色: + // surface=面板、primary=强调色、secondary=次强调、error=危险色。 + final ColorScheme scheme = ColorScheme.fromSeed( + seedColor: t.accent, + brightness: t.brightness, + ).copyWith( + surface: t.panel, + onSurface: t.text, + primary: t.accent, + secondary: t.accent2, + error: t.danger, + ); + return ThemeData( + useMaterial3: true, + brightness: t.brightness, + colorScheme: scheme, + scaffoldBackgroundColor: t.bg, + // 使用 Windows 的 UI 版字体(针对屏幕显示优化,比普通版更锐利), + // 并为西文/数字回退到 Segoe UI。 + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Segoe UI', 'sans-serif'], + extensions: >[TokensTheme(t)], + dividerColor: t.line, + textTheme: TextTheme( + bodyMedium: TextStyle(color: t.text, fontSize: 12), + bodySmall: TextStyle(color: t.sub, fontSize: 11), + ), + ); +} diff --git a/lib/ui/ai_dialog.dart b/lib/ui/ai_dialog.dart new file mode 100644 index 0000000..c406643 --- /dev/null +++ b/lib/ui/ai_dialog.dart @@ -0,0 +1,280 @@ +/// AI 生成时序图对话框。 +/// +/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)与推理强度 +/// (高 / 最高)→ 在较大的自然语言输入框中描述工艺流程 → 点击「生成」, +/// 由 [AiClient] 调用大模型并解析为 [Project],成功后载入工作台。 +/// +/// 安全:API Key 仅保存在内存(静态字段,便于本次会话内复用), +/// 不写入工程文件,也不会被日志输出。 +library; + +import 'package:flutter/material.dart'; + +import '../ai/ai_client.dart'; +import '../model/models.dart'; +import '../state/app_controller.dart'; +import '../theme/tokens.dart'; + +class AiGenerateDialog extends StatefulWidget { + const AiGenerateDialog({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + @override + State createState() => _AiGenerateDialogState(); +} + +class _AiGenerateDialogState extends State { + /// 会话内复用的 API Key(不持久化)。 + static String _sessionKey = ''; + + late final TextEditingController _key; + late final TextEditingController _prompt; + + String _model = kAiModels.first.id; + String _effort = 'high'; + bool _obscure = true; + bool _busy = false; + String? _error; + + @override + void initState() { + super.initState(); + _key = TextEditingController(text: _sessionKey); + _prompt = TextEditingController(); + } + + @override + void dispose() { + _key.dispose(); + _prompt.dispose(); + super.dispose(); + } + + Future _generate() async { + setState(() { + _busy = true; + _error = null; + }); + try { + _sessionKey = _key.text.trim(); + final Project p = await AiClient.generate( + prompt: _prompt.text, + settings: AiSettings(apiKey: _sessionKey, model: _model, effort: _effort), + ); + widget.controller.loadProject(p, dirty: true); + widget.controller.setStatus('AI 已生成时序图(${p.actions.length} 个动作)'); + if (mounted) Navigator.pop(context); + } catch (e) { + if (mounted) setState(() => _error = '$e'); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 880, + height: 620, + child: Padding( + padding: const EdgeInsets.all(18), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 标题 + Row( + children: [ + Icon(Icons.auto_awesome, size: 20, color: t.accent2), + const SizedBox(width: 8), + Text('AI 生成时序图', style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w700)), + const Spacer(), + Text('自然语言 → 时序图', style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + const Divider(height: 22), + + // API Key + Text('DeepSeek API Key', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + TextField( + controller: _key, + obscureText: _obscure, + style: TextStyle(color: t.text, fontSize: 11), + decoration: InputDecoration( + isDense: true, + hintText: 'sk-...', + hintStyle: TextStyle(color: t.dim, fontSize: 11), + filled: true, + fillColor: t.panel2, + prefixIcon: Icon(Icons.key, size: 16, color: t.dim), + suffixIcon: IconButton( + onPressed: () => setState(() => _obscure = !_obscure), + icon: Icon(_obscure ? Icons.visibility_off : Icons.visibility, size: 16, color: t.dim), + tooltip: _obscure ? '显示' : '隐藏', + ), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(height: 14), + + // 模型 + 推理强度 + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('模型', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + Container( + height: 38, + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: t.line2), + ), + child: DropdownButton( + value: _model, + isExpanded: true, + underline: const SizedBox.shrink(), + dropdownColor: t.dialog, + style: TextStyle(color: t.text, fontSize: 11), + icon: Icon(Icons.keyboard_arrow_down, size: 18, color: t.sub), + items: kAiModels + .map((AiModelOption m) => + DropdownMenuItem(value: m.id, child: Text(m.label))) + .toList(), + onChanged: (String? v) { + if (v != null) setState(() => _model = v); + }, + ), + ), + ], + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('推理强度', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + Row( + children: [ + Expanded(child: _effortChip(t, '高', 'high')), + const SizedBox(width: 8), + Expanded(child: _effortChip(t, '最高', 'max')), + ], + ), + ], + ), + ), + ], + ), + const SizedBox(height: 14), + + // 自然语言输入(大输入框) + Text('用自然语言描述工艺流程', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + Expanded( + child: Container( + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line2), + ), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: TextField( + controller: _prompt, + maxLines: null, + expands: true, + textAlignVertical: TextAlignVertical.top, + style: TextStyle(color: t.text, fontSize: 11, height: 1.5), + decoration: InputDecoration.collapsed( + hintText: '例如:一条装配线,循环 2.4 秒。上料后定位夹紧,夹紧完成再伺服下压 0.6 秒;' + '下压完成后并行进行超声波焊接与视觉检测;检测完成分选下料,最后清洁吹气。' + '共 3 个工位,请给出动作、相位与依赖关系。', + hintStyle: TextStyle(color: t.dim, fontSize: 11, height: 1.5), + ), + ), + ), + ), + if (_error != null) ...[ + const SizedBox(height: 10), + Container( + width: double.infinity, + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.danger.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: t.danger.withValues(alpha: 0.5)), + ), + child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11, height: 1.4)), + ), + ], + const SizedBox(height: 14), + + // 操作按钮 + Row( + children: [ + Expanded( + child: Text( + 'API Key 仅保存在本机内存,不写入工程文件。', + style: TextStyle(color: t.dim, fontSize: 10), + ), + ), + TextButton(onPressed: _busy ? null : () => Navigator.pop(context), child: const Text('取消')), + const SizedBox(width: 8), + FilledButton.icon( + onPressed: _busy ? null : _generate, + icon: _busy + ? const SizedBox( + width: 15, + height: 15, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.auto_awesome, size: 16), + label: Text(_busy ? '生成中…' : '生成'), + style: FilledButton.styleFrom( + backgroundColor: t.accent2, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + ), + ), + ], + ), + ], + ), + ), + ), + ); + } + + /// 推理强度分段按钮。 + Widget _effortChip(Tokens t, String label, String value) { + final bool active = _effort == value; + return InkWell( + onTap: () => setState(() => _effort = value), + borderRadius: BorderRadius.circular(8), + child: Container( + height: 38, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.18) : t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: active ? t.accent : t.line2), + ), + child: Text(label, style: TextStyle(color: active ? t.accent : t.sub, fontSize: 11)), + ), + ); + } +} diff --git a/lib/ui/app_logo.dart b/lib/ui/app_logo.dart new file mode 100644 index 0000000..8a1b78b --- /dev/null +++ b/lib/ui/app_logo.dart @@ -0,0 +1,88 @@ +// 应用图标组件:绘制一个与应用程序图标一致的紧凑“时钟 / 周期表盘”标记。 +// +// 架构位置:属于纯 UI 装饰组件,仅依赖主题令牌(Tokens)取色, +// 不持有任何业务状态;在工具栏与启动画面等处复用。 +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../theme/tokens.dart'; + +/// 应用图标:一个简洁的时钟 / 周期表盘标记,呼应产品“节拍”主题。 +class AppLogo extends StatelessWidget { + /// 创建应用图标;[size] 为正方形边长,默认 30。 + const AppLogo({super.key, this.size = 30}); + + /// 图标边长(逻辑像素)。 + final double size; + + /// 使用 [_LogoPainter] 在方形画布上绘制图标。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return CustomPaint( + size: Size.square(size), + painter: _LogoPainter(t), + ); + } +} + +/// 图标绘制器:按主题令牌绘制圆角底板、双色圆弧表盘与指针。 +class _LogoPainter extends CustomPainter { + /// 创建绘制器,[t] 为当前主题令牌。 + _LogoPainter(this.t); + + /// 当前主题令牌,提供配色。 + final Tokens t; + + /// 依次绘制:圆角底板 → 双色圆环弧 → 时针分针 → 中心圆点。 + @override + void paint(Canvas canvas, Size size) { + // 以最短边为基准计算尺寸,保证图标始终为正方形。 + final double s = size.shortestSide; + final Offset c = Offset(size.width / 2, size.height / 2); + // 圆角方形底板:半透明填充 + 主题色描边。 + final RRect badge = RRect.fromRectAndRadius( + Rect.fromLTWH(0, 0, s, s), + Radius.circular(s * 0.28), + ); + canvas.drawRRect(badge, Paint()..color = t.accent.withValues(alpha: 0.16)); + canvas.drawRRect( + badge, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 + ..color = t.accent, + ); + + // 表盘圆环:用两段不同颜色的圆弧表示进度/周期。 + final double r = s * 0.30; + final Paint ring = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = s * 0.075 + ..strokeCap = StrokeCap.round; + ring.color = t.accent; + canvas.drawArc(Rect.fromCircle(center: c, radius: r), -math.pi / 2, + math.pi * 0.55, false, ring); + ring.color = t.accent2; + canvas.drawArc(Rect.fromCircle(center: c, radius: r), -math.pi / 2 + math.pi * 0.62, + math.pi * 0.5, false, ring); + + // 指针:一根主色长针 + 一根强调色短针,从中心向外绘制。 + final Paint hand = Paint() + ..strokeCap = StrokeCap.round + ..strokeWidth = s * 0.085; + hand.color = t.text; + canvas.drawLine(c, c.translate(0, -r * 0.62), hand); + hand.color = t.accent; + canvas.drawLine(c, c.translate(r * 0.5, r * 0.16), hand); + + // 中心轴点:外圈文字色、内圈背景色,形成中空圆点。 + canvas.drawCircle(c, s * 0.055, Paint()..color = t.text); + canvas.drawCircle(c, s * 0.022, Paint()..color = t.bg); + } + + /// 仅当主题令牌变化时重绘。 + @override + bool shouldRepaint(covariant _LogoPainter old) => old.t != t; +} diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart new file mode 100644 index 0000000..6855259 --- /dev/null +++ b/lib/ui/app_shell.dart @@ -0,0 +1,1849 @@ +// 应用外壳:组织工具栏、左右可停靠侧栏、画布舞台与状态栏的整体布局, +// 并集中处理文件、导出、快捷键与侧栏停靠等交互。 +// +// 架构位置:位于 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)), + ], + ), + ), + ), + // 收起状态:贴边轨道(悬停可展开为悬浮面板)。 + 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) { + // 响应式断点:窄于 1960 时使用紧凑布局(图标化、隐藏次要信息)。 + final bool compact = cons.maxWidth < 1960; + // 左侧工具组:品牌、文件操作、撤销重做、编辑与视图切换。 + final List 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)), + if (!compact) + Text('Sequence Diagram Studio', style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + SizedBox(width: compact ? 12 : 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), + ]; + // 右侧工具组:导出、缩放、单位、文件状态、侧栏开关与主题。 + final List right = [ + _primaryBtn(t, '导出 SVG', _exportSvg), + const SizedBox(width: 6), + _ghost(t, '导出 PNG', _exportPng), + const SizedBox(width: 6), + _zoomBox(t), + const SizedBox(width: 6), + if (compact) + _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图') + else + _ghost(t, '适应视图', c.fitView), + const SizedBox(width: 8), + _unitDropdown(t), + if (!compact) ...[ + const SizedBox(width: 8), + fileChip, + ], + const SizedBox(width: 8), + _iconBtn(t, Icons.view_sidebar_outlined, () => setState(() { + if (_leftVisible) { + _leftVisible = false; + _leftHover = false; + } else { + _leftVisible = true; + if (!_leftPinned) _leftHover = true; + } + }), tooltip: '显示 / 隐藏左侧栏'), + 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: '显示 / 隐藏右侧栏'), + ), + _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]), + ), + ), + ); + }, + ), + ); + } + + /// 视图模式分段控件:条形节拍 / 圆周节拍一键切换。 + Widget _segmented(Tokens t) { + 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: 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: 11, fontWeight: FontWeight.w600)), + style: FilledButton.styleFrom( + backgroundColor: t.accent2, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + minimumSize: const Size(0, 34), + ), + ), + ); + } + + /// 图标按钮,可附带 tooltip。 + Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip}) { + return IconButton( + onPressed: onTap, + icon: Icon(icon, size: 19, color: onTap == null ? t.dim : t.text), + tooltip: tooltip, + splashRadius: 18, + ); + } + + // ===================== 侧栏停靠状态机(钉住 / 悬浮 / 轨道) ===================== + + /// 侧栏标题栏控制按钮:切换钉住状态与隐藏侧栏。 + 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.maxLayer + 1})'), + ), + 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), + for (int i = 0; i < actions.length; i++) _actionRow(t, actions[i], i, 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)), + ], + ), + ), + ), + ); + } + + /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 + 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.maxLayer + 2}', 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.maxLayer + 1}' : '工位 ${c.project.stations.length}', + circular ? '同心圆 ${c.project.maxLayer + 1}' : '时间轴 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)), + ], + ), + ); + } +} diff --git a/lib/ui/canvas_overlays.dart b/lib/ui/canvas_overlays.dart new file mode 100644 index 0000000..0144d08 --- /dev/null +++ b/lib/ui/canvas_overlays.dart @@ -0,0 +1,899 @@ +// 画布浮层:绘制在交互画布之上的固定信息面板,对应设计稿中的 +// 标题、图例、统计、实时预览与编辑工具等元素。 +// +// 架构位置:属于纯展示层,叠加在 CanvasView 之上,通过 AppController +// 读取项目数据;所有浮层均使用 IgnorePointer 或自身交互包裹,避免 +// 遮挡画布手势。本文件通过 LayoutBuilder 依据窗口尺寸做响应式断点, +// 决定各面板是否显示。 +import 'dart:math' as math; + +import 'package:flutter/material.dart' hide Action; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../model/units.dart'; +import '../state/app_controller.dart'; +import '../theme/tokens.dart'; +import 'dialogs.dart'; + +/// 画布浮层容器:按响应式断点组合并定位各信息面板。 +class CanvasOverlays extends StatelessWidget { + /// 创建浮层容器,[controller] 为全局应用控制器。 + const CanvasOverlays({super.key, required this.controller}); + + /// 全局应用控制器,提供项目数据与编辑动作。 + final AppController controller; + + /// 控制器快捷访问器。 + AppController get c => controller; + + /// 使用 [LayoutBuilder] 获取可用尺寸,计算响应式断点后, + /// 通过 [Stack] + [Positioned] 摆放各浮层面板。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final bool circular = c.project.viewState.mode == ViewMode.circular; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final double w = constraints.maxWidth; + final double h = constraints.maxHeight; + // ---- 响应式断点:不同尺寸下显示不同的浮层组合 ---- + // 圆周视图左侧图例列:需要较宽较高的窗口。 + final bool showLeftColumn = circular && w >= 1500 && h >= 820; + // 条形视图统计卡片:中等尺寸以上显示。 + final bool showStats = !circular && w >= 900 && h >= 760; + // 编辑工具条:门槛最低,几乎始终显示。 + final bool showTools = w >= 760; + // 实时预览卡片:需要大屏才显示。 + final bool showPreview = w >= 1400 && h >= 760; + // 浮层整体使用 Stack 叠加,各面板按断点条件选择性插入。 + return Stack( + children: [ + // 顶部标题与副标题,横跨整个画布宽度,不拦截手势。 + Positioned( + left: 18, + top: 12, + right: 18, + child: IgnorePointer(child: _Title(t: t, circular: circular, project: c.project)), + ), + // 圆周视图左侧信息列:图例 + 选中卡片 + 依赖图例。 + if (showLeftColumn) + Positioned( + left: 18, + top: 70, + bottom: 12, + width: 268, + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + IgnorePointer(child: _CircularLegend(t: t, project: c.project)), + const SizedBox(height: 12), + IgnorePointer(child: _SelectedCard(t: t, c: c, circular: true)), + const SizedBox(height: 12), + IgnorePointer(child: _DepTypeLegend(t: t)), + ], + ), + ), + ), + // 条形视图左下角:节拍统计 + 编辑工具。 + if (!circular && (showStats || showTools)) + Positioned( + left: 18, + bottom: 12, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (showStats) ...[ + _StatsButton(t: t, c: c), + const SizedBox(height: 8), + ], + _EditTools(t: t, c: c), + ], + ), + ), + // 右下角实时预览:圆周视图显示条形缩略,反之亦然。 + if (showPreview) + Positioned( + right: 18, + bottom: 12, + child: IgnorePointer( + child: circular + ? _BarPreviewCard(t: t, project: c.project) + : _CircularPreviewCard(t: t, project: c.project), + ), + ), + // 圆周视图右侧浮动工具栏(添加/编辑/复制/删除/改层/对齐/帮助)。 + if (circular) + Positioned( + right: 16, + top: 120, + child: _FloatingToolbar(t: t, c: c), + ), + ], + ); + }, + ); + } +} + +/// 通用卡片容器:统一浮层的背景、圆角与边框样式。 +class _Card extends StatelessWidget { + const _Card({required this.t, required this.child, this.width, this.borderColor}); + + /// 主题令牌。 + final Tokens t; + /// 卡片内容。 + final Widget child; + /// 可选固定宽度。 + final double? width; + /// 可选边框颜色,默认使用主题分隔线色。 + final Color? borderColor; + + @override + Widget build(BuildContext context) { + return Container( + width: width, + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.panel2.withValues(alpha: 0.96), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: borderColor ?? t.line), + ), + child: child, + ); + } +} + +/// 顶部标题浮层:显示当前视图名称与双刻度/图例说明。 +class _Title extends StatelessWidget { + const _Title({required this.t, required this.circular, required this.project}); + + /// 主题令牌。 + final Tokens t; + /// 是否处于圆周视图。 + final bool circular; + /// 当前项目,用于展示循环时长等文案。 + final Project project; + + @override + Widget build(BuildContext context) { + final String title = circular + ? '圆周节拍视图(同心圆 · 12 点钟起始 · 顺时针)' + : '条形节拍视图(甘特 / 流程图 · 依赖箭头)'; + final String sub = circular + ? '同心圆环 = 动作层;箭头 = 执行顺序(绿色实线 FS 严格顺序,琥珀虚线 SS 并行重叠);1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%' + : '时间轴与相位角双刻度联动;箭头表示动作间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠);跨循环动作自动拆分并标注'; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + Text(sub, style: TextStyle(color: t.dim, fontSize: 11)), + ], + ); + } +} + +/// 圆周视图左侧图例:逐条列出动作的层号、相位区间与时长。 +class _CircularLegend extends StatelessWidget { + const _CircularLegend({required this.t, required this.project}); + + /// 主题令牌。 + final Tokens t; + /// 当前项目,用于枚举动作。 + final Project project; + + @override + Widget build(BuildContext context) { + return _Card( + t: t, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('图层 / 相位图例', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + for (int i = 0; i < project.actions.length; i++) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 15, + height: 15, + margin: const EdgeInsets.only(top: 2), + decoration: BoxDecoration( + color: Color(project.actions[i].color), + borderRadius: BorderRadius.circular(5), + ), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${i + 1}. ${project.actions[i].id} ${project.actions[i].name}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text2, fontSize: 11)), + Text( + 'L${project.actions[i].layer + 1} · ${project.actions[i].startAngle.toStringAsFixed(0)}°–${math.min(project.actions[i].endAngle, 360).toStringAsFixed(0)}° · ${tfmt(project.actions[i].durationAngle / 360 * project.cycle.durationMs, project.units)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +/// 选中动作信息卡:展示选中动作的起止/持续相位与所在层。 +class _SelectedCard extends StatelessWidget { + const _SelectedCard({required this.t, required this.c, required this.circular}); + + /// 主题令牌。 + final Tokens t; + /// 全局应用控制器。 + final AppController c; + /// 是否处于圆周视图(用于文案微调)。 + final bool circular; + + @override + Widget build(BuildContext context) { + final Action? a = c.selected; + if (a == null) { + return _Card( + t: t, + borderColor: t.accent, + child: Text('未选中动作\n点击画布或左侧列表选择', style: TextStyle(color: t.dim, fontSize: 11, height: 1.6)), + ); + } + final UnitSettings u = c.project.units; + final double cycle = c.project.cycle.durationMs; + final Station? st = c.project.stationById(a.stationId); + final String delta = tfmt(a.durationAngle / 360 * cycle, u); + return _Card( + t: t, + borderColor: t.accent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('选中动作', style: TextStyle(color: t.accent, fontSize: 10, fontWeight: FontWeight.w700, letterSpacing: 1)), + const SizedBox(height: 6), + Text('${a.id} ${a.name}', style: TextStyle(color: t.text, fontSize: 13, fontWeight: FontWeight.w700)), + const SizedBox(height: 8), + _kv(t, '起始相位', pfmt(a.startAngle, u)), + _kv(t, '结束相位', pfmt(a.endAngle, u)), + _kv(t, '持续相位', pfmt(a.durationAngle, u)), + const SizedBox(height: 4), + Text('Δ = $delta · 层 L${a.layer + 1} · ${st?.id ?? a.stationId}', + style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), + ], + ), + ); + } + + /// 渲染一行“标签 — 值”信息。 + Widget _kv(Tokens t, String k, String v) => Padding( + padding: const EdgeInsets.only(bottom: 3), + child: Row( + children: [ + Text(k, style: TextStyle(color: t.sub, fontSize: 11)), + const Spacer(), + Flexible( + child: Text(v, + textAlign: TextAlign.right, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text, fontSize: 11, fontWeight: FontWeight.w600)), + ), + ], + ), + ); +} + +/// 依赖类型图例:说明 FS/SS 及关键路径的线条样式含义。 +class _DepTypeLegend extends StatelessWidget { + const _DepTypeLegend({required this.t}); + + /// 主题令牌。 + final Tokens t; + + @override + Widget build(BuildContext context) { + Widget row(Widget sample, String label) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + children: [ + SizedBox(width: 48, child: sample), + const SizedBox(width: 8), + Expanded(child: Text(label, style: TextStyle(color: t.sub, fontSize: 10))), + ], + ), + ); + return _Card( + t: t, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('执行顺序 / 依赖类型', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + const SizedBox(height: 10), + row(_SampleLine(color: t.fs, dash: false, arrow: true), 'FS 严格顺序(完成后启动)'), + row(_SampleLine(color: t.ss, dash: true, arrow: true), 'SS 并行重叠(可提前启动)'), + row(_SampleLine(color: t.fs, dash: false, arrow: false, star: true), '关键路径(累计最长链)'), + ], + ), + ); + } +} + +/// 图例中的示例线段:可组合实线/虚线、箭头与关键路径星标。 +class _SampleLine extends StatelessWidget { + const _SampleLine({required this.color, required this.dash, required this.arrow, this.star = false}); + + /// 线条颜色。 + final Color color; + /// 是否绘制为虚线。 + final bool dash; + /// 是否绘制箭头。 + final bool arrow; + /// 是否绘制关键路径星标。 + final bool star; + + /// 用 [_SamplePainter] 绘制示例线段。 + @override + Widget build(BuildContext context) { + return SizedBox( + height: 16, + child: CustomPaint(painter: _SamplePainter(color, dash, arrow, star)), + ); + } +} + +/// 示例线段绘制器:按参数绘制实/虚线、箭头与星标。 +class _SamplePainter extends CustomPainter { + _SamplePainter(this.color, this.dash, this.arrow, this.star); + + /// 线条颜色。 + final Color color; + /// 是否绘制为虚线。 + final bool dash; + /// 是否绘制箭头。 + final bool arrow; + /// 是否绘制关键路径星标。 + final bool star; + + /// 绘制示例线段本体、箭头及可选星标。 + @override + void paint(Canvas canvas, Size size) { + final Paint p = Paint() + ..color = color + ..strokeWidth = 2.4 + ..strokeCap = StrokeCap.round; + final double y = size.height / 2; + if (dash) { + for (double x = 0; x < size.width - 10; x += 8) { + canvas.drawLine(Offset(x, y), Offset(math.min(x + 4, size.width - 10), y), p); + } + } else { + canvas.drawLine(Offset(0, y), Offset(size.width - 10, y), p); + } + if (arrow) { + final Path a = Path() + ..moveTo(size.width - 1, y) + ..lineTo(size.width - 11, y - 4.5) + ..lineTo(size.width - 11, y + 4.5) + ..close(); + canvas.drawPath(a, Paint()..color = color); + } + if (star) { + canvas.drawCircle(Offset(size.width - 8, y), 7.5, Paint()..color = const Color(0xFF4CC9F0)); + final TextPainter tp = TextPainter( + text: const TextSpan(text: '★', style: TextStyle(color: Colors.black, fontSize: 10, fontWeight: FontWeight.w700)), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset(size.width - 8 - tp.width / 2, y - tp.height / 2)); + } + } + + /// 示例线段始终重绘(开销极小)。 + @override + bool shouldRepaint(covariant _SamplePainter old) => true; +} + +/// 条形视图左下角的「节拍统计」按钮。 +/// +/// 统计内容改为**弹出窗口**展示(见 [_CycleStatsDialog]), +/// 避免固定面板长期遮挡画布。 +class _StatsButton extends StatelessWidget { + const _StatsButton({required this.t, required this.c}); + + /// 主题令牌。 + final Tokens t; + /// 全局应用控制器。 + final AppController c; + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: () => showDialog( + context: context, + builder: (BuildContext ctx) => _CycleStatsDialog(t: t, c: c), + ), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), + decoration: BoxDecoration( + color: t.panel2.withValues(alpha: 0.96), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line2), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.insights, size: 15, color: t.accent), + const SizedBox(width: 6), + Text('节拍统计', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + ], + ), + ), + ); + } +} + +/// 节拍统计弹窗:汇总循环周期、动作数、关键路径、并行度、 +/// 相位覆盖率、瓶颈工位与预估产能。 +class _CycleStatsDialog extends StatelessWidget { + const _CycleStatsDialog({required this.t, required this.c}); + + /// 主题令牌。 + final Tokens t; + /// 全局应用控制器。 + final AppController c; + + @override + Widget build(BuildContext context) { + final Project p = c.project; + final UnitSettings u = p.units; + final List acts = p.actions; + final int stations = p.stations.length; + final double perHour = p.cycle.durationMs > 0 ? 3600 / (p.cycle.durationMs / 1000) : 0; + final List> stats = >[ + ['循环周期', '${tfmt(p.cycle.durationMs, u)} / 360° / 100%'], + ['动作数量', '${acts.length}($stations 工位)'], + ['关键路径', _criticalChain()], + ['最大并行度', _maxParallel(acts)], + ['相位覆盖率', _coverage(acts)], + ['瓶颈工位', _bottleneck(p)], + ['预估产能', '${perHour.toStringAsFixed(0)} 件/小时(节拍 ${tfmt(p.cycle.durationMs, u)})'], + ]; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 460, + child: Padding( + padding: const EdgeInsets.fromLTRB(18, 16, 12, 14), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.insights, size: 18, color: t.accent), + const SizedBox(width: 8), + Text('节拍统计', style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w700)), + const Spacer(), + IconButton( + onPressed: () => Navigator.pop(context), + icon: Icon(Icons.close, size: 18, color: t.sub), + splashRadius: 16, + ), + ], + ), + Divider(height: 14, color: t.line), + for (int i = 0; i < stats.length; i++) ...[ + Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + children: [ + Text(stats[i][0], style: TextStyle(color: t.dim, fontSize: 11)), + const Spacer(), + Flexible( + child: Text(stats[i][1], + textAlign: TextAlign.right, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text2, fontSize: 11, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + if (i < stats.length - 1) Divider(height: 1, color: t.line.withValues(alpha: 0.6)), + ], + ], + ), + ), + ), + ); + } + + /// 拼接关键路径上的动作 id 链。 + String _criticalChain() { + final List ids = []; + for (final Action a in c.project.actions) { + if (c.criticalActions.contains(a.id)) ids.add(a.id); + } + if (ids.isEmpty) return '—'; + return ids.join(' → '); + } + + /// 扫描 0–360°,找出同时执行的动作数量峰值。 + String _maxParallel(List acts) { + int best = 0; + double bestAt = 0; + for (int d = 0; d <= 360; d += 5) { + int n = 0; + for (final Action a in acts) { + if (d >= a.startAngle && d <= math.min(a.endAngle, 360)) n++; + } + if (n > best) { + best = n; + bestAt = d.toDouble(); + } + } + return '$best 个动作同时执行(${bestAt.toStringAsFixed(0)}° 附近)'; + } + + /// 统计 0–360° 被动作覆盖的相位比例。 + String _coverage(List acts) { + final List cover = List.filled(360, false); + for (final Action a in acts) { + for (int d = a.startAngle.floor(); d < math.min(a.endAngle, 360).ceil(); d++) { + if (d >= 0 && d < 360) cover[d] = true; + } + } + final int filled = cover.where((bool e) => e).length; + return '${(filled / 360 * 100).toStringAsFixed(0)}%(0°–360°)'; + } + + /// 找出累计相位占用最大的工位作为瓶颈。 + String _bottleneck(Project p) { + final Map load = {}; + for (final Action a in p.actions) { + load[a.stationId] = (load[a.stationId] ?? 0) + a.durationAngle; + } + String best = '—'; + double bestV = -1; + for (final MapEntry e in load.entries) { + if (e.value > bestV) { + bestV = e.value; + best = '${e.key} ${e.value.toStringAsFixed(0)}°'; + } + } + return best; + } +} + +/// 条形视图编辑工具条:添加 / 编辑 / 复制 / 删除 / 对齐 / 帮助。 +class _EditTools extends StatelessWidget { + const _EditTools({required this.t, required this.c}); + + /// 主题令牌。 + final Tokens t; + /// 全局应用控制器。 + final AppController c; + + /// 渲染一组横向排列的编辑工具按钮。 + @override + Widget build(BuildContext context) { + return _Card( + t: t, + width: 470, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('编辑工具', style: TextStyle(color: t.sub, fontSize: 12, fontWeight: FontWeight.w600)), + const SizedBox(height: 10), + Row( + children: [ + _tool(t, Icons.add, '添加动作', t.ok, t.onAccent, () => c.addAction(startAngle: 0)), + const SizedBox(width: 8), + _tool(t, Icons.edit, '编辑', t.accent, t.onAccent, () { + final Action? a = c.selected; + if (a != null) showDialog(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)); + }), + const SizedBox(width: 8), + _tool(t, Icons.copy, '复制', t.panel, t.sub, c.duplicateSelected, border: t.line2), + const SizedBox(width: 8), + _tool(t, Icons.delete_outline, '删除', t.panel, t.sub, + () => c.selectedId != null ? c.deleteAction(c.selectedId!) : null, + border: t.line2), + const SizedBox(width: 8), + _tool(t, Icons.align_horizontal_left, '对齐', t.panel, t.sub, c.alignPhase, border: t.line2), + const SizedBox(width: 8), + _tool(t, Icons.help_outline, '帮助', t.panel, t.sub, + () => showDialog(context: context, builder: (_) => const HelpDialog()), + border: t.line2), + ], + ), + ], + ), + ); + } + + /// 渲染单个带图标与文字的工具按钮。 + Widget _tool(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: 66, + height: 56, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: border ?? bg), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 19, color: fg), + const SizedBox(height: 4), + Text(label, style: TextStyle(color: fg, fontSize: 10, fontWeight: FontWeight.w600)), + ], + ), + ), + ); + } +} + +/// 圆周视图右侧浮动工具栏:纵向排列的编辑与帮助按钮。 +class _FloatingToolbar extends StatelessWidget { + const _FloatingToolbar({required this.t, required this.c}); + + /// 主题令牌。 + final Tokens t; + /// 全局应用控制器。 + final AppController c; + + /// 渲染纵向排列的浮动工具按钮组。 + @override + Widget build(BuildContext context) { + /// 渲染单个浮动工具按钮。 + Widget item(IconData icon, String label, Color bg, Color fg, VoidCallback onTap, {Color? border}) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 46, + height: 46, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: border ?? bg), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 17, color: fg), + const SizedBox(height: 1), + Text(label, style: TextStyle(color: fg, fontSize: 10, fontWeight: FontWeight.w600)), + ], + ), + ), + ), + ); + } + + return Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: t.panel.withValues(alpha: 0.96), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: t.line2), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + item(Icons.add, '添加', t.ok, t.onAccent, () => c.addAction(startAngle: 0)), + item(Icons.edit, '编辑', t.accent, t.onAccent, () { + final Action? a = c.selected; + if (a != null) showDialog(context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)); + }), + item(Icons.copy, '复制', t.panel2, t.sub, c.duplicateSelected, border: t.line), + item(Icons.delete_outline, '删除', t.panel2, t.sub, + () => c.selectedId != null ? c.deleteAction(c.selectedId!) : null, border: t.line), + item(Icons.keyboard_arrow_up, '层+', t.panel2, t.sub, + () => c.selectedId != null ? c.changeLayer(c.selectedId!, 1) : null, border: t.line), + item(Icons.keyboard_arrow_down, '层−', t.panel2, t.sub, + () => c.selectedId != null ? c.changeLayer(c.selectedId!, -1) : null, border: t.line), + item(Icons.align_horizontal_left, '对齐', t.panel2, t.sub, c.alignPhase, border: t.line), + item(Icons.help_outline, '帮助', t.panel2, t.sub, + () => showDialog(context: context, builder: (_) => const HelpDialog()), border: t.line), + ], + ), + ); + } +} + +/// 条形节拍缩略预览卡(在圆周视图右下角显示)。 +class _BarPreviewCard extends StatelessWidget { + const _BarPreviewCard({required this.t, required this.project}); + + /// 主题令牌。 + final Tokens t; + /// 当前项目。 + final Project project; + + /// 渲染条形缩略预览。 + @override + Widget build(BuildContext context) { + return _Card( + t: t, + width: 320, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('条形节拍预览(实时联动)', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + const SizedBox(height: 10), + SizedBox( + height: project.actions.length * 22.0 + 18, + child: CustomPaint(painter: _MiniBarPainter(project, t)), + ), + ], + ), + ); + } +} + +/// 条形缩略预览绘制器:按相位比例绘制各动作的横向色条。 +class _MiniBarPainter extends CustomPainter { + _MiniBarPainter(this.project, this.t); + + /// 当前项目。 + final Project project; + /// 主题令牌。 + final Tokens t; + + /// 逐行绘制动作色条、跨圈尾段与底部刻度。 + @override + void paint(Canvas canvas, Size size) { + final double w = size.width - 4; + final double rh = 19; + for (int i = 0; i < project.actions.length; i++) { + final Action a = project.actions[i]; + final double y = i * (rh + 3); + final double x1 = 2 + a.startAngle / 360 * w; + final double x2 = 2 + math.min(a.endAngle, 360) / 360 * w; + final RRect r = RRect.fromRectAndRadius( + Rect.fromLTWH(x1, y, math.max(x2 - x1, 2), rh - 4), + const Radius.circular(3), + ); + canvas.drawRRect(r, Paint()..color = Color(a.color).withValues(alpha: 0.9)); + if (a.wrap) { + canvas.drawRRect( + RRect.fromRectAndRadius(Rect.fromLTWH(2, y, (a.endAngle - 360) / 360 * w, rh - 4), const Radius.circular(3)), + Paint()..color = Color(a.color).withValues(alpha: t.tailOp), + ); + } + } + final double baseY = project.actions.length * (rh + 3) + 4; + canvas.drawLine(Offset(2, baseY), Offset(size.width - 2, baseY), Paint()..color = t.line2..strokeWidth = 1); + final TextPainter tp = TextPainter( + text: TextSpan(text: '0.0 ${timeUnitLabel(project.units.timeUnit)}', style: TextStyle(color: t.dim, fontSize: 10)), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset(2, baseY + 4)); + final TextPainter tp2 = TextPainter( + text: TextSpan(text: tfmt(project.cycle.durationMs, project.units), style: TextStyle(color: t.dim, fontSize: 10)), + textDirection: TextDirection.ltr, + )..layout(); + tp2.paint(canvas, Offset(size.width - 2 - tp2.width, baseY + 4)); + } + + /// 预览始终重绘(数据实时联动)。 + @override + bool shouldRepaint(covariant _MiniBarPainter old) => true; +} + +/// 圆周节拍缩略预览卡(在条形视图右下角显示)。 +class _CircularPreviewCard extends StatelessWidget { + const _CircularPreviewCard({required this.t, required this.project}); + + /// 主题令牌。 + final Tokens t; + /// 当前项目。 + final Project project; + + /// 渲染圆周缩略预览。 + @override + Widget build(BuildContext context) { + return _Card( + t: t, + width: 330, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('圆周节拍预览(实时联动)', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + SizedBox( + height: 250, + child: CustomPaint(painter: _MiniCircularPainter(project, t)), + ), + Text('12 点钟起始 · 顺时针 · 每层一环', style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ); + } +} + +/// 圆周缩略预览绘制器:每层一环,绘制同心圆与动作圆弧。 +class _MiniCircularPainter extends CustomPainter { + _MiniCircularPainter(this.project, this.t); + + /// 当前项目。 + final Project project; + /// 主题令牌。 + final Tokens t; + + /// 绘制同心圆环、各动作圆弧、12 点钟箭头与“360°”标注。 + @override + void paint(Canvas canvas, Size size) { + final Offset c = Offset(size.width / 2, size.height / 2); + final int n = project.actions.length; + final double r0 = 26; + final double pitch = n <= 1 ? 18 : math.min(20, (size.height / 2 - 30 - r0) / (n - 1)); + const double pw = 9; + canvas.drawCircle(c, r0 + (n - 1) * pitch + pw + 12, Paint()..color = t.dial); + for (int i = 0; i < n; i++) { + final Action a = project.actions[i]; + final double r = r0 + i * pitch; + canvas.drawCircle( + c, + r, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = pw + ..color = i.isEven ? t.ringA : t.ringB, + ); + for (final List s in splitArcs(a.startAngle, a.endAngle)) { + canvas.drawPath( + arcPath(c, r, s[0], s[1]), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = pw + ..strokeCap = a.wrap ? StrokeCap.butt : StrokeCap.round + ..color = Color(a.color).withValues(alpha: 0.95), + ); + } + } + final double tip = r0 + (n - 1) * pitch + pw + 12; + final Path arrow = Path() + ..moveTo(c.dx, c.dy - tip - 10) + ..lineTo(c.dx - 7, c.dy - tip - 22) + ..lineTo(c.dx + 7, c.dy - tip - 22) + ..close(); + canvas.drawPath(arrow, Paint()..color = t.accent); + final TextPainter tp = TextPainter( + text: TextSpan(text: '360°', style: TextStyle(color: t.sub, fontSize: 11, fontWeight: FontWeight.w600)), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset(c.dx - tp.width / 2, c.dy - 8)); + } + + /// 预览始终重绘(数据实时联动)。 + @override + bool shouldRepaint(covariant _MiniCircularPainter old) => true; +} diff --git a/lib/ui/canvas_view.dart b/lib/ui/canvas_view.dart new file mode 100644 index 0000000..ff9e338 --- /dev/null +++ b/lib/ui/canvas_view.dart @@ -0,0 +1,569 @@ +// 画布交互视图:承载条形 / 圆周两种节拍视图的绘制与全部手势操作。 +// +// 架构位置:位于 UI 层核心,向下调用布局(BarLayout / CircularLayout) +// 与渲染器(BarPainter / CircularPainter),向上通过 AppController 修改 +// 项目状态。本文件负责: +// · 屏幕坐标 → 逻辑坐标的变换(考虑平移与缩放); +// · 点选、双击新建、拖拽移动相位、拖拽端点改持续角、Shift 拖拽改层; +// · 空白区域拖拽平移、Ctrl + 滚轮缩放; +// · 右键上下文菜单。 +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart' hide Action; +import 'package:flutter/services.dart'; + +import '../layout/layout.dart'; +import '../model/models.dart'; +import '../render/bar_painter.dart'; +import '../render/circular_painter.dart'; +import '../state/app_controller.dart'; +import '../theme/tokens.dart'; +import 'dialogs.dart'; + +/// 当前拖拽行为类型:无操作 / 平移相位 / 拖右端改时长 / 拖左端改起始。 +enum _DragMode { none, move, resize, resizeStart } + +/// 画布视图组件:根据视图模式渲染图形并处理所有画布手势。 +class CanvasView extends StatefulWidget { + /// 创建画布视图,[controller] 为全局应用控制器。 + const CanvasView({super.key, required this.controller}); + + /// 全局应用控制器,提供项目数据与编辑动作。 + final AppController controller; + + /// 创建画布视图对应的状态对象。 + @override + State createState() => _CanvasViewState(); +} + +/// 画布视图状态:维护一次拖拽过程中的起始快照与拖拽模式。 +class _CanvasViewState extends State { + // ---- 拖拽会话状态:在一次手势内记录起始值,用于计算增量 ---- + /// 当前拖拽模式(平移相位或调整持续角)。 + _DragMode _mode = _DragMode.none; + + /// 当前正在拖拽的动作;为空表示拖拽空白区域(执行画布平移)。 + Action? _dragAction; + + /// 手势按下时的逻辑坐标,作为位移计算的参考点。 + Offset _startPointer = Offset.zero; + + /// 动作在按下时的起始相位角。 + double _startAngle = 0; + + /// 动作在按下时的持续角。 + double _startDuration = 0; + + /// 圆周视图中按下时指针相对圆心的角度,用于计算旋转增量。 + double _startAnglePointer = 0; + + /// 正在拖拽的相位分区下标(-1 表示未在拖拽分区)。 + int _zoneIndex = -1; + + /// 拖拽的是分区的起始边界(true)还是结束边界(false)。 + bool _zoneIsStart = false; + + /// 拖拽分区边界或动作端点时的参考角(用于绘制虚线坐标参考);否则为 null。 + double? _zoneGuideAngle; + + /// 当前鼠标指针样式(靠近可拖拽端点时显示左右箭头)。 + MouseCursor _cursor = SystemMouseCursors.basic; + + /// 控制器快捷访问器。 + AppController get c => widget.controller; + + /// 在条形图顶部的相位分区带上命中一条边界。 + /// + /// 返回命中的 `(分区下标, 是否起始边界)`;未命中返回 null。 + /// 仅当指针落在分区带高度范围内、且距某条边界 8px 以内时命中。 + (int, bool)? _hitZoneBoundary(Offset p, BarLayout layout) { + if (p.dy < BarPainter.phaseBandTop - 6 || p.dy > BarPainter.phaseBandTop + 40) return null; + final List zones = c.project.phaseZones; + int best = -1; + bool bestStart = false; + double bestDist = 9; + for (int i = 0; i < zones.length; i++) { + final double xs = layout.xFor(zones[i].startAngle); + final double xe = layout.xFor(zones[i].endAngle); + final double ds = (p.dx - xs).abs(); + final double de = (p.dx - xe).abs(); + if (ds < bestDist) { + bestDist = ds; + best = i; + bestStart = true; + } + if (de < bestDist) { + bestDist = de; + best = i; + bestStart = false; + } + } + if (best < 0) return null; + return (best, bestStart); + } + + /// 命中相位分区带内的某个分区(返回下标;未命中返回 -1)。 + int _hitZoneAt(Offset p, BarLayout layout) { + if (p.dy < BarPainter.phaseBandTop - 6 || p.dy > BarPainter.phaseBandTop + 40) return -1; + final double angle = (p.dx - layout.plotLeft) / layout.span * 360; + for (int i = 0; i < c.project.phaseZones.length; i++) { + if (c.project.phaseZones[i].contains(angle)) return i; + } + return -1; + } + + /// 更新鼠标指针样式:靠近分区边界或动作端点时显示左右拖拽箭头。 + void _updateCursor(Offset local, Size size) { + final Offset p = _toLogical(local, size); + MouseCursor next = SystemMouseCursors.basic; + if (c.project.viewState.mode == ViewMode.bar) { + final BarLayout layout = BarLayout(c.project, size); + if (_hitZoneBoundary(p, layout) != null) { + next = SystemMouseCursors.resizeLeftRight; + } else { + final Action? hit = layout.hitTest(p); + if (hit != null) { + final Rect r = layout.rectFor(hit); + if ((p.dx - r.right).abs() <= 6 || (p.dx - r.left).abs() <= 6) { + next = SystemMouseCursors.resizeLeftRight; + } + } + } + } + if (next != _cursor) setState(() => _cursor = next); + } + + /// 动作端点弱吸附:贴合到整 5°、分区边界或其它动作端点(容差 2.5°)。 + double _snapActionAngle(double raw, String excludeId) { + const double tol = 2.5; + final List cands = [0, 360]; + for (int d = 0; d <= 360; d += 5) { + cands.add(d.toDouble()); + } + for (final Action a in c.project.actions) { + if (a.id == excludeId) continue; + cands.add(a.startAngle); + cands.add(a.endAngle); + } + for (final PhaseZone z in c.project.phaseZones) { + cands.add(z.startAngle); + cands.add(z.endAngle); + } + double best = raw; + double bestD = tol; + for (final double cand in cands) { + final double d = (cand - raw).abs(); + if (d < bestD) { + bestD = d; + best = cand; + } + } + return best; + } + + /// 弱吸附:把 [raw] 贴合到最近的整 5°、动作端点或其它分区边界(容差 2.5°)。 + double _snapZoneAngle(double raw, int zoneIndex, bool isStart) { + const double tol = 2.5; + final List cands = [0, 360, 400]; + for (int d = 0; d <= 400; d += 5) { + cands.add(d.toDouble()); + } + for (final Action a in c.project.actions) { + cands.add(a.startAngle); + cands.add(a.endAngle); + } + for (int i = 0; i < c.project.phaseZones.length; i++) { + if (i == zoneIndex) continue; + cands.add(c.project.phaseZones[i].startAngle); + cands.add(c.project.phaseZones[i].endAngle); + } + double best = raw; + double bestD = tol; + for (final double cand in cands) { + final double d = (raw - cand).abs(); + if (d < bestD) { + bestD = d; + best = cand; + } + } + return best.clamp(0, 400); + } + + /// 双击分区带:弹出对话框重命名该分区。 + Future _renameZone(int index) async { + final PhaseZone z = c.project.phaseZones[index]; + final TextEditingController ctrl = TextEditingController(text: z.name); + final String? name = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('重命名相位分区'), + content: TextField( + controller: ctrl, + autofocus: true, + decoration: const InputDecoration(labelText: '分区名称'), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')), + FilledButton(onPressed: () => Navigator.pop(ctx, ctrl.text.trim()), child: const Text('确定')), + ], + ), + ); + ctrl.dispose(); + if (name == null || name.isEmpty) return; + final List zones = List.of(c.project.phaseZones)..[index] = z.copyWith(name: name); + c.setPhaseZones(zones, status: '分区已重命名为「$name」'); + } + + // ===================== 坐标变换 ===================== + + /// 将画布局部坐标 [local] 转换为项目逻辑坐标: + /// 先减去平移量,再除以缩放系数。 + Offset _toLogical(Offset local, Size size) { + final double z = c.project.viewState.zoom; + return Offset( + (local.dx - c.project.viewState.panX) / z, + (local.dy - c.project.viewState.panY) / z, + ); + } + + // ===================== 手势处理 ===================== + + /// 单击:命中最上层动作则选中,否则清空选中。 + void _onTapDown(TapDownDetails d, Size size) { + final Offset p = _toLogical(d.localPosition, size); + final Action? hit = c.project.viewState.mode == ViewMode.bar + ? BarLayout(c.project, size).hitTest(p) + : CircularLayout(c.project, size).hitTest(p); + // Ctrl(或 Shift)点击:切换该动作的选中状态,实现多选。 + final bool toggle = HardwareKeyboard.instance.isControlPressed || + HardwareKeyboard.instance.isShiftPressed; + c.select(hit?.id, toggle: toggle && hit != null); + } + + /// 双击空白处:按点击位置换算出的相位角新建动作; + /// 若双击在已有动作上则不处理。 + void _onDoubleTapDown(TapDownDetails d, Size size) { + final Offset p = _toLogical(d.localPosition, size); + // 双击相位分区带:重命名该分区。 + if (c.project.viewState.mode == ViewMode.bar) { + final int zi = _hitZoneAt(p, BarLayout(c.project, size)); + if (zi >= 0) { + _renameZone(zi); + return; + } + } + final Action? hit = c.project.viewState.mode == ViewMode.bar + ? BarLayout(c.project, size).hitTest(p) + : CircularLayout(c.project, size).hitTest(p); + if (hit != null) return; + double angle = 0; + if (c.project.viewState.mode == ViewMode.bar) { + angle = BarLayout(c.project, size).angleAt(p.dx); + } else { + final CircularLayout cl = CircularLayout(c.project, size); + angle = angleOf(cl.center, p); + } + c.addAction(startAngle: angle); + } + + /// 拖拽开始:判断落点是否命中动作。 + /// 条形视图下靠近动作右端 8px 视为“调整持续角”,否则为“平移相位”; + /// 圆周视图下统一为“平移相位”。未命中则进入画布平移模式。 + void _onPanStart(DragStartDetails d, Size size) { + final Offset p = _toLogical(d.localPosition, size); + if (c.project.viewState.mode == ViewMode.bar) { + final BarLayout layout = BarLayout(c.project, size); + // 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。 + final (int, bool)? zone = _hitZoneBoundary(p, layout); + if (zone != null) { + _zoneIndex = zone.$1; + _zoneIsStart = zone.$2; + _mode = _DragMode.none; + _dragAction = null; + _startPointer = p; + return; + } + final Action? hit = layout.hitTest(p); + if (hit != null) { + final Rect r = layout.rectFor(hit); + final bool nearRight = (p.dx - r.right).abs() <= 8; + final bool nearLeft = (p.dx - r.left).abs() <= 8; + _mode = nearRight + ? _DragMode.resize + : (nearLeft ? _DragMode.resizeStart : _DragMode.move); + _dragAction = hit; + _startPointer = p; + _startAngle = hit.startAngle; + _startDuration = hit.durationAngle; + c.select(hit.id); + return; + } + } else { + final CircularLayout layout = CircularLayout(c.project, size); + final Action? hit = layout.hitTest(p); + if (hit != null) { + final double a = angleOf(layout.center, p); + _mode = _DragMode.move; + _dragAction = hit; + _startPointer = p; + _startAngle = hit.startAngle; + _startDuration = hit.durationAngle; + _startAnglePointer = a; + c.select(hit.id); + return; + } + } + _mode = _DragMode.none; + _dragAction = null; + } + + /// 拖拽更新:未命中动作时平移画布;命中动作时根据模式与修饰键 + /// 计算增量并写回控制器(调整持续角 / 改层 / 平移相位)。 + void _onPanUpdate(DragUpdateDetails d, Size size) { + final Offset p = _toLogical(d.localPosition, size); + // 拖拽相位分区边界:按横坐标换算角度(结束角允许超过 360° 表示跨圈), + // 并做「弱吸附」——靠近整 5°、动作端点或其它分区边界时自动贴合。 + if (_zoneIndex >= 0) { + final BarLayout layout = BarLayout(c.project, size); + final double raw = ((p.dx - layout.plotLeft) / layout.span * 360).clamp(0, 400); + final double angle = _snapZoneAngle(raw, _zoneIndex, _zoneIsStart); + _zoneGuideAngle = angle; + c.movePhaseZoneBoundary(_zoneIndex, _zoneIsStart, angle); + return; + } + // 未命中动作:整幅画布跟随指针平移。 + if (_dragAction == null) { + c.panBy(d.delta); + return; + } + final bool shift = HardwareKeyboard.instance.isShiftPressed; + if (c.project.viewState.mode == ViewMode.bar) { + // 条形视图:水平位移按时间轴跨度换算为相位角。 + final BarLayout layout = BarLayout(c.project, size); + final double dx = p.dx - _startPointer.dx; + final double dy = p.dy - _startPointer.dy; + if (_mode == _DragMode.resize) { + // 拖右端:固定起始角,改结束角(弱吸附 + 虚线参考)。 + final double rawEnd = _startAngle + _startDuration + dx / layout.span * 360; + final double end = _snapActionAngle(rawEnd, _dragAction!.id).clamp(_startAngle + 5, 360); + _zoneGuideAngle = end; + c.setActionDuration(_dragAction!.id, end - _startAngle); + } else if (_mode == _DragMode.resizeStart) { + // 拖左端:固定结束角,改起始角(弱吸附 + 虚线参考)。 + final double rawStart = _startAngle + dx / layout.span * 360; + final double fixedEnd = _startAngle + _startDuration; + final double ns = _snapActionAngle(rawStart, _dragAction!.id).clamp(0, fixedEnd - 5); + _zoneGuideAngle = ns; + c.updateAction( + _dragAction!.id, + (Action x) => x.copyWith(startAngle: ns, durationAngle: fixedEnd - ns), + status: '调整起始角', + ); + } else if (shift) { + // Shift + 垂直拖拽:按每 26px 一层调整层号,并限制在 0–63。 + final int deltaLayer = (dy / 26).round(); + c.setLayer(_dragAction!.id, (_dragAction!.layer - deltaLayer).clamp(0, 63)); + } else if (dy.abs() > dx.abs() + 6 && dy.abs() > 12) { + // 以垂直为主:上下拖拽调整行序,动作可自由换行(不再被相位锁死)。 + final int target = ((p.dy - BarLayout.topPad) / layout.pitch).round().clamp(0, layout.ordered.length - 1); + c.moveActionRow(_dragAction!.id, target); + } else { + c.setActionStart(_dragAction!.id, _startAngle + dx / layout.span * 360); + } + } else { + // 圆周视图:用指针相对圆心的角度差作为旋转增量,并归一化到 ±180°。 + final CircularLayout layout = CircularLayout(c.project, size); + final double a = angleOf(layout.center, p); + double delta = a - _startAnglePointer; + if (delta > 180) delta -= 360; + if (delta < -180) delta += 360; + if (_mode == _DragMode.resize) { + c.setActionDuration(_dragAction!.id, _startDuration + delta); + } else if (shift) { + // Shift + 径向拖拽:按层间距 pitch 换算层号增量。 + final double dr = (p - layout.center).distance - (_startPointer - layout.center).distance; + final int dl = (dr / layout.pitch).round(); + c.setLayer(_dragAction!.id, (_dragAction!.layer + dl).clamp(0, 63)); + } else { + c.setActionStart(_dragAction!.id, _startAngle + delta); + } + } + } + + /// 拖拽结束:重置拖拽会话状态。 + void _onPanEnd(DragEndDetails d) { + _mode = _DragMode.none; + _dragAction = null; + _zoneIndex = -1; + _zoneGuideAngle = null; + } + + /// 滚轮:按住 Ctrl 时以指针方向缩放,否则按滚轮增量平移画布。 + void _onScroll(PointerScrollEvent e, Size size) { + if (HardwareKeyboard.instance.isControlPressed) { + // 以光标位置为锚点缩放,避免“越缩越偏”。 + c.zoomAt(e.scrollDelta.dy > 0 ? 0.92 : 1.08, e.localPosition); + } else { + c.panBy(Offset(-e.scrollDelta.dx, -e.scrollDelta.dy)); + } + } + + // ===================== 右键上下文菜单 ===================== + + /// 在命中动作处弹出右键菜单,提供添加依赖、改层、复制、删除等操作; + /// 若右键落在相位分区带上,则弹出分区的增删改菜单。 + Future _contextMenu(Offset global, Size size) async { + final Offset local = _toLogical(global, size); + if (c.project.viewState.mode == ViewMode.bar) { + final int zi = _hitZoneAt(local, BarLayout(c.project, size)); + if (zi >= 0) { + await _zoneMenu(global, zi); + return; + } + } + final Action? hit = c.project.viewState.mode == ViewMode.bar + ? BarLayout(c.project, size).hitTest(local) + : CircularLayout(c.project, size).hitTest(local); + if (hit == null) return; + c.select(hit.id); + final RenderBox box = context.findRenderObject()! as RenderBox; + final Offset pos = box.globalToLocal(global); + final String? result = await showMenu( + context: context, + position: RelativeRect.fromLTRB(pos.dx, pos.dy, pos.dx, pos.dy), + items: const >[ + PopupMenuItem(value: 'add-dep', child: Text('添加依赖…')), + PopupMenuItem(value: 'layer-up', child: Text('上移一层')), + PopupMenuItem(value: 'layer-down', child: Text('下移一层')), + PopupMenuItem(value: 'duplicate', child: Text('复制动作')), + PopupMenuItem(value: 'delete', child: Text('删除动作')), + ], + ); + if (result == null) return; + // 根据菜单选项分派到对应控制器动作。 + switch (result) { + case 'layer-up': + c.changeLayer(hit.id, 1); + break; + case 'layer-down': + c.changeLayer(hit.id, -1); + break; + case 'duplicate': + c.duplicateSelected(); + break; + case 'delete': + c.deleteAction(hit.id); + break; + case 'add-dep': + break; + } + } + + /// 相位分区右键菜单:重命名 / 插入 / 删除,实现任意增减。 + Future _zoneMenu(Offset global, int index) async { + final RenderBox box = context.findRenderObject()! as RenderBox; + final Offset pos = box.globalToLocal(global); + final String? result = await showMenu( + context: context, + position: RelativeRect.fromLTRB(pos.dx, pos.dy, pos.dx, pos.dy), + items: const >[ + PopupMenuItem(value: 'rename', child: Text('重命名分区')), + PopupMenuItem(value: 'insert', child: Text('在其后插入分区')), + PopupMenuItem(value: 'delete', child: Text('删除此分区')), + PopupMenuItem(value: 'edit-all', child: Text('编辑全部…')), + ], + ); + if (result == null) return; + if (result == 'rename') { + await _renameZone(index); + return; + } + if (result == 'edit-all') { + if (!mounted) return; + await showDialog(context: context, builder: (_) => PhaseZoneDialog(controller: c)); + return; + } + final List zones = List.of(c.project.phaseZones); + if (result == 'insert') { + final PhaseZone z = zones[index]; + final double mid = ((z.startAngle + z.endAngle) / 2).clamp(0, 360); + zones.insert(index + 1, PhaseZone(name: '分区 ${zones.length + 1}', startAngle: mid, endAngle: (mid + 30).clamp(0, 400))); + c.setPhaseZones(zones, status: '已插入分区'); + } else if (result == 'delete') { + zones.removeAt(index); + c.setPhaseZones(zones, status: '已删除分区'); + } + } + + // ===================== 构建与视图变换 ===================== + + /// 构建画布:用 [LayoutBuilder] 获取可用尺寸,[Listener] 处理滚轮, + /// [GestureDetector] 处理点选/拖拽/右键,[Transform] 应用平移与缩放, + /// 最后由对应的 Painter 完成绘制。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return LayoutBuilder( + builder: (BuildContext ctx, BoxConstraints constraints) { + final Size size = Size(constraints.maxWidth, constraints.maxHeight); + // 回填视口尺寸,供控制器计算「适应窗口」与居中缩放锚点。 + c.setViewport(size); + // 鼠标指针样式:靠近分区边界或动作端点时变为左右拖拽箭头。 + return MouseRegion( + cursor: _cursor, + onHover: (PointerHoverEvent e) => _updateCursor(e.localPosition, size), + onExit: (_) { + if (_cursor != SystemMouseCursors.basic) { + setState(() => _cursor = SystemMouseCursors.basic); + } + }, + // 指针信号监听:仅处理滚轮事件(缩放 / 平移)。 + child: Listener( + onPointerSignal: (PointerSignalEvent e) { + if (e is PointerScrollEvent) _onScroll(e, size); + }, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (TapDownDetails d) => _onTapDown(d, size), + onDoubleTapDown: (TapDownDetails d) => _onDoubleTapDown(d, size), + onPanStart: (DragStartDetails d) => _onPanStart(d, size), + onPanUpdate: (DragUpdateDetails d) => _onPanUpdate(d, size), + onPanEnd: _onPanEnd, + onSecondaryTapDown: (TapDownDetails d) => _contextMenu(d.globalPosition, size), + // 裁剪到画布范围内,避免缩放/平移后内容溢出。 + child: ClipRect( + // 应用视图变换矩阵:先平移(panX/panY),再整体缩放(zoom)。 + child: Transform( + transform: Matrix4.identity() + ..setEntry(0, 3, c.project.viewState.panX) + ..setEntry(1, 3, c.project.viewState.panY) + ..setEntry(0, 0, c.project.viewState.zoom) + ..setEntry(1, 1, c.project.viewState.zoom) + ..setEntry(2, 2, c.project.viewState.zoom), + child: CustomPaint( + size: size, + painter: c.project.viewState.mode == ViewMode.bar + ? BarPainter( + project: c.project, + tokens: t, + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + selectedIds: c.selectedIds.toSet(), + guideAngle: _zoneGuideAngle, + ) + : CircularPainter( + project: c.project, + tokens: t, + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + selectedIds: c.selectedIds.toSet(), + ), + ), + ), + ), + ), + ), + ); + }, + ); + } +} diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart new file mode 100644 index 0000000..7604715 --- /dev/null +++ b/lib/ui/dialogs.dart @@ -0,0 +1,1355 @@ +// 对话框集合:集中定义应用内的所有弹窗流程。 +// +// 架构位置:属于 UI 层,向上被 AppShell / CanvasOverlays 等调用, +// 向下通过 AppController 读写项目状态、通过 dart:io 访问文件系统。 +// 包含: +// · 通用消息提示(showMessage); +// · .seq.json 文件浏览/保存对话框(FileBrowserDialog / pickFile); +// · 动作编辑、依赖编辑、工艺参数设置、帮助中心等业务对话框。 +import 'dart:io'; + +import 'package:flutter/material.dart' hide Action; + +import '../model/models.dart'; +import '../model/units.dart'; +import '../state/app_controller.dart'; +import '../theme/tokens.dart'; + +// ===================== 通用提示 ===================== + +/// 弹出一个仅含“确定”按钮的简单消息对话框。 +Future showMessage(BuildContext context, String title, String message) { + return showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: Text(title), + content: Text(message), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('确定')), + ], + ), + ); +} + +// ===================== 文件浏览 / 保存对话框 ===================== + +/// 文件浏览对话框:用于打开或另存为 `.seq.json` 文件。 +/// [saveMode] 为 true 时进入保存流程,否则为打开流程。 +class FileBrowserDialog extends StatefulWidget { + const FileBrowserDialog({super.key, required this.saveMode, this.initialPath}); + + /// 是否为保存模式(true = 另存为,false = 打开)。 + final bool saveMode; + /// 初始目录或初始文件路径。 + final String? initialPath; + + /// 创建文件浏览对话框对应的状态对象。 + @override + State createState() => _FileBrowserDialogState(); +} + +/// 文件浏览对话框状态:维护当前目录、文件名输入与目录项列表。 +class _FileBrowserDialogState extends State { + /// 当前浏览的目录。 + late Directory _dir; + /// 文件名输入控制器。 + late TextEditingController _name; + /// 当前目录下的条目(子目录 + .json 文件)。 + List _entries = []; + /// 读取目录失败时的错误信息。 + String? _error; + + /// 解析初始路径、初始化文件名,并首次刷新目录列表。 + @override + void initState() { + super.initState(); + String start = widget.initialPath ?? ''; + if (start.isEmpty) { + start = Platform.environment['USERPROFILE'] ?? Directory.current.path; + } + if (File(start).existsSync()) { + start = File(start).parent.path; + } + _dir = Directory(start); + if (!_dir.existsSync()) _dir = Directory.current; + final String base = widget.initialPath != null && widget.initialPath!.isNotEmpty + ? widget.initialPath!.split(RegExp(r'[\\/]')).last + : '节拍方案.seq.json'; + _name = TextEditingController(text: base); + _refresh(); + } + + /// 重新读取当前目录:仅保留子目录与 .json 文件, + /// 目录排在文件之前并按名称不区分大小写排序。 + void _refresh() { + try { + final List all = _dir.listSync(); + _entries = all.where((FileSystemEntity e) { + if (e is Directory) return true; + return e.path.toLowerCase().endsWith('.json'); + }).toList() + ..sort((FileSystemEntity a, FileSystemEntity b) { + final bool ad = a is Directory; + final bool bd = b is Directory; + if (ad != bd) return ad ? -1 : 1; + return a.path.toLowerCase().compareTo(b.path.toLowerCase()); + }); + _error = null; + } catch (e) { + _error = '无法读取目录:$e'; + _entries = []; + } + setState(() {}); + } + + /// 枚举 Windows 盘符(A–Z)中当前存在的根目录。 + List _drives() { + final List out = []; + for (int i = 65; i <= 90; i++) { + final String p = '${String.fromCharCode(i)}:\\'; + try { + if (Directory(p).existsSync()) out.add(p); + } catch (_) {} + } + return out; + } + + /// 渲染文件浏览器:路径栏、盘符快捷入口、条目列表与文件名输入。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final List drives = _drives(); + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 760, + height: 560, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.saveMode ? '另存为 .seq.json' : '打开 .seq.json', + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: t.line2), + ), + child: Text(_dir.path, style: TextStyle(color: t.sub, fontSize: 11)), + ), + ), + const SizedBox(width: 8), + OutlinedButton( + onPressed: () { + final Directory p = _dir.parent; + if (p.path != _dir.path) { + _dir = p; + _refresh(); + } + }, + child: const Text('上一级'), + ), + ], + ), + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: drives.map((String d) { + return Padding( + padding: const EdgeInsets.only(right: 6), + child: ActionChip( + label: Text(d), + onPressed: () { + _dir = Directory(d); + _refresh(); + }, + ), + ); + }).toList(), + ), + ), + const Divider(), + Expanded( + child: _error != null + ? Center(child: Text(_error!, style: TextStyle(color: t.danger))) + : ListView.builder( + itemCount: _entries.length, + itemBuilder: (BuildContext ctx, int i) { + final FileSystemEntity e = _entries[i]; + final bool isDir = e is Directory; + final String name = e.path.split(RegExp(r'[\\/]')).last; + return ListTile( + dense: true, + leading: Icon(isDir ? Icons.folder : Icons.description, + color: isDir ? t.accent : t.sub, size: 20), + title: Text(name, style: TextStyle(color: t.text, fontSize: 11)), + onTap: () { + if (isDir) { + _dir = Directory(e.path); + _refresh(); + } else { + setState(() => _name.text = name); + } + }, + ); + }, + ), + ), + const Divider(), + Row( + children: [ + Text('文件名', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: _name, + style: TextStyle(color: t.text, fontSize: 11), + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: t.panel2, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + const SizedBox(width: 8), + FilledButton( + onPressed: () { + // 规范化文件名:空名忽略,缺少 .json 后缀时补全为 .seq.json。 + String name = _name.text.trim(); + if (name.isEmpty) return; + if (!name.toLowerCase().endsWith('.json')) name = '$name.seq.json'; + final String sep = Platform.pathSeparator; + final String path = '${_dir.path}$sep$name'; + Navigator.pop(context, path); + }, + child: Text(widget.saveMode ? '保存' : '打开'), + ), + ], + ), + ], + ), + ), + ), + ); + } +} + +/// 打开文件选择对话框并返回所选路径;[save] 决定保存或打开模式。 +Future pickFile(BuildContext context, {required bool save, String? initialPath}) { + return showDialog( + context: context, + builder: (BuildContext ctx) => FileBrowserDialog(saveMode: save, initialPath: initialPath), + ); +} + +// ===================== 动作编辑对话框 ===================== + +/// 动作编辑对话框:修改选中动作的名称、驱动、工位、相位与颜色。 +class ActionEditorDialog extends StatefulWidget { + const ActionEditorDialog({super.key, required this.controller, required this.action}); + + /// 全局应用控制器。 + final AppController controller; + /// 待编辑的动作。 + final Action action; + + /// 创建动作编辑对话框对应的状态对象。 + @override + State createState() => _ActionEditorDialogState(); +} + +/// 动作编辑对话框状态:用文本控制器暂存各字段,确认时一次性写回。 +class _ActionEditorDialogState extends State { + /// 动作名称输入。 + late TextEditingController _name; + /// 驱动 / 执行器输入。 + late TextEditingController _driver; + /// 起始相位输入。 + late TextEditingController _start; + /// 持续相位输入。 + late TextEditingController _duration; + /// 起始时刻输入(按当前时间单位,与角度双向换算)。 + late TextEditingController _startTime; + /// 持续时长输入(按当前时间单位)。 + late TextEditingController _durationTime; + /// 防止角度↔时间联动时递归触发。 + bool _syncing = false; + /// 当前选择的工位 id。 + late String _station; + /// 当前选择的颜色值。 + late int _color; + + /// 用待编辑动作的现有值初始化各输入控件,并建立角度↔时间联动。 + @override + void initState() { + super.initState(); + final Action a = widget.action; + final UnitSettings u = widget.controller.project.units; + final double cycle = widget.controller.project.cycle.durationMs; + _name = TextEditingController(text: a.name); + _driver = TextEditingController(text: a.driver); + _start = TextEditingController(text: a.startAngle.toStringAsFixed(1)); + _duration = TextEditingController(text: a.durationAngle.toStringAsFixed(1)); + _startTime = TextEditingController(text: _fmtMs(a.startAngle / 360 * cycle, u)); + _durationTime = TextEditingController(text: _fmtMs(a.durationAngle / 360 * cycle, u)); + _station = a.stationId; + _color = a.color; + + // 角度 → 时间 + _start.addListener(() { + if (_syncing) return; + final double? v = double.tryParse(_start.text); + if (v == null) return; + _syncing = true; + _startTime.text = _fmtMs(v / 360 * cycle, u); + _syncing = false; + }); + _duration.addListener(() { + if (_syncing) return; + final double? v = double.tryParse(_duration.text); + if (v == null) return; + _syncing = true; + _durationTime.text = _fmtMs(v / 360 * cycle, u); + _syncing = false; + }); + // 时间 → 角度 + _startTime.addListener(() { + if (_syncing) return; + final double? ms = parseDuration(_startTime.text, u); + if (ms == null) return; + _syncing = true; + _start.text = (ms / cycle * 360).toStringAsFixed(1); + _syncing = false; + }); + _durationTime.addListener(() { + if (_syncing) return; + final double? ms = parseDuration(_durationTime.text, u); + if (ms == null) return; + _syncing = true; + _duration.text = (ms / cycle * 360).toStringAsFixed(1); + _syncing = false; + }); + } + + /// 按当前时间单位格式化毫秒值。 + String _fmtMs(double ms, UnitSettings u) { + final int dec = u.precision >= 0 ? u.precision : kTimeDec[u.timeUnit]!; + return timeValue(ms, u.timeUnit).toStringAsFixed(dec); + } + + /// 释放全部文本控制器。 + @override + void dispose() { + _name.dispose(); + _driver.dispose(); + _start.dispose(); + _duration.dispose(); + _startTime.dispose(); + _durationTime.dispose(); + super.dispose(); + } + + /// 渲染动作编辑表单:名称、驱动、工位、相位与调色板。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final Project p = widget.controller.project; + return AlertDialog( + backgroundColor: t.dialog, + title: Text('编辑 ${widget.action.id}'), + content: SizedBox( + width: 460, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _name, + decoration: const InputDecoration(labelText: '动作名称'), + ), + const SizedBox(height: 8), + TextField( + controller: _driver, + decoration: const InputDecoration(labelText: '驱动 / 执行器'), + ), + const SizedBox(height: 8), + DropdownButtonFormField( + initialValue: _station, + decoration: const InputDecoration(labelText: '工位'), + items: p.stations + .map((Station s) => DropdownMenuItem(value: s.id, child: Text('${s.id} ${s.name}'))) + .toList(), + onChanged: (String? v) => setState(() => _station = v ?? _station), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: TextField( + controller: _start, + keyboardType: TextInputType.number, + decoration: const InputDecoration(labelText: '起始相位 (°)'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _duration, + keyboardType: TextInputType.number, + decoration: const InputDecoration(labelText: '持续相位 (°)'), + ), + ), + ], + ), + const SizedBox(height: 8), + // 按时间输入:与角度实时双向换算(单位随工艺参数设置)。 + Row( + children: [ + Expanded( + child: TextField( + controller: _startTime, + keyboardType: TextInputType.number, + decoration: InputDecoration(labelText: '起始时刻 (${timeUnitLabel(p.units.timeUnit)})'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _durationTime, + keyboardType: TextInputType.number, + decoration: InputDecoration(labelText: '持续时长 (${timeUnitLabel(p.units.timeUnit)})'), + ), + ), + ], + ), + const SizedBox(height: 4), + Align( + alignment: Alignment.centerLeft, + child: Text( + '角度与时间可互相换算:1 圈 = ${tfmt(p.cycle.durationMs, p.units)} = 360°', + style: TextStyle(color: t.dim, fontSize: 11), + ), + ), + const SizedBox(height: 12), + Wrap( + spacing: 8, + children: kActionPalette.map((int col) { + return GestureDetector( + onTap: () => setState(() => _color = col), + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: Color(col), + borderRadius: BorderRadius.circular(7), + border: Border.all( + color: _color == col ? t.selOutline : Colors.transparent, + width: 2, + ), + ), + ), + ); + }).toList(), + ), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + FilledButton( + onPressed: () { + // 解析相位输入;解析失败则保留原值,并将相位限制在合法区间。 + final double? s = double.tryParse(_start.text); + final double? d = double.tryParse(_duration.text); + widget.controller.updateAction( + widget.action.id, + (Action a) => a.copyWith( + name: _name.text.trim().isEmpty ? a.name : _name.text.trim(), + driver: _driver.text.trim(), + stationId: _station, + color: _color, + startAngle: (s ?? a.startAngle).clamp(0, 360), + durationAngle: (d ?? a.durationAngle).clamp(5, 360), + ), + status: '编辑 ${widget.action.id}', + ); + Navigator.pop(context); + }, + child: const Text('确定'), + ), + ], + ); + } +} + +// ===================== 依赖编辑对话框 ===================== + +/// 依赖编辑对话框:为指定动作添加一条前置依赖。 +class DependencyEditorDialog extends StatefulWidget { + const DependencyEditorDialog({super.key, required this.controller, required this.action}); + + /// 全局应用控制器。 + final AppController controller; + /// 目标动作(依赖的“后置”端)。 + final Action action; + + /// 创建依赖编辑对话框对应的状态对象。 + @override + State createState() => _DependencyEditorDialogState(); +} + +/// 依赖编辑对话框状态:维护前置动作、依赖类型与偏移角。 +class _DependencyEditorDialogState extends State { + /// 选择的前置动作 id。 + String? _from; + /// 依赖类型,默认 FS(完成-启动)。 + DepType _type = DepType.fs; + /// 偏移角输入控制器。 + final TextEditingController _offset = TextEditingController(text: '0'); + + /// 渲染依赖表单:前置动作、依赖类型与偏移角。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final List others = + widget.controller.project.actions.where((Action a) => a.id != widget.action.id).toList(); + return AlertDialog( + backgroundColor: t.dialog, + title: Text('为 ${widget.action.id} 添加前置依赖'), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + DropdownButtonFormField( + initialValue: _from, + decoration: const InputDecoration(labelText: '前置动作'), + items: others + .map((Action a) => DropdownMenuItem(value: a.id, child: Text('${a.id} ${a.name}'))) + .toList(), + onChanged: (String? v) => setState(() => _from = v), + ), + const SizedBox(height: 8), + DropdownButtonFormField( + initialValue: _type, + decoration: const InputDecoration(labelText: '依赖类型'), + items: const >[ + DropdownMenuItem(value: DepType.fs, child: Text('FS 完成-启动(严格顺序)')), + DropdownMenuItem(value: DepType.ss, child: Text('SS 起始-起始(并行重叠)')), + DropdownMenuItem(value: DepType.ff, child: Text('FF 完成-完成')), + DropdownMenuItem(value: DepType.sf, child: Text('SF 起始-完成')), + ], + onChanged: (DepType? v) => setState(() => _type = v ?? _type), + ), + const SizedBox(height: 8), + TextField( + controller: _offset, + keyboardType: TextInputType.number, + decoration: const InputDecoration(labelText: '偏移角 offset (°)'), + ), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + FilledButton( + onPressed: () { + // 未选择前置动作时不提交。 + if (_from == null) return; + widget.controller.addDependency( + _from!, + widget.action.id, + _type, + double.tryParse(_offset.text) ?? 0, + ); + Navigator.pop(context); + }, + child: const Text('添加'), + ), + ], + ); + } +} + +// ===================== 工艺参数设置对话框 ===================== + +/// 工艺参数对话框:设置项目名称、时间/相位单位、显示精度、 +/// 循环时长、换算表与编辑辅助选项。 +class SettingsDialog extends StatefulWidget { + const SettingsDialog({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 创建工艺参数对话框对应的状态对象。 + @override + State createState() => _SettingsDialogState(); +} + +/// 工艺参数对话框状态:以副本形式编辑单位设置,点击“应用”后统一提交。 +class _SettingsDialogState extends State { + /// 正在编辑的单位设置副本。 + late UnitSettings _u; + /// 循环时长输入控制器。 + late TextEditingController _cycle; + /// 项目名称输入控制器。 + late TextEditingController _name; + + /// 用当前项目的单位与名称初始化编辑副本。 + @override + void initState() { + super.initState(); + _u = widget.controller.project.units; + _cycle = TextEditingController( + text: timeValue(widget.controller.project.cycle.durationMs, _u.timeUnit) + .toStringAsFixed(_u.timeUnit == TimeUnit.ms ? 0 : 3), + ); + _name = TextEditingController(text: widget.controller.project.name); + } + + /// 渲染工艺参数表单:项目名、单位、精度、循环、换算表与编辑辅助。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final double cycleMs = widget.controller.project.cycle.durationMs; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 860, + height: 620, + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text('工艺参数', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: t.text)), + const SizedBox(width: 14), + Text('单位与精度 / 循环与相位 / 编辑辅助', + style: TextStyle(fontSize: 11, color: t.dim)), + ], + ), + const Divider(height: 24), + Expanded( + child: ListView( + children: [ + Text('项目名称', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + TextField( + controller: _name, + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: t.panel2, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(height: 18), + // 时间单位:ms / s / min,附精度示例。 + Text('时间单位', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 8), + Row( + children: TimeUnit.values.map((TimeUnit u) { + final bool active = _u.timeUnit == u; + return Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 8), + child: _card( + t, + active: active, + title: timeUnitLabel(u), + subtitle: _timeHint(u), + example: '1° = ${tfmtAuto(cycleMs / 360)}', + onTap: () => setState(() => _u = _u.copyWith(timeUnit: u)), + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 18), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('相位单位', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _card( + t, + active: _u.phaseUnit == PhaseUnit.deg, + title: '° 角度', + subtitle: '0 – 360°', + example: '105.0°', + onTap: () => setState(() => _u = _u.copyWith(phaseUnit: PhaseUnit.deg)), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _card( + t, + active: _u.phaseUnit == PhaseUnit.percent, + title: '% 百分比', + subtitle: '0 – 100%', + example: '29.17%', + onTap: () => setState(() => _u = _u.copyWith(phaseUnit: PhaseUnit.percent)), + ), + ), + ], + ), + ], + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('显示精度', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 8), + Wrap( + spacing: 6, + children: [-1, 0, 1, 2, 3, 4].map((int p) { + final bool active = _u.precision == p; + return ChoiceChip( + label: Text(p == -1 ? '自动' : '$p'), + selected: active, + onSelected: (_) => setState(() => _u = _u.copyWith(precision: p)), + ); + }).toList(), + ), + const SizedBox(height: 8), + Text( + '${tfmt(2400, _u)} · ${pfmt(105, _u)} · 0.700 s', + style: TextStyle(color: t.accent, fontSize: 11), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 18), + // 循环与相位:循环时长可编辑,起点与方向为固定展示。 + Text('循环与相位', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: TextField( + controller: _cycle, + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: '循环时长(1 圈,${timeUnitLabel(_u.timeUnit)})', + isDense: true, + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: TextEditingController(text: '0.0 (12 点钟)'), + enabled: false, + decoration: const InputDecoration( + labelText: '起始相位 / 起点', + isDense: true, + border: OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: TextEditingController(text: '顺时针 CW'), + enabled: false, + decoration: const InputDecoration( + labelText: '旋转方向', + isDense: true, + border: OutlineInputBorder(), + ), + ), + ), + ], + ), + const SizedBox(height: 18), + // 时间 / 相位换算表:以 90° 为步长展示对应关系。 + Text('时间 / 相位 换算', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 6), + Table( + border: TableBorder.all(color: t.line), + children: [ + _row(t, ['相位角', '时间', '百分比', '说明'], header: true), + for (final List r in >[ + ['0°', tfmt(0, _u), '0.00%', '循环起点(12 点钟)'], + ['90°', tfmt(cycleMs / 4, _u), '25.00%', '四分之一圈'], + ['180°', tfmt(cycleMs / 2, _u), '50.00%', '半圈'], + ['270°', tfmt(cycleMs * 3 / 4, _u), '75.00%', '四分之三圈'], + ['360°', tfmt(cycleMs, _u), '100.00%', '循环终点'], + ]) + _row(t, r), + ], + ), + const SizedBox(height: 18), + // 编辑辅助:吸附步长与网格/跨圈等开关。 + Text('编辑辅助', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(height: 8), + Row( + children: [ + Text('角度吸附', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 8), + for (final double s in [1, 5, 15]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: ChoiceChip( + label: Text('${s.toStringAsFixed(0)}°'), + selected: _u.snapAngle == s, + onSelected: (_) => setState(() => _u = _u.copyWith(snapAngle: s)), + ), + ), + const SizedBox(width: 16), + Text('时间吸附', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 8), + for (final double s in [0.01, 0.1, 1]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: ChoiceChip( + label: Text(s < 1 ? '${(s * 1000).toStringAsFixed(0)} ms' : '1 s'), + selected: _u.snapTime == s, + onSelected: (_) => setState(() => _u = _u.copyWith(snapTime: s)), + ), + ), + ], + ), + const SizedBox(height: 10), + Wrap( + spacing: 10, + children: [ + FilterChip( + label: const Text('显示网格'), + selected: _u.showGrid, + onSelected: (bool v) => setState(() => _u = _u.copyWith(showGrid: v)), + ), + FilterChip( + label: const Text('吸附网格'), + selected: _u.snapGrid, + onSelected: (bool v) => setState(() => _u = _u.copyWith(snapGrid: v)), + ), + FilterChip( + label: const Text('跨圈自动拆分'), + selected: _u.autoSplitWrap, + onSelected: (bool v) => setState(() => _u = _u.copyWith(autoSplitWrap: v)), + ), + ], + ), + const SizedBox(height: 18), + // 相位分区:以独立对话框编辑,支持增删 / 改名 / 改起止角,允许重叠或留空。 + Row( + children: [ + Text('相位分区', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 8), + Expanded( + child: Text('名称 / 起止角 / 数量均可编辑,可重叠', + style: TextStyle(color: t.dim, fontSize: 10)), + ), + OutlinedButton.icon( + onPressed: () => showDialog( + context: context, + builder: (_) => PhaseZoneDialog(controller: widget.controller), + ), + icon: const Icon(Icons.edit, size: 15), + label: Text('编辑…(${widget.controller.project.phaseZones.length})', + style: const TextStyle(fontSize: 11)), + ), + ], + ), + ], + ), + ), + const Divider(height: 24), + Row( + children: [ + TextButton( + onPressed: () => setState(() => _u = const UnitSettings()), + child: const Text('恢复默认'), + ), + const Spacer(), + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + const SizedBox(width: 8), + FilledButton( + onPressed: () { + // 将输入的循环时长按当前时间单位换算为毫秒后统一提交。 + final double? cv = double.tryParse(_cycle.text); + final double ms = cv == null ? cycleMs : cv * kTimeDiv[_u.timeUnit]!; + final AppController c = widget.controller; + c.setUnits(_u, status: '工艺参数已应用'); + c.setCycleDuration(ms); + if (_name.text.trim().isNotEmpty && _name.text.trim() != c.project.name) { + c.setProjectName(_name.text.trim()); + } + Navigator.pop(context); + }, + child: const Text('应用'), + ), + ], + ), + ], + ), + ), + ), + ); + } + + /// 构建换算表的一行;[header] 为 true 时使用表头样式。 + TableRow _row(Tokens t, List cells, {bool header = false}) { + return TableRow( + children: cells.map((String s) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), + child: Text( + s, + style: TextStyle( + color: header ? t.dim : (s.endsWith('°') ? t.accent : t.sub), + fontSize: 11, + fontWeight: header ? FontWeight.w600 : FontWeight.normal, + ), + ), + ); + }).toList(), + ); + } + + /// 返回各时间单位对应的使用场景提示。 + String _timeHint(TimeUnit u) { + switch (u) { + case TimeUnit.ms: + return '高速动作 · 伺服点位'; + case TimeUnit.s: + return '装配 / 压装(推荐)'; + case TimeUnit.min: + return '热处理 · 长周期'; + } + } + + /// 渲染一个可点选的设置卡片(标题、副标题与示例)。 + Widget _card( + Tokens t, { + required bool active, + required String title, + required String subtitle, + required String example, + required VoidCallback onTap, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.12) : t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: active ? t.accent : t.line, width: active ? 1.5 : 1), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(active ? Icons.radio_button_checked : Icons.radio_button_unchecked, + size: 15, color: active ? t.accent : t.dim), + const SizedBox(width: 6), + Text(title, style: TextStyle(color: active ? t.text : t.sub, fontWeight: FontWeight.w600, fontSize: 12)), + ], + ), + const SizedBox(height: 6), + Text(subtitle, style: TextStyle(color: t.dim, fontSize: 10)), + const SizedBox(height: 4), + Text(example, style: TextStyle(color: active ? t.accent : t.dim, fontSize: 10)), + ], + ), + ), + ); + } +} + +// ===================== 相位分区编辑器 ===================== + +/// 相位分区编辑器:增删分区、修改名称与起止角。 +/// +/// 设计要点: +/// - 数量不限,允许区间相互重叠,也允许结束角大于 360° 表示跨圈; +/// - 每行独立的输入控制器,行增删时通过 [_ZoneRow] 的 State 维持输入; +/// - 点击「确定」时一次性提交给 [AppController.setPhaseZones]。 +class PhaseZoneDialog extends StatefulWidget { + const PhaseZoneDialog({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + @override + State createState() => _PhaseZoneDialogState(); +} + +class _PhaseZoneDialogState extends State { + late List _zones; + + @override + void initState() { + super.initState(); + _zones = List.of(widget.controller.project.phaseZones); + } + + void _add() { + setState(() { + _zones.add(const PhaseZone(name: '新分区', startAngle: 0, endAngle: 30)); + }); + } + + void _remove(int i) { + setState(() => _zones.removeAt(i)); + } + + void _update(int i, PhaseZone z) { + setState(() => _zones[i] = z); + } + + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 620, + height: 560, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.view_week_outlined, size: 18, color: t.accent), + const SizedBox(width: 8), + Text('相位分区', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: t.text)), + const SizedBox(width: 10), + Expanded( + child: Text('名称 / 起止角 / 数量均可编辑;允许区间重叠,结束角 > 360° 表示跨圈', + style: TextStyle(fontSize: 10, color: t.dim)), + ), + ], + ), + const Divider(height: 20), + Expanded( + child: _zones.isEmpty + ? Center(child: Text('暂无分区,点击下方「添加分区」', style: TextStyle(color: t.dim, fontSize: 11))) + : ListView.builder( + itemCount: _zones.length, + itemBuilder: (BuildContext ctx, int i) { + return _ZoneRow( + key: ValueKey(i), + t: t, + zone: _zones[i], + onChanged: (PhaseZone z) => _update(i, z), + onDelete: () => _remove(i), + ); + }, + ), + ), + const Divider(height: 20), + Row( + children: [ + OutlinedButton.icon( + onPressed: _add, + icon: const Icon(Icons.add, size: 16), + label: const Text('添加分区'), + ), + const SizedBox(width: 8), + TextButton( + onPressed: () => setState(() => _zones = List.of(PhaseZone.defaults)), + child: const Text('恢复默认'), + ), + const Spacer(), + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + const SizedBox(width: 8), + FilledButton( + onPressed: () { + widget.controller.setPhaseZones(_zones, status: '相位分区已更新'); + Navigator.pop(context); + }, + child: const Text('确定'), + ), + ], + ), + ], + ), + ), + ), + ); + } +} + +/// 相位分区编辑器中的单行:名称、起始角、结束角与删除按钮。 +class _ZoneRow extends StatefulWidget { + const _ZoneRow({super.key, required this.t, required this.zone, required this.onChanged, required this.onDelete}); + + final Tokens t; + final PhaseZone zone; + final ValueChanged onChanged; + final VoidCallback onDelete; + + @override + State<_ZoneRow> createState() => _ZoneRowState(); +} + +class _ZoneRowState extends State<_ZoneRow> { + late final TextEditingController _name; + late final TextEditingController _start; + late final TextEditingController _end; + + @override + void initState() { + super.initState(); + _name = TextEditingController(text: widget.zone.name); + _start = TextEditingController(text: _fmt(widget.zone.startAngle)); + _end = TextEditingController(text: _fmt(widget.zone.endAngle)); + } + + @override + void dispose() { + _name.dispose(); + _start.dispose(); + _end.dispose(); + super.dispose(); + } + + static String _fmt(double v) => v == v.roundToDouble() ? v.toStringAsFixed(0) : v.toString(); + + void _emit() { + widget.onChanged(PhaseZone( + name: _name.text.trim().isEmpty ? '相位分区' : _name.text.trim(), + startAngle: double.tryParse(_start.text.trim()) ?? widget.zone.startAngle, + endAngle: double.tryParse(_end.text.trim()) ?? widget.zone.endAngle, + )); + } + + @override + Widget build(BuildContext context) { + final Tokens t = widget.t; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Expanded( + flex: 3, + child: _field(t, _name, '名称', (String _) => _emit()), + ), + const SizedBox(width: 8), + SizedBox( + width: 90, + child: _field(t, _start, '起始°', (String _) => _emit()), + ), + const SizedBox(width: 6), + Text('–', style: TextStyle(color: t.dim)), + const SizedBox(width: 6), + SizedBox( + width: 90, + child: _field(t, _end, '结束°', (String _) => _emit()), + ), + IconButton( + onPressed: widget.onDelete, + icon: Icon(Icons.delete_outline, size: 17, color: t.danger), + splashRadius: 16, + tooltip: '删除分区', + ), + ], + ), + ); + } + + Widget _field(Tokens t, TextEditingController c, String hint, ValueChanged onChanged) { + return TextField( + controller: c, + onChanged: onChanged, + style: TextStyle(color: t.text, fontSize: 11), + decoration: InputDecoration( + isDense: true, + hintText: hint, + hintStyle: TextStyle(color: t.dim, fontSize: 11), + filled: true, + fillColor: t.panel2, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ); + } +} + +// ===================== 帮助中心对话框 ===================== + +/// 帮助中心对话框:以四个标签页展示快速开始、快捷键、 +/// 双视图说明以及单位与导出等信息。 +class HelpDialog extends StatelessWidget { + const HelpDialog({super.key}); + + /// 渲染帮助中心:标签栏 + 各标签页的内容列表。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: SizedBox( + width: 880, + height: 620, + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.help_outline, color: t.accent), + const SizedBox(width: 8), + Text('帮助中心', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: t.text)), + ], + ), + const Divider(height: 22), + Expanded( + child: DefaultTabController( + length: 6, + child: Column( + children: [ + const TabBar( + isScrollable: true, + tabs: [ + Tab(text: '开始与动作'), + Tab(text: '时间与依赖'), + Tab(text: '相位分区与视图'), + Tab(text: 'AI 与导出'), + Tab(text: '界面与快捷键'), + Tab(text: '关于'), + ], + ), + Expanded( + child: TabBarView( + children: [ + // 目标:完成方案的搭建与动作的增删改。 + _section(t, >[ + ['我要新建方案', '顶部「新建」创建空白节拍;「打开」载入 .seq.json。'], + ['我要先看看示例', '首次启动载入 2 个动作的示例节拍,可直接修改。'], + ['我要新增动作', '双击画布空白处在点击相位新增;或左侧「新建」在 0° 新增(默认最外层)。'], + ['我要删除动作', '选中后:左侧「删除」/ 行内删除图标 / 右侧删除 / Delete 键 / 右键菜单。'], + ['我要改动作属性', '选中动作 → 右侧「编辑」,可改名称、工位、驱动与颜色。'], + ['我要复制 / 对齐', '右侧「编辑操作」→「复制」/「对齐相位」;圆周视图还可改层。'], + ]), + // 目标:调整时间轴与动作间的先后 / 并行关系。 + _section(t, >[ + ['我要改时间轴长度', '点左侧项目卡的「循环 …」,或按 F2 →「循环与相位」→ 循环时长 → 应用。'], + ['我要调相位 / 时长', '拖动动作块平移相位;拖条形右端改持续角;右侧滑杆可精调。'], + ['我要让动作跨循环', '使「起始角 + 持续角 > 360°」,会自动拆分并以半透明虚线渲染尾段。'], + ['我要加前置依赖(输入)', '右侧「前置依赖 · 输入」→「添加前置依赖」;或右键动作 →「添加依赖」。'], + ['一个动作多输入', '可重复添加多条前置依赖,逐条列出、逐条可删。'], + ['一个动作多输出', '在「输出依赖 · 结果」查看本动作指向的后续动作,并可逐条删除。'], + ['FS / SS 是什么', 'FS 绿色实线=完成后启动;SS 琥珀虚线=可提前启动(并行重叠,带 +n°)。'], + ]), + // 目标:编辑相位分区并控制画布显示。 + _section(t, >[ + ['相位分区是什么', '把一个循环按角度分成的命名工艺阶段(默认上料/夹紧/加工/检测/下料),条形图顶部标注带即它。'], + ['我要编辑相位分区', 'F2 →「相位分区」→「编辑…」:增删分区、改名称与起止角;可重叠、可留空、>360° 表示跨圈。'], + ['我要隐藏相位分区', '左侧「显示选项」取消勾选「相位分区标注」。'], + ['我要切换视图', '顶部「条形节拍 / 圆周节拍」分段开关,两种视图共享同一份数据。'], + ['我要缩放 / 平移', 'Ctrl+滚轮 以光标为锚点缩放;普通滚轮或拖拽空白平移。'], + ['我要完整显示', '顶部「适应视图」:自动按内容(含刻度、箭头、跨圈标注)计算缩放与居中,编辑后也不会被裁切。'], + ['我要开关标注', '左侧「显示选项」逐项开关双刻度、依赖箭头、圆环背景、层标注、跨循环高亮等。'], + ]), + // 目标:用 AI 生成,并导出成果。 + _section(t, >[ + ['我要 AI 生成', '顶部「AI 生成」→ 填 DeepSeek API Key → 选模型(Flash / Pro)→ 选强度(高 / 最高)→ 用自然语言描述 → 生成。'], + ['生成效果不好', '描述里写清:循环时长、工位数、各动作时长、哪些顺序(完成后启动)、哪些并行。'], + ['我要看节拍统计', '画布左下角「节拍统计」按钮 → 弹窗查看关键路径、并行度、瓶颈工位、产能等。'], + ['我要导出 SVG', '顶部「导出 SVG」:矢量、分层、带语义 id 与 data-*,可直接进工艺卡 / MES。'], + ['我要导出 PNG', '顶部「导出 PNG」:按 2 倍像素比导出当前画布为位图。'], + ['我要保存 / 恢复', '「保存」写入 .seq.json 并生成 .bak;每 5 秒自动快照,异常退出后启动可恢复。'], + ]), + // 目标:调整界面与使用快捷键。 + _section(t, >[ + ['我要隐藏 / 显示侧栏', '工具栏右侧两个侧栏按钮,分别控制左、右侧栏。'], + ['我要钉住侧栏', '侧栏标题右侧图钉:钉住=固定占位;取消钉住=悬浮,鼠标移开自动收起。'], + ['边缘把手', '侧栏收起后画布边缘有细把手:悬停临时展开,点击固定显示。'], + ['拖拽 / 缩放', '左键拖拽平移相位;拖端点改时长;Shift+拖拽改层;Ctrl+滚轮缩放。'], + ['右键动作', '菜单:添加依赖 / 改层 / 复制 / 删除。'], + ['撤销 / 保存', 'Ctrl+Z / Ctrl+Y 撤销重做;Ctrl+S 保存;Ctrl+O / Ctrl+N 打开 / 新建。'], + ['其它', 'F1 帮助;F2 工艺参数(含相位分区);F3 切换深/浅主题;Delete 删除选中动作。'], + ]), + // 关于:设计人、版本与版权声明。 + _section(t, >[ + ['软件名称', '时序图工作台 · Sequence Diagram Studio'], + ['设计人', '呆头鹅'], + ['版本', 'V1.0.0'], + ['版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'], + ['用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'], + ['技术栈', 'Flutter Desktop · 自绘 Canvas · 纯 Dart 几何 · JSON 持久化 · SVG 导出。'], + ]), + ], + ), + ), + ], + ), + ), + ), + Align( + alignment: Alignment.centerRight, + child: FilledButton(onPressed: () => Navigator.pop(context), child: const Text('关闭')), + ), + ], + ), + ), + ), + ); + } + + /// 渲染帮助中的一个条目列表,每行左侧为标题、右侧为说明。 + Widget _section(Tokens t, List> rows) { + return ListView( + padding: const EdgeInsets.only(top: 14), + children: rows.map((List r) { + return Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 150, + child: Text(r[0], style: TextStyle(color: t.accent, fontWeight: FontWeight.w600, fontSize: 12)), + ), + Expanded( + child: Text(r[1], style: TextStyle(color: t.sub, fontSize: 11, height: 1.5)), + ), + ], + ), + ); + }).toList(), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..d2970fb --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,277 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.9" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.3" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.0.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "2b7f9d2a3c730ac1a98221b420cef966b990fca7ab546ede324642ca57a533e3" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.4.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.flutter-io.cn" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.1.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.9.1" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "484dfc873ea4c4f4240e5635444fa066f87b07862b7279ebd004a2b71fba4b7a" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.4.3" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.12.2" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.12" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.2" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.flutter-io.cn" + source: hosted + version: "15.3.0" +sdks: + dart: ">=3.13.3 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..a03f35a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,89 @@ +name: sequence_diagram +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.13.3 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_riverpod: ^3.4.3 +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/scripts/build.bat b/scripts/build.bat new file mode 100644 index 0000000..caad272 --- /dev/null +++ b/scripts/build.bat @@ -0,0 +1,32 @@ +@echo off +rem Build the Windows release and copy the runnable bundle to .\dist\ +rem (ASCII only: .bat files are read with the OEM codepage.) +setlocal + +set FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn +set PUB_HOSTED_URL=https://pub.flutter-io.cn +set PATH=E:\flutter\bin;%PATH% + +if exist E:\cmake-lv\bin\cmk2.exe ( + set FLUTTER_CMAKE_PATH=E:\cmake-lv\bin\cmk2.exe +) else ( + echo [warn] renamed CMake not found: E:\cmake-lv\bin\cmk2.exe + echo [warn] if a transparent-encryption DLP is installed, run scripts\setup-cmake.bat first. +) + +cd /d "%~dp0.." +rem --no-tree-shake-icons: bundle the full Material icon font so newly used +rem icons are always present (avoids stale/blank icons after incremental builds). +call flutter build windows --release --no-tree-shake-icons +if errorlevel 1 ( + echo Build failed. + exit /b 1 +) + +if exist dist rmdir /s /q dist +mkdir dist +xcopy /e /i /y /q "build\windows\x64\runner\Release\*" "dist\" >nul + +echo. +echo Build OK: dist\sequence_diagram.exe +endlocal diff --git a/scripts/run.bat b/scripts/run.bat new file mode 100644 index 0000000..abe29f5 --- /dev/null +++ b/scripts/run.bat @@ -0,0 +1,13 @@ +@echo off +rem 开发调试运行 +setlocal + +set FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn +set PUB_HOSTED_URL=https://pub.flutter-io.cn +set PATH=E:\flutter\bin;%PATH% + +if exist E:\cmake-lv\bin\cmk2.exe set FLUTTER_CMAKE_PATH=E:\cmake-lv\bin\cmk2.exe + +cd /d "%~dp0.." +call flutter run -d windows +endlocal diff --git a/scripts/setup-cmake.bat b/scripts/setup-cmake.bat new file mode 100644 index 0000000..3cd8b73 --- /dev/null +++ b/scripts/setup-cmake.bat @@ -0,0 +1,23 @@ +@echo off +rem 为绿盾(透明加密)环境准备一份重命名后的 CMake。 +rem 绿盾按进程名 cmake.exe 加密其生成文件,导致 CMake 解析失败; +rem 复制到非受控路径并重命名即可规避。 +setlocal + +set SRC=C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake +set DST=E:\cmake-lv + +if not exist "%SRC%\bin\cmake.exe" ( + echo [error] 未找到 Visual Studio 自带的 CMake: + echo %SRC% + echo 请根据实际安装路径修改本脚本。 + exit /b 1 +) + +echo 复制 CMake 到 %DST% ... +robocopy "%SRC%" "%DST%" /E /NFL /NDL /NJH /NJS /NP >nul +copy /y "%DST%\bin\cmake.exe" "%DST%\bin\cmk2.exe" >nul + +echo 完成: %DST%\bin\cmk2.exe +echo 构建时请设置 FLUTTER_CMAKE_PATH=%DST%\bin\cmk2.exe +endlocal diff --git a/test/model_test.dart b/test/model_test.dart new file mode 100644 index 0000000..727da4e --- /dev/null +++ b/test/model_test.dart @@ -0,0 +1,60 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; + +void main() { + group('units', () { + test('time conversion', () { + const UnitSettings u = UnitSettings(timeUnit: TimeUnit.s); + expect(tfmt(2400, u), '2.400 s'); + expect(tfmt(467, u), '0.467 s'); + const UnitSettings ms = UnitSettings(timeUnit: TimeUnit.ms); + expect(tfmt(467, ms), '467 ms'); + expect(parseDuration('700ms', u), 700); + expect(parseDuration('0.7s', u), 700); + expect(parseDuration('0.7', u), 700); + }); + + test('phase conversion', () { + expect(pfmt(105, const UnitSettings()), '105.0°'); + expect(pfmt(105, const UnitSettings(phaseUnit: PhaseUnit.percent)), '29.17%'); + expect(parsePhase('29.17%'), closeTo(105.012, 0.01)); + expect(parsePhase('105°'), 105); + }); + + test('snap and normalize', () { + expect(snapTo(103, 5), 105); + expect(normalizeAngle(-10), 350); + expect(normalizeAngle(370), 10); + }); + }); + + group('model', () { + test('wrap detection', () { + final Action a = Action( + id: 'A8', + name: '清洁', + stationId: 'ST3', + driver: '', + startAngle: 340, + durationAngle: 45, + layer: 7, + color: kActionPalette[0], + ); + expect(a.wrap, isTrue); + expect(a.endAngle, 385); + }); + + test('json round trip', () { + final Project p = Project.demo(); + final String encoded = p.encode(); + final Project decoded = Project.decode(encoded); + expect(decoded.actions.length, p.actions.length); + expect(decoded.stations.length, p.stations.length); + expect(decoded.phaseZones.length, p.phaseZones.length); + expect(decoded.actions.last.deps.first.type, DepType.fs); + expect(decoded.cycle.durationMs, 2400); + expect(decoded.actions.last.color, p.actions.last.color); + }); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..8cd3cdb --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/app_shell.dart'; + +void main() { + testWidgets('renders bar and circular views without errors', (WidgetTester tester) async { + tester.view.physicalSize = const Size(1920, 1080); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final AppController controller = AppController(); + addTearDown(controller.dispose); + + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.dark), + home: AppShell(controller: controller), + )); + await tester.pump(); + expect(find.byType(AppShell), findsOneWidget); + + controller.setViewMode(ViewMode.circular); + await tester.pump(); + expect(controller.project.viewState.mode, ViewMode.circular); + + controller.addAction(startAngle: 30); + await tester.pump(); + expect(controller.project.actions.length, 3); + + controller.setViewMode(ViewMode.bar); + await tester.pump(); + expect(find.text('条形节拍'), findsOneWidget); + }); + + testWidgets('light theme renders by default and can toggle', (WidgetTester tester) async { + tester.view.physicalSize = const Size(1920, 1080); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final AppController controller = AppController(); + addTearDown(controller.dispose); + // 默认应为浅色(白底)。 + expect(controller.brightness, Brightness.light); + + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.of(controller.brightness)), + home: AppShell(controller: controller), + )); + await tester.pump(); + expect(find.byType(AppShell), findsOneWidget); + + // 切换主题后应变为深色。 + controller.toggleTheme(); + await tester.pump(); + expect(controller.brightness, Brightness.dark); + }); +} diff --git a/tools/gen-icon.py b/tools/gen-icon.py new file mode 100644 index 0000000..1bcaade --- /dev/null +++ b/tools/gen-icon.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Generate the Sequence Diagram Studio application icon. + +A clock / cycle dial that reflects the product spirit: one turn = one cycle, +12 o'clock origin, clockwise phase progression. + +Outputs: + windows/runner/resources/app_icon.ico (multi-size, for the Windows build) + demo/app-icon.png (1024px preview) +""" +import math +import os + +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +OUT_ICO = os.path.join(ROOT, "windows", "runner", "resources", "app_icon.ico") +OUT_PNG = os.path.join(ROOT, "demo", "app-icon.png") + +S = 1024 +BG_TOP = (14, 21, 32, 255) +BG_BOT = (11, 16, 24, 255) +LINE = (31, 44, 64, 255) +ACCENT = (76, 201, 240, 255) +ACCENT2 = (124, 92, 255, 255) +OK = (52, 211, 153, 255) +DIAL = (12, 19, 32, 255) +TICK = (42, 58, 82, 255) +TEXT = (232, 238, 252, 255) + + +def lerp(a, b, t): + return tuple(round(a[i] + (b[i] - a[i]) * t) for i in range(4)) + + +def rounded_mask(size, radius, inset=0): + m = Image.new("L", (size, size), 0) + d = ImageDraw.Draw(m) + d.rounded_rectangle( + [inset, inset, size - 1 - inset, size - 1 - inset], + radius=radius, + fill=255, + ) + return m + + +def polar(cx, cy, r, deg): + t = math.radians(deg - 90) + return (cx + r * math.cos(t), cy + r * math.sin(t)) + + +def arc(draw, cx, cy, r, a0, a1, color, width): + draw.arc( + [cx - r, cy - r, cx + r, cy + r], + start=a0 - 90, + end=a1 - 90, + fill=color, + width=width, + ) + + +def build_master(): + img = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + draw = ImageDraw.Draw(img) + + # Rounded-square body with a vertical gradient. + body = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + bd = ImageDraw.Draw(body) + for y in range(S): + bd.line([(0, y), (S, y)], fill=lerp(BG_TOP, BG_BOT, y / (S - 1))) + mask = rounded_mask(S, 210, inset=48) + img.paste(body, (0, 0), mask) + + # Inner border ring. + draw.rounded_rectangle( + [48, 48, S - 1 - 48, S - 1 - 48], + radius=210, + outline=LINE, + width=6, + ) + + cx = cy = S // 2 + r_ring = 320 + ring_w = 46 + + # Dial disc. + draw.ellipse( + [cx - r_ring - ring_w // 2, cy - r_ring - ring_w // 2, + cx + r_ring + ring_w // 2, cy + r_ring + ring_w // 2], + fill=DIAL, + outline=LINE, + width=4, + ) + + # 12 / 3 / 6 / 9 major ticks. + for d in range(0, 360, 30): + major = d % 90 == 0 + r1 = r_ring - 96 + r2 = r_ring - (52 if major else 74) + col = ACCENT if major else TICK + w = 14 if major else 9 + draw.line([polar(cx, cy, r1, d), polar(cx, cy, r2, d)], fill=col, width=w) + + # Phase arcs on the outer ring: two "actions" of the cycle. + arc(draw, cx, cy, r_ring, 0, 70, ACCENT, ring_w) + arc(draw, cx, cy, r_ring, 105, 190, ACCENT2, ring_w) + arc(draw, cx, cy, r_ring, 300, 360, OK, ring_w) + + # Clock hands: classic 10:10 pose. + for r, deg, col, w in ((168, 305, TEXT, 34), (238, 55, ACCENT, 26)): + hx, hy = polar(cx, cy, r, deg) + draw.line([(cx, cy), (hx, hy)], fill=col, width=w) + draw.ellipse([hx - w / 2, hy - w / 2, hx + w / 2, hy + w / 2], fill=col) + + # Hub. + draw.ellipse([cx - 30, cy - 30, cx + 30, cy + 30], fill=TEXT) + draw.ellipse([cx - 13, cy - 13, cx + 13, cy + 13], fill=DIAL) + + return img + + +def main(): + master = build_master() + os.makedirs(os.path.dirname(OUT_ICO), exist_ok=True) + os.makedirs(os.path.dirname(OUT_PNG), exist_ok=True) + + master.save(OUT_PNG) + + sizes = [256, 128, 64, 48, 32, 24, 16] + frames = [master.resize((s, s), Image.LANCZOS) for s in sizes] + frames[0].save( + OUT_ICO, + format="ICO", + sizes=[(s, s) for s in sizes], + append_images=frames[1:], + ) + print("wrote", OUT_ICO) + print("wrote", OUT_PNG) + + +if __name__ == "__main__": + main() diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..148cfb8 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(sequence_diagram LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "sequence_diagram") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..64880bd --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,46 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +target_link_options(${BINARY_NAME} PRIVATE "/MANIFEST:NO") +add_custom_command(TARGET ${BINARY_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/runner.exe.manifest" + "$/${BINARY_NAME}.exe.manifest") + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..c4c25e8 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "呆头鹅" "\0" + VALUE "FileDescription", "时序图工作台 Sequence Diagram Studio" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "sequence_diagram" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 呆头鹅. All rights reserved." "\0" + VALUE "OriginalFilename", "sequence_diagram.exe" "\0" + VALUE "ProductName", "时序图工作台" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c842cee --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,108 @@ +#include "flutter_window.h" + +#include +#include + +#include +#include +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + // Method channel used by the Dart side to update the native window title + // (e.g. "时序图工作台 - "). + title_channel_ = + std::make_unique>( + flutter_controller_->engine()->messenger(), "seqstudio/window", + &flutter::StandardMethodCodec::GetInstance()); + title_channel_->SetMethodCallHandler( + [this](const flutter::MethodCall& call, + std::unique_ptr> + result) { + if (call.method_name() == "setTitle") { + const std::string* title = + std::get_if(call.arguments()); + if (title != nullptr) { + HWND handle = GetHandle(); + if (handle != nullptr) { + const int size = ::MultiByteToWideChar( + CP_UTF8, 0, title->c_str(), -1, nullptr, 0); + std::wstring wide(size > 0 ? size - 1 : 0, L'\0'); + if (size > 0) { + ::MultiByteToWideChar(CP_UTF8, 0, title->c_str(), -1, + &wide[0], size); + } + ::SetWindowTextW(handle, wide.c_str()); + } + } + result->Success(); + } else { + result->NotImplemented(); + } + }); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..95e556a --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,39 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; + + // Channel used to set the native window title from Dart. + std::unique_ptr> + title_channel_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..e1fac0c --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,54 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + + // Open at ~94% of the primary monitor so the full workbench is visible on + // any display without the panels running off screen. + HDC screen = ::GetDC(nullptr); + const int dpi = ::GetDeviceCaps(screen, LOGPIXELSX); + ::ReleaseDC(nullptr, screen); + const double scale = dpi > 0 ? dpi / 96.0 : 1.0; + const int screen_width = ::GetSystemMetrics(SM_CXSCREEN); + const int screen_height = ::GetSystemMetrics(SM_CYSCREEN); + Win32Window::Point origin(10, 10); + Win32Window::Size size( + static_cast(screen_width / scale * 0.94), + static_cast(screen_height / scale * 0.94)); + if (!window.Create(L"\u65F6\u5E8F\u56FE\u5DE5\u4F5C\u53F0", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..23eb9a4e3af3498ac28c6a385a47058e11c2a71d GIT binary patch literal 47579 zcmagFWl$W!+6KD#;)?}$cSvw|3-0a~Ai*uz0*gDr-Q6L$yE}p4?(WXbIp_Yob-%8u znST16u9>Ns=hYqn01AKr0D%Di8X15K1^{sT*Tcj6A7+OG04n~Ck&*omyC47nYd`>i zjqQKf9|ZtV`8QWYhOlN#5~A{fr^|Q65!F-ES7Ct#DW&Ot$e210BV`jAAe}PEYAUX?*nZam%c# z!$*99U*q@kB)+Fr(sAt@o&uhXQLnYc%|7S*`xd`^JcK?Yw6;-|pQUd~vHfWFR$2qM zWNfMBmkj3I>pku(mgEA~g3YPdg^%~2!mGXFB^w1vSUrYJ4v#DUBzr3=tf|e$w$+!* z&xBE4=KL`;Khpm!6aVRa$~bmrW%GSz@;uoHknENU8ZTS2Nu9hv|EsNU@#7t}sHo`i zxfiarbL?@YIP4igNAQE)=Y_Ub_BU-wSlm_z>tvhVftAL5!b?Au#q7RtyX!HwbaBz+ zQOpa+c}1P$8&Y9hvBMdcR67L&S5+1r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pl$oSL7gR7-h zfDvLXmx0gtN%X$a^IZ^i_e2YQbHWKY)nKI;E8TglA-)a{6*T|$cly!fbjLN-jeRsx zoKIeP(RS=LLz&U9#AZ$GEqgfLKlBM79e`+Tx^=g^_df*aC=r0mERzpCEh7`=kO*M8z_h0)U*^9ck|%~A!H7#Aip!UIdPTgP69eez^Srt?`u zy79nm=Ae9&=0d5f28kPjLgGp1MOlmdUq3Oah>d%bj66ij9SEM&J7m$s#xzF;EGA4w zWdee{e=;X+Q`Dr|J;0_usOoe1&pyam=woal0Q2GhgDqDVneKjV@-!y#fq*(ehv5E& zeT-C_Gno;lQ8FPCd`gH!%}+I9`3*~HSfGeOi0p>|zLr~{O}=ytG` zP{OzK8MiEUsM*oOm_`mT;yTvJV92kP?jhkEd&{?u50@wBv$x!*rZ{A{oFknF%!ND? z;5KS~(5AtT6401D6O50K_)4OT`m@DO_kZK#o9y@~_xF>2t=?FgSB10gtgYEGJwG-V zCNlXA)1O^n@wR;gw3MrHm3wLacuQBPayAjug + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_