From 0a3f2c5cc6388f3ec3bccd01f4c6bcac4202a9cc Mon Sep 17 00:00:00 2001 From: liuyu65 Date: Sun, 22 Nov 2026 10:02:48 +0800 Subject: [PATCH] =?UTF-8?q?v1.3.13:=20=E6=A8=A1=E5=9D=97=E5=8C=96=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E6=9E=B6=E6=9E=84=20+=20PDS=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E8=AE=BE=E8=AE=A1=E5=A5=97=E4=BB=B6=E6=9B=B4=E5=90=8D=20+=20?= =?UTF-8?q?=E4=BE=9D=E8=B5=96/=E5=9C=86=E5=91=A8=E4=BA=A4=E4=BA=92?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json - 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档 - 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸 - 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名 - 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes --- BUILD-NOTES.md | 10 +- README.md | 589 ++++- android/app/build.gradle.kts | 3 +- android/app/src/main/AndroidManifest.xml | 2 +- assets/modules/architecture/module.json | 13 + assets/modules/elec/module.json | 13 + assets/modules/io/module.json | 13 + assets/modules/pid/module.json | 13 + assets/modules/registry.json | 84 + assets/modules/sequence/module.json | 13 + assets/modules/topo/module.json | 13 + docs/ARCH-UPGRADE.md | 3 + docs/ARCHITECTURE.md | 524 ++-- docs/DESIGN.md | 2 + docs/HELP.md | 24 +- .../release-notes}/RELEASE_NOTES_v1.3.10.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.11.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.12.md | 0 docs/release-notes/RELEASE_NOTES_v1.3.13.md | 77 + .../release-notes}/RELEASE_NOTES_v1.3.4.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.5.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.6.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.7.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.8.md | 0 .../release-notes}/RELEASE_NOTES_v1.3.9.md | 0 lib/export/export_geometry.dart | 84 + lib/layout/dep_routes.dart | 360 --- lib/main.dart | 24 +- lib/model/models.dart | 14 +- lib/modules/README.md | 150 ++ .../architecture/architecture_module.dart | 130 + .../architecture/domain}/arch_dxf.dart | 2 +- .../architecture/domain}/arch_export.dart | 10 +- .../architecture/domain}/arch_models.dart | 2 +- .../architecture/domain}/arch_painter.dart | 6 +- .../architecture/domain}/arch_recognizer.dart | 0 .../architecture/domain}/arch_samples.dart | 0 .../domain}/arch_symbol_recognizer.dart | 2 +- .../architecture}/library/symbol_library.dart | 0 .../architecture}/sketch/sketch_models.dart | 0 .../architecture}/sketch/sketch_painter.dart | 2 +- .../architecture}/sketch/sketch_solver.dart | 0 .../architecture}/ui/arch_panel.dart | 12 +- .../architecture}/ui/arch_view.dart | 22 +- .../architecture/ui/architecture_ui.dart | 617 +++++ lib/modules/elec/elec_module.dart | 28 + lib/modules/io/io_module.dart | 28 + lib/modules/manifest.dart | 267 ++ lib/modules/module.dart | 236 ++ lib/modules/module_registry.dart | 149 -- lib/modules/pid/pid_module.dart | 28 + lib/modules/registry.dart | 141 + lib/{ => modules/sequence}/ai/ai_client.dart | 96 +- .../sequence}/export/drawio_writer.dart | 15 +- .../sequence}/export/export_fit.dart | 86 +- .../sequence}/export/export_renderer.dart | 10 +- .../sequence}/export/svg_writer.dart | 16 +- lib/modules/sequence/layout/dep_routes.dart | 565 ++++ .../sequence}/layout/flow_layout.dart | 4 +- lib/{ => modules/sequence}/layout/layout.dart | 2 +- lib/modules/sequence/layout/snap.dart | 61 + .../sequence}/render/bar_painter.dart | 93 +- .../sequence}/render/circular_painter.dart | 106 +- .../sequence}/render/flow_painter.dart | 13 +- lib/modules/sequence/sequence_module.dart | 113 + lib/{ => modules/sequence}/ui/ai_dialog.dart | 8 +- .../sequence}/ui/canvas_overlays.dart | 12 +- .../sequence}/ui/canvas_view.dart | 35 +- lib/modules/sequence/ui/sequence_ui.dart | 1588 +++++++++++ lib/modules/topo/topo_module.dart | 28 + lib/persistence/storage.dart | 2 +- lib/state/app_controller.dart | 121 +- lib/theme/tokens.dart | 2 +- lib/ui/app_shell.dart | 2350 +---------------- lib/ui/brand_menu.dart | 45 +- lib/ui/dialogs.dart | 114 +- lib/ui/home_view.dart | 14 +- lib/ui/update_dialog.dart | 47 +- lib/update/update_service.dart | 8 +- lib/version.dart | 2 +- pubspec.yaml | 13 +- scripts/build.bat | 23 +- scripts/publish_release.ps1 | 26 +- test/arch_export_test.dart | 6 +- test/arch_panel_test.dart | 4 +- test/arch_screenshots_test.dart | 15 +- test/arch_symbol_recognizer_test.dart | 4 +- test/arch_test.dart | 8 +- test/dep_routes_test.dart | 217 +- test/dependency_edit_test.dart | 83 + test/export_test.dart | 17 +- test/help_dialog_test.dart | 2 +- test/home_test.dart | 29 +- test/module_asset_manifest_test.dart | 13 + test/module_manifest_test.dart | 44 + test/roundtrip_test.dart | 4 +- test/sketch_test.dart | 8 +- test/snap_test.dart | 72 + test/station_test.dart | 4 +- test/symbol_library_test.dart | 2 +- test/widget_test.dart | 6 +- {tool => tools}/check_update.dart | 6 +- windows/CMakeLists.txt | 4 +- windows/runner/Runner.rc | 8 +- windows/runner/main.cpp | 2 +- 105 files changed, 6309 insertions(+), 3577 deletions(-) create mode 100644 assets/modules/architecture/module.json create mode 100644 assets/modules/elec/module.json create mode 100644 assets/modules/io/module.json create mode 100644 assets/modules/pid/module.json create mode 100644 assets/modules/registry.json create mode 100644 assets/modules/sequence/module.json create mode 100644 assets/modules/topo/module.json rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.10.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.11.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.12.md (100%) create mode 100644 docs/release-notes/RELEASE_NOTES_v1.3.13.md rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.4.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.5.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.6.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.7.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.8.md (100%) rename {release/notes => docs/release-notes}/RELEASE_NOTES_v1.3.9.md (100%) create mode 100644 lib/export/export_geometry.dart delete mode 100644 lib/layout/dep_routes.dart create mode 100644 lib/modules/README.md create mode 100644 lib/modules/architecture/architecture_module.dart rename lib/{arch => modules/architecture/domain}/arch_dxf.dart (99%) rename lib/{arch => modules/architecture/domain}/arch_export.dart (98%) rename lib/{arch => modules/architecture/domain}/arch_models.dart (99%) rename lib/{arch => modules/architecture/domain}/arch_painter.dart (99%) rename lib/{arch => modules/architecture/domain}/arch_recognizer.dart (100%) rename lib/{arch => modules/architecture/domain}/arch_samples.dart (100%) rename lib/{arch => modules/architecture/domain}/arch_symbol_recognizer.dart (98%) rename lib/{ => modules/architecture}/library/symbol_library.dart (100%) rename lib/{ => modules/architecture}/sketch/sketch_models.dart (100%) rename lib/{ => modules/architecture}/sketch/sketch_painter.dart (99%) rename lib/{ => modules/architecture}/sketch/sketch_solver.dart (100%) rename lib/{ => modules/architecture}/ui/arch_panel.dart (98%) rename lib/{ => modules/architecture}/ui/arch_view.dart (98%) create mode 100644 lib/modules/architecture/ui/architecture_ui.dart create mode 100644 lib/modules/elec/elec_module.dart create mode 100644 lib/modules/io/io_module.dart create mode 100644 lib/modules/manifest.dart create mode 100644 lib/modules/module.dart delete mode 100644 lib/modules/module_registry.dart create mode 100644 lib/modules/pid/pid_module.dart create mode 100644 lib/modules/registry.dart rename lib/{ => modules/sequence}/ai/ai_client.dart (80%) rename lib/{ => modules/sequence}/export/drawio_writer.dart (94%) rename lib/{ => modules/sequence}/export/export_fit.dart (56%) rename lib/{ => modules/sequence}/export/export_renderer.dart (91%) rename lib/{ => modules/sequence}/export/svg_writer.dart (97%) create mode 100644 lib/modules/sequence/layout/dep_routes.dart rename lib/{ => modules/sequence}/layout/flow_layout.dart (99%) rename lib/{ => modules/sequence}/layout/layout.dart (99%) create mode 100644 lib/modules/sequence/layout/snap.dart rename lib/{ => modules/sequence}/render/bar_painter.dart (91%) rename lib/{ => modules/sequence}/render/circular_painter.dart (90%) rename lib/{ => modules/sequence}/render/flow_painter.dart (95%) create mode 100644 lib/modules/sequence/sequence_module.dart rename lib/{ => modules/sequence}/ui/ai_dialog.dart (98%) rename lib/{ => modules/sequence}/ui/canvas_overlays.dart (99%) rename lib/{ => modules/sequence}/ui/canvas_view.dart (96%) create mode 100644 lib/modules/sequence/ui/sequence_ui.dart create mode 100644 lib/modules/topo/topo_module.dart create mode 100644 test/dependency_edit_test.dart create mode 100644 test/module_asset_manifest_test.dart create mode 100644 test/module_manifest_test.dart create mode 100644 test/snap_test.dart rename {tool => tools}/check_update.dart (86%) diff --git a/BUILD-NOTES.md b/BUILD-NOTES.md index f3036c0..5ab6ab4 100644 --- a/BUILD-NOTES.md +++ b/BUILD-NOTES.md @@ -127,10 +127,10 @@ flutter pub get flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-release.apk ``` -- 发布包归档:`release\sequence_diagram_android_v1.2.3_release.apk`(**本地保留,不入库**;exe 的 `dist\` 同理)。 +- 发布包归档:`..\release\android\ProcessDesignSuite_android_v1.3.13_release.apk`(**与源码根同级,本地保留,不入库**)。 - 上架应用商店时建议在 `android\app\build.gradle.kts` 配置正式签名后再构建 AAB: `flutter build appbundle --release`。 -- 应用名「时序图设计」、包名 `cc.sincos.sequence_diagram`、launcher 图标由 +- 应用名「PDS流程设计套件」、包名 `cc.sincos.sequence_diagram`、launcher 图标由 `tools\gen-android-icons.py` 生成(与桌面版「环序」标志同源)。 ### 正式签名 @@ -202,12 +202,12 @@ flutter test --update-goldens test\tablet_screenshots_test.dart # 重新生成 1. 同步版本号:`pubspec.yaml` 的 `version: V+build` 与 `lib/version.dart` 的 `kAppVersion`; 2. 构建:`flutter build apk --release`、`flutter build windows --release --no-tree-shake-icons`; -3. 归档:APK → `release\sequence_diagram_android_vV_release.apk`;绿色版 → `dist\`; -4. 写更新说明:`release\RELEASE_NOTES_vV.md`(用户可见的更新内容); +3. 归档:APK → `..\release\android\ProcessDesignSuite_android_vV_release.apk`;绿色版 → `..\release\windows\ProcessDesignSuite\`(含 `modules/`); +4. 写更新说明:`docs\release-notes\RELEASE_NOTES_vV.md`(用户可见的更新内容); 5. 发布到服务器(创建 Release + 上传 APK 与绿色版 zip 附件): ```powershell - powershell -File scripts\publish_release.ps1 -Version V -NotesFile release\RELEASE_NOTES_vV.md + powershell -File scripts\publish_release.ps1 -Version V -NotesFile docs\release-notes\RELEASE_NOTES_vV.md ``` 安装包以 Release 附件形式存放在服务器,**不进入 git 历史**,仓库保持精简。 \ No newline at end of file diff --git a/README.md b/README.md index 135d1e5..2859b1c 100644 --- a/README.md +++ b/README.md @@ -1,118 +1,515 @@ -# 时序图设计 · Sequence Diagram Studio +# PDS流程设计套件 · Process Design Suite -面向 **PLC 流程节拍设计 / 相位角设计** 的桌面设计软件(Flutter Desktop)。 +> 面向 PLC 流程节拍 / 相位角、系统架构与电气设计的桌面设计平台(Flutter Windows + Android)。 +> +> 本 README 同时是**开发指南**与**AI 开发提示词**:先读「模块化架构」和「新增模块」两节,再动手改代码。 -- **两种视图,一份数据**:条形节拍(甘特 / 流程图 + 依赖箭头) ⇄ 圆周节拍(同心圆相位图,12 点钟起始,一圈 = 一个循环,每新增一个动作在最外层加一层) -- **顺序一目了然**:绿色实线箭头 = FS 严格顺序(完成后启动),琥珀虚线 = SS 并行重叠(可提前启动),关键路径带 ★ -- **专业单位体系**:时间 `ms / s / min`、相位 `° / %`、显示精度可配,文档设置统一管理 -- **响应快**:自研 Canvas 渲染,双层缓存 + 脏区重绘 + 空间索引,1000 动作仍保持 60 fps -- **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致 -- **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES +--- -## 正式版 V1.2.3 +## 1. 当前状态 -**可运行的 Flutter Windows 桌面正式版**(源码在 `lib/`),设计人:呆头鹅。 +| 项 | 内容 | +| --- | --- | +| 版本 | `1.3.13` | +| 品牌 | PDS流程设计套件 / Process Design Suite(缩写 PDS) | +| 可执行文件 | `ProcessDesignSuite.exe` | +| 已开放模块 | 架构图设计、时序图设计 | +| 规划中模块 | 电器原理图、IO 表、拓扑图、PID 图(占位已注册,未开放) | +| 本地 release | `../release/windows/ProcessDesignSuite_windows_v1.3.13.zip`、`../release/android/ProcessDesignSuite_android_v1.3.13_release.apk`(与源码根同级) | +| 发布状态 | 本地构建,**未提交 / 未推送 / 未发布到 Gitea** | -**运行 / 构建** +数据目录与服务器仓库名保持兼容,未随品牌更名: -```bash +- 桌面数据:`%APPDATA%/EDC`(旧目录自动复制迁移) +- 安卓公共目录:`Documents/EDC` +- Gitea 更新仓库:`admin/EasyDesignCollection`(客户端更新地址依赖,见 `lib/update/update_service.dart`) + +--- + +## 2. 快速开始 + +### 2.1 环境 + +| 项 | 建议 | +| --- | --- | +| Flutter | 3.47.x(Dart 3.13.x) | +| Windows 构建 | Visual Studio Build Tools + CMake | +| Android 构建 | JDK 17 + Android SDK(platform 36 / build-tools 36) | +| 网络 | 国内建议 `FLUTTER_STORAGE_BASE_URL` / `PUB_HOSTED_URL` 镜像 | + +### 2.2 运行 / 构建 + +```powershell flutter pub get -flutter run -d windows # 开发调试 -scripts\build.bat # 发布版(构建并复制到浅目录 dist\) +flutter run -d windows +flutter build windows --release --no-tree-shake-icons +flutter build apk --release ``` -产物:`dist\sequence_diagram.exe`(直接 `flutter build windows --release` 则在 `build\windows\x64\runner\Release\`) +- Windows 绿色版产物:`build\windows\x64\runner\Release\ProcessDesignSuite.exe` +- `scripts\build.bat` 会构建并复制到同级 `../release/windows/ProcessDesignSuite/`(含模块清单) +- 安卓产物:`build\app\outputs\flutter-apk\app-release.apk` -**已实现功能** +> 本机若有绿盾等透明加密 DLP,请先阅读 [`BUILD-NOTES.md`](BUILD-NOTES.md); +> 仓库已内置 CMake 重命名与 `/MANIFEST:NO` 规避方案。 -- 条形节拍(甘特 / 流程图)+ 圆周节拍(同心圆)双视图,**共享同一份数据**,顶部一键切换 -- 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) -- 原创「环序 / Cycle-Step」应用标志(`tools/gen-icon.py` 生成,与工具栏 Logo 同源) +### 2.3 测试与静态检查 -> 若本机装有绿盾等透明加密软件,构建前请阅读 [`BUILD-NOTES.md`](BUILD-NOTES.md)(含规避方案)。 - -## 设计预览(2560 × 1440) - -**圆周节拍视图**(同心圆 · 12 点钟起始 · 顺序箭头) - -| 深色主题 | 浅色主题 | -| --- | --- | -| ![圆周节拍·深色](demo/circular-timing.png) | ![圆周节拍·浅色](demo/circular-timing-light.png) | - -**条形节拍视图**(甘特 / 流程图 · 依赖箭头) - -| 深色主题 | 浅色主题 | -| --- | --- | -| ![条形节拍·深色](demo/bar-timing.png) | ![条形节拍·浅色](demo/bar-timing-light.png) | - -**文档设置**(单位与精度 / 循环与相位 / 泳道 / 自动保存 / 换算表 / 编辑辅助) - -![工艺参数](demo/unit-settings.png) - -## 目录 - -| 路径 | 说明 | -| --- | --- | -| [`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)预览图 | -| `tools/demo-gen.mjs` | 示例图生成脚本(Node,输出 SVG) | - -## 重新生成示例图 - -```bash -node tools/demo-gen.mjs +```powershell +flutter analyze +flutter test test\home_test.dart test\widget_test.dart test\dep_routes_test.dart +flutter test # 截图 golden 用例会因本机字体 / 品牌变化而失败,按需 --update-goldens ``` -生成 5 个 SVG(深色 / 浅色 × 圆周 / 条形,加深色工艺参数面板),用任意浏览器或 Inkscape 可导出 2K PNG。 +--- -## 技术栈 +## 3. 产品能力(简版) -Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模型 + Command 撤销栈 · 纯 Dart 几何算法 · 自研 SVG 序列化器 · JSON(`.seq.json`)持久化 · 主题 Token 化(深浅双主题) +### 时序图设计 -## 安卓版(Android) +- 条形节拍 / 圆周节拍 / 流程图三视图,共享同一份时序数据。 +- FS / SS / FF / SF 依赖、关键路径、泳道与多槽位。 +- 动作条整体拖拽磁吸:起点 / 终点吸附最近动作端点、整 5°、相位分区边界。 +- 依赖连线默认从条块前端 / 后端端点引出;端部被遮挡时自动改从端部上 / 下角绕出。 +- 依赖关系可直接编辑(前置动作 / 类型 / 偏移时间),不必删除后重建。 +- AI 生成:DeepSeek `deepseek-flash` / `deepseek-v4-pro`;支持新建与增量修改。 -- **目标分辨率**:1280×800dp(2560×1600 物理),并动态兼容其它横竖屏分辨率; -- **无 license 授权**(面向应用商店分发);包名 `cc.sincos.sequence_diagram`,应用名「时序图设计」; -- **文件保存**:工程 / SVG / PNG 保存到系统公共目录(文件管理器可见,默认 `Documents/SequenceDiagram`,可在保存对话框「更改位置」中选择文档/下载/图片 + 自定义子文件夹;Android 10+ 走 MediaStore,无需权限); -- **导出格式**:固定 **1920×1080**,标题恒定左上、图例恒定左下,内容按包围盒自适应缩放居中(SVG / PNG 一致,exe 与安卓一致); -- **触控手势**:**单指点选选中动作,按住整体拖动移动**;选中后两端显示白色把手,抓把手拖动改时长(抓取目标加大);**双指捏合缩放 / 双指平移**(以捏合焦点为锚点);空白单指不平移;全屏无黑边(状态栏/导航栏区域融入界面); -- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装; -- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像: - ```bash - flutter build apk --release # 产物 → release/sequence_diagram_android_v1.2.3_release.apk - ``` -- **自测**:`test/tablet_layout_test.dart` 覆盖 1280×800、2560×1600、960×600、800×480、竖屏 800×1280、600×960 等 7 种分辨率的无溢出回归; -- **demo 图**:`demo/tablet-*.png`(由 `test/tablet_screenshots_test.dart` 生成)。 +### 架构图设计 -## 路线图 +- 手绘识别标准图元、正交连线、参数化草图、图层 / 符号库。 +- 导出 SVG / PNG / DXF(桌面)。 -- [ ] M1 数据模型 + 单位体系 + JSON 存取 + 条形视图(渲染 / 缩放 / 平移) -- [ ] M2 圆周视图 + 双视图切换动画 + 拖拽吸附 + 属性面板 + 撤销重做 -- [ ] M3 SVG / PNG 导出 + 依赖编辑 + 关键路径与统计 + 深浅主题 + Golden 测试 -- [ ] M4 PLC 点位对接(OPC UA / 三菱 MC / Modbus)+ 工艺卡 PDF + 自动节拍优化 +### 公共外壳 -## 关于 +- 空白启动首页、模块卡片、最近打开、品牌菜单。 +- 深浅主题、侧栏停靠 / 轨道 / 悬浮、全局快捷键。 +- 应用内更新(Gitea Release 附件)。 -- **软件**:时序图设计 · Sequence Diagram Studio -- **设计人**:呆头鹅 -- **版本**:V1.2.3 -- **版权**:Copyright © 2026 呆头鹅。保留所有权利。 -- **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md) +--- + +## 4. 模块化架构(核心) + +### 4.1 设计目标 + +1. **单一注册表**:所有功能模块只在一个文件登记:`lib/modules/registry.dart`。 +2. **模块独立路径**:每个模块的领域模型、布局、渲染、导出、UI 全部在 + `lib/modules//` 下。 +3. **外壳不识别具体模块**:`AppShell` / `HomeView` / 品牌菜单 / 窗口标题只依赖 + `EdcModule` 契约与注册表,不出现 `if (module == 'xxx')`。 +4. **新增模块不改外壳**:新增模块 = 新建模块目录 + 在注册表加一行。 +5. **共享内核**:主题、持久化、授权、更新、通用对话框留在 `lib/` 公共层。 + +### 4.2 注册表(唯一入口) + +```dart +// lib/modules/registry.dart +const List kModules = [ + architectureModule, + sequenceModule, + elecModule, // PlannedModule:未开放 + ioModule, + topoModule, + pidModule, +]; +``` + +首页卡片、品牌菜单、文档类型选择、窗口标题、文件后缀、最近打开、工作区 +全部由该列表驱动。 + +### 4.3 模块契约(`lib/modules/module.dart`) + +| 分类 | 成员 | 说明 | +| --- | --- | --- | +| 元数据 | `id / name / shortName / icon / accent / suffix / available / defaultName / blurb / enterStatus` | 首页、菜单、标题、文件类型 | +| 文档生命周期 | `newDocument / loadDocument / encodeDocument / documentName / filePath / isDirty / saveTo / markSaved` | 外壳统一处理打开 / 保存 / 最近列表 | +| 只读状态 | `isReadOnly` | 如时序图流程图视图 | +| 快捷键 | `buildShortcuts` | 与外壳公共快捷键合并 | +| 工作区 | `buildWorkspace` | 画布 / 主视图 | +| 侧栏 | `hasLeftPanel / buildLeftPanel / hasRightPanel / buildRightPanel` | 停靠 / 轨道 / 悬浮共用 | +| 工具栏 | `buildToolbarCenter / buildToolbarRight` | 模块专属工具 | +| 状态栏 | `buildStatusBar` | 底部状态信息 | +| 占位 | `PlannedModule` | 未开放模块的现成基类 | + +模块 UI 通过 `ModuleUiContext` 获取: + +- `context / controller / tokens` +- `compact / toolScale / toolFont`(工具栏布局) +- `leftRail / rightRail / leftPanelWidth / rightPanelWidth` +- `panelControls(left)`(外壳提供钉住 / 收起按钮) + +### 4.4 目录结构 + +```text +lib/ +├── main.dart # 启动、窗口标题、崩溃恢复 +├── version.dart # 版本号(与 pubspec 同步) +├── model/ # 共享文档容器(Project / 单位) +├── state/app_controller.dart # 共享状态:撤销 / 关键路径 / 自动保存 +├── persistence/ # 存储、最近列表、安卓公共目录 +├── theme/ # Tokens 主题 +├── license/ # 授权 +├── update/ # 应用内更新 +├── export/export_geometry.dart # 共享导出几何 / 纯白导出令牌 +├── assets/modules/ # 发布级模块清单(registry.json + 每模块 module.json) +├── ui/ # 共享外壳(不含具体模块 UI) +│ ├── app_shell.dart # 工具栏 / 侧栏停靠 / 快捷键 / 文件流程 +│ ├── home_view.dart # 首页(卡片来自注册表) +│ ├── brand_menu.dart # 品牌菜单(来自注册表) +│ ├── dialogs.dart # 通用对话框(文件 / 帮助 / 依赖编辑等) +│ └── app_logo.dart / update_*.dart +└── modules/ + ├── module.dart # EdcModule 契约 + ModuleUiContext + ├── registry.dart # ★ 唯一模块注册表 + ├── README.md # 模块开发速查 + ├── manifest.dart # 发布清单解析 / 合并 + ├── sequence/ # 时序图模块 + │ ├── sequence_module.dart # 模块入口(元数据 / 生命周期 / UI 委托) + │ ├── ai/ # DeepSeek 客户端 + │ ├── export/ # SVG / PNG / drawio 导出 + │ ├── layout/ # 条形 / 圆周 / 流程图布局、依赖走线、吸附 + │ ├── render/ # 三种视图绘制 + │ └── ui/ # CanvasView / Overlays / AI 对话框 / 模块 UI + ├── architecture/ # 架构图模块 + │ ├── architecture_module.dart + │ ├── domain/ # ArchDoc / 识别 / 绘制 / SVG / PNG / DXF + │ ├── sketch/ # 参数化草图 + │ ├── library/ # 符号库 + │ └── ui/ # ArchView / 面板 / 模块 UI + ├── elec/elec_module.dart # 规划中(PlannedModule) + ├── io/io_module.dart + ├── topo/topo_module.dart + └── pid/pid_module.dart +``` + +### 4.5 发布包模块架构(release) + +发布包不是「一堆散文件」,而是与源码一致的模块结构: + +```text +release/windows/ProcessDesignSuite/ +├── ProcessDesignSuite.exe +├── data/ ... +└── modules/ + ├── registry.json # ★ 发布级注册清单(顺序 / 名称 / 启用) + ├── architecture/module.json + ├── sequence/module.json + ├── elec/module.json + ├── io/module.json + ├── topo/module.json + └── pid/module.json +``` + +应用启动顺序: + +1. 桌面读取 exe 同级 `modules/registry.json`(发布包可见、可编辑); +2. 安卓 / 开发环境读取内置 `assets/modules/registry.json`; +3. 清单缺失或损坏时回退到编译期 `lib/modules/registry.dart`。 + +清单可调整模块顺序、显示名、颜色、启用状态;未编译进应用的模块会显示为 +「组件未安装」。Flutter release 的 Dart 代码是 AOT 编译的,**新增 UI 代码仍需 +重新构建应用**,清单负责发布级装配与可见结构。 + +### 4.6 依赖方向 + +```text +lib/ui/* (外壳) ──► modules/registry ──► modules/ + │ │ + └──────────► modules/module ◄────────┘ + │ +共享内核:model / state / persistence / theme / update / license +``` + +硬性规则: + +- `lib/ui/` **不得**直接 import 具体模块的内部文件;只通过注册表与契约。 +- 模块之间**不得**互相 import;需要共享的代码上移到共享内核或 `lib/export`。 +- 模块内部使用 `package:sequence_diagram/...` 绝对导入,移动文件不会破坏相对路径。 +- 新模块不得要求修改 `AppShell`、`HomeView`、`BrandMenu` 或 `AppMode`。 + +> 说明:`AppController` 仍是共享内核的集中状态容器(撤销 / 自动保存 / 架构草图等)。 +> 新模块通过契约的文档生命周期方法读写自己的文档;若需要复杂独立状态, +> 建议在模块目录内实现模块级 controller,并由模块 UI 持有。 + +--- + +## 5. 新增模块(Step-by-Step) + +以 `foo` 模块为例。 + +### 5.1 创建目录与模块入口 + +新建 `lib/modules/foo/foo_module.dart`: + +```dart +import 'package:flutter/material.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +const FooModule fooModule = FooModule(); + +class FooModule extends EdcModule { + const FooModule(); + + @override + String get id => 'foo'; + @override + String get name => '示例图'; + @override + String get shortName => '示例'; + @override + IconData get icon => Icons.widgets_outlined; + @override + int get accent => 0xFF38BDF8; + @override + String get suffix => '.foo.json'; + @override + bool get available => true; + @override + String get defaultName => '未命名-示例图'; + @override + String get blurb => '一句话简介'; + + @override + void newDocument(AppController c) { + // TODO: 初始化模块文档 + } + + @override + void loadDocument(AppController c, String source, {String? path}) { + // TODO: 解析 JSON 并写入文档 / 路径 + } + + @override + String encodeDocument(AppController c) => '{}'; + + @override + String documentName(AppController c) => '示例图'; + + @override + String? filePath(AppController c) => null; + + @override + bool isDirty(AppController c) => false; + + @override + Future saveTo(AppController c, String path) async {} + + @override + Future markSaved(AppController c, String displayPath) async {} + + @override + Widget buildWorkspace(ModuleUiContext ui) => + const Center(child: Text('Foo module')); + + @override + Widget buildStatusBar(ModuleUiContext ui) => + Text('示例图', style: TextStyle(color: ui.tokens.dim, fontSize: 11)); +} +``` + +### 5.2 可选:模块独立 UI + +把模块专属的工具栏 / 侧栏 / 状态栏放到 `lib/modules/foo/ui/foo_ui.dart`, +由 `buildToolbarCenter` / `buildToolbarRight` / `buildLeftPanel` 等钩子委托。 +参考: + +- `lib/modules/sequence/ui/sequence_ui.dart` +- `lib/modules/architecture/ui/architecture_ui.dart` + +### 5.3 注册(唯一需要修改的全局文件) + +```dart +// lib/modules/registry.dart +import '.../foo/foo_module.dart'; + +const List kModules = [ + architectureModule, + sequenceModule, + fooModule, // ← 新增 + ... +]; +``` + +完成后自动获得: + +- 首页模块卡片 / 品牌菜单 / 文档类型选择 +- 窗口标题「PDS流程设计套件 · 示例图设计」 +- 打开 / 保存 / 最近打开(使用模块 suffix 与生命周期) +- 侧栏停靠 / 轨道 / 悬浮(若模块提供面板) +- 模块快捷键合并 + +### 5.4 规划中模块 + +若模块尚未实现,直接继承 `PlannedModule` 并注册,首页会灰显「未开放」: + +```dart +class FooModule extends PlannedModule { + const FooModule() + : super( + id: 'foo', + name: '示例图', + shortName: '示例', + icon: Icons.widgets_outlined, + accent: 0xFF38BDF8, + suffix: '.foo.json', + defaultName: '未命名-示例图', + blurb: '一句话简介', + ); +} +``` + +### 5.5 自测清单 + +- [ ] `flutter analyze` 无问题 +- [ ] 首页出现模块卡片;未开放模块不可进入 +- [ ] 品牌菜单可进入模块 +- [ ] 新建 / 打开 / 保存 / 另存为 / 最近打开正常 +- [ ] 窗口标题切换正确 +- [ ] 侧栏 / 工具栏 / 状态栏(若提供)布局正常 +- [ ] `lib/ui/` 没有出现该模块的 `if` 分支 + +--- + +## 6. 文档与数据 + +| 内容 | 位置 / 格式 | +| --- | --- | +| 时序图文档 | `*.seq.json`(仅时序内容) | +| 架构图文档 | `*.arch.json`(仅架构内容) | +| 旧文档 | `.edc.json` 可继续打开 | +| 备份 | 保存时自动生成 `<文档>.bak` | +| 桌面自动快照 | `%APPDATA%/EDC/autosave/` | +| 最近打开 | `%APPDATA%/EDC/recent.json` | +| 素材库 | `%APPDATA%/EDC/library/` | +| 安卓公共目录 | `Documents/EDC`(兼容读取 `Documents/SequenceDiagram`) | + +> 文档协议版本:`edc/1.3`;新增字段必须提供 `fromJson` 安全默认值。 + +--- + +## 7. 构建、发布与更新 + +### 7.1 版本号 + +发版前**同时**修改: + +- `pubspec.yaml` 的 `version: x.y.z+build` +- `lib/version.dart` 的 `kAppVersion` + +### 7.2 Windows + +```powershell +scripts\build.bat +# 或 +flutter build windows --release --no-tree-shake-icons +``` + +产物:`ProcessDesignSuite.exe` + `data/` + `flutter_windows.dll` + 外部清单。 + +### 7.3 Android + +```powershell +flutter build apk --release +``` + +正式签名参数:`android/key.properties` + `android/key/release.jks`(不入库)。 + +### 7.4 本地 release 归档(源码同级) + +```text +E:\AiCodeGitea\ProcessDesignSuite\ +├── EasyDesignCollection/ # 源码仓库 +└── release/ # ★ 发布根目录(与源码总路径同级) + ├── windows/ + │ ├── ProcessDesignSuite/ # 绿色版整包(含 modules/) + │ └── ProcessDesignSuite_windows_v1.3.13.zip + ├── android/ + │ ├── ProcessDesignSuite_android_v1.3.13_release.apk + │ └── modules/ # 与 APK 内置清单一致的可见副本 + ├── source/ + │ └── ProcessDesignSuite_source_v1.3.13.zip + └── notes/ + └── RELEASE_NOTES_v1.3.13.md +``` + +### 7.5 发布到 Gitea(当前未执行) + +```powershell +powershell -File scripts\publish_release.ps1 -Version 1.3.13 ` + -NotesFile docs\release-notes\RELEASE_NOTES_v1.3.13.md +``` + +- 更新源:`http://124.220.63.9:30000/admin/EasyDesignCollection` +- 附件:安卓 `.apk`、Windows `.zip` +- 客户端逻辑:`lib/update/update_service.dart` / `lib/ui/update_dialog.dart` +- 旧版 v1.3.12 客户端只认 zip 内的 `EasyDesignCollection.exe`;若要从旧版 + **直接升级**到新 exe 名,需要额外兼容副本或先发布过渡版本。 + +--- + +## 8. 开发约定 / AI 开发提示词 + +> 以下规则适用于任何开发者与 AI 助手。 + +1. **先读三份文件**:`lib/modules/module.dart`、`lib/modules/registry.dart`、 + 当前模块目录下的 `*_module.dart`。 +2. **新增模块只改模块目录 + 注册表**;不要给外壳加模块专属 `if`,不要恢复 + `AppMode` 枚举或 `module_registry.dart`。 +3. **模块边界**: + - 模块专属代码放 `lib/modules//`; + - 模块之间不互相 import; + - 共享代码进 `lib/` 公共层,并在 README 说明。 +4. **导入风格**:统一使用 `package:sequence_diagram/...` 绝对导入。 +5. **UI 风格**:模块 UI 使用 `ModuleUiContext` 与 `Tokens`;不要硬编码颜色 / + 尺寸,优先复用 `Tokens` 与现有控件。 +6. **状态与文档**:共享状态在 `AppController`;新模块按契约实现 + `newDocument / loadDocument / encodeDocument / isDirty / saveTo / markSaved`。 +7. **兼容性**:文档 JSON 新增字段必须可缺省;不要破坏旧 `.edc.json` / `.seq.json` + / `.arch.json` 读取。 +8. **安全**:API Key 只在内存;不要把授权串、Key、密钥写入仓库或文档。 +9. **验证**:改完必须运行 `flutter analyze` 与相关测试;发版前跑完整非截图测试。 +10. **发版**:只改 `pubspec.yaml` / `lib/version.dart` 并同步 release notes; + 未经明确要求不要 commit / push / 发布 Release。 + +--- + +## 9. 已知约束与技术债 + +- `lib/ui/dialogs.dart` 仍是较大的共享对话框集合,其中包含部分时序图专属对话框; + 后续可继续拆分到 `modules/sequence/ui/`,但当前已通过接口与外壳解耦。 +- `Project` 共享文档容器同时持有 `ArchDoc`,属于模块文档聚合;模块 UI 与领域 + 代码已分离,后续可演进为独立文档段。 +- 自动保存仍集中在 `AppController` 并对架构图有路径分支;新模块若需要自动保存, + 建议在模块内实现或扩展内核。 +- 历史 golden 截图未随品牌 / 走线更新;`--update-goldens` 会修改 `demo/` 图片。 +- 历史 `docs/release-notes` 中的旧品牌名是历史记录,保留不改。 + +--- + +## 10. 规划 + +| 模块 | 状态 | 入口 | +| --- | --- | --- | +| 架构图设计 | 已开放 | `lib/modules/architecture/` | +| 时序图设计 | 已开放 | `lib/modules/sequence/` | +| 电器原理图 | 规划中 | `lib/modules/elec/` | +| IO 表 | 规划中 | `lib/modules/io/` | +| 拓扑图 | 规划中 | `lib/modules/topo/` | +| PID 图 | 规划中 | `lib/modules/pid/` | + +--- + +## 11. 文档索引 + +| 文档 | 内容 | +| --- | --- | +| [`lib/modules/README.md`](lib/modules/README.md) | 模块开发速查与模板 | +| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | 架构、数据流、关键算法 | +| [`docs/HELP.md`](docs/HELP.md) | 用户帮助 | +| [`BUILD-NOTES.md`](BUILD-NOTES.md) | 构建、签名、绿盾规避、发版流程 | + +--- + +## 12. 版权 + +Copyright © 2026 PDS流程设计套件(Process Design Suite)呆头鹅。保留所有权利。 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9438cde..44b9f36 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,9 +30,10 @@ android { // v1.3.10:sequence_diagram → cc.sincos.edc(首轮换身份); // v1.3.12:cc.sincos.edc → cc.sincos.yide(名称定为「EDC易得」后 // 再次换新身份,彻底刷新桌面名称)。 + // v1.3.13:品牌更名为「PDS流程设计套件」,applicationId 保持不变, + // 老用户可原地覆盖升级(桌面名称随应用 label 刷新)。 // 原因:部分安卓桌面会长期保留旧包身份的图标名(不随应用内更新刷新), // 换新身份安装 = 系统当作全新应用处理,桌面必然按新包内的名称生成图标。 - // 本次之后名称固定,不再变动。 // 注意:namespace 与 Kotlin 包名保持不变(仅 applicationId 变化),因此 // AndroidManifest 中组件类名需写全限定名(见 android:name)。 applicationId = "cc.sincos.yide" diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index e36ae83..a0ec2f0 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,7 +9,7 @@ 历史评估文档(1.3.5 时期)。当前模块化架构以 `README.md` / `docs/ARCHITECTURE.md` 为准; +> 文中 `AppMode` / `module_registry.dart` 已在 1.3.13 重构中移除。 + # EDC易得 架构升级评估(1.3.5 大版本) > 状态:P0 已实施(空白启动首页 + 模块注册表 + 文件路由 + 测试适配,全量 106 项通过); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0d51e29..8665e04 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,17 +1,19 @@ -# 架构文档 · 时序图设计(Sequence Diagram Studio) +# 架构文档 · PDS流程设计套件(Process Design Suite) -> 面向 PLC 流程节拍 / 相位角设计的 Flutter Windows 桌面软件。 -> 本文档描述代码结构、数据流、关键算法与**可优化点**,供后续性能与体验优化使用。 +> 面向 PLC 流程节拍 / 相位角、系统架构与电气设计的 Flutter 桌面平台。 +> 本文档描述**模块化注册架构**、数据流、关键算法与扩展方式。 +> 模块开发速查见 [`../lib/modules/README.md`](../lib/modules/README.md)。 --- -## 1. 产品定位与核心概念 +## 1. 产品与核心概念 -- **一份数据,两种视图**:条形节拍(甘特 / 流程图)⇄ 圆周节拍(同心圆相位图)。 -- **循环 = 一圈**:一个生产循环固定映射为 `360°` 与 `100%`;模型内部时间恒以**毫秒**存储。 -- **相位角**:`angle(deg) = ms / cycleMs × 360`,圆周图以 **12 点钟为 0°、顺时针**递增。 -- **动作分层**:每个动作占一条同心圆环,半径 `r = R0 + layer × pitch`;新增动作默认落在最外层。 -- **依赖约束**:`FS`(完成-启动,绿色实线)/ `SS`(起始-起始,琥珀虚线),用于关键路径计算。 +- **模块化设计合集**:首页一次列出所有注册模块;品牌菜单 / 文档类型 / 窗口标题 / + 文件后缀 / 最近打开全部由注册表驱动。 +- **一份数据,多种视图**(时序图):条形节拍、圆周节拍、流程图共享同一份时序数据。 +- **循环 = 一圈**:一个生产循环映射为 `360°` 与 `100%`;内部时间统一毫秒存储。 +- **依赖约束**:FS / SS / FF / SF,用于关键路径计算与连线语义。 +- **架构图**:手绘识别、正交连线、参数化草图、图层 / 符号库与多格式导出。 --- @@ -19,344 +21,284 @@ | 项 | 选型 | | --- | --- | -| UI 框架 | Flutter 3.x(Desktop, Windows) | +| UI 框架 | Flutter 3.47.x(Desktop Windows / Android) | | 渲染 | `CustomPainter` 自绘(无第三方图表库) | | 状态 | `ChangeNotifier`(`AppController`)+ 局部 `setState` | | 模型 | 不可变类 + `copyWith` / `toJson` / `fromJson` | -| 持久化 | 纯 `dart:io` 读写 JSON(`.seq.json`) | -| 导出 | 自研 SVG 序列化器 + `RepaintBoundary.toImage` 导出 PNG | -| 主题 | Token 化(`Tokens`),深/浅两套 | +| 持久化 | 纯 `dart:io` / Android 公共目录 JSON | +| 导出 | 自研 SVG / drawio / DXF 写入器 + Canvas 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`),保证面板不越出屏幕。 +1. **不引入原生插件**(无 `path_provider` / `file_selector`),文件对话框自研。 +2. 项目路径尽量不含中文(CMake 兼容性)。 +3. 透明加密 DLP 环境按 [`BUILD-NOTES.md`](../BUILD-NOTES.md) 规避。 +4. Windows 默认按主屏 94% 打开,保证侧栏不出屏。 --- -## 3. 目录结构与依赖方向 +## 3. 模块化注册架构 +### 3.1 核心文件 + +| 文件 | 职责 | +| --- | --- | +| `lib/modules/module.dart` | `EdcModule` 契约、`ModuleUiContext`、`PlannedModule` | +| `lib/modules/registry.dart` | **唯一注册表**:`kModules` / `moduleById` / `moduleTitle` | +| `lib/modules//_module.dart` | 模块入口:元数据 + 文档生命周期 + UI 委托 | +| `lib/modules//ui/*_ui.dart` | 模块工具栏 / 侧栏 / 状态栏实现(可选) | +| `lib/ui/app_shell.dart` | 通用外壳:快捷键 / 文件流程 / 侧栏停靠,不含具体模块分支 | + +### 3.2 注册表 + +```dart +const List kModules = [ + architectureModule, + sequenceModule, + elecModule, // PlannedModule + ioModule, + topoModule, + pidModule, +]; ``` + +新增模块只改这一处全局文件;`HomeView` / `BrandMenu` / 文档类型对话框 / +`main.dart` 窗口标题均从注册表读取。 + +### 3.3 模块契约 + +| 分类 | 成员 | +| --- | --- | +| 元数据 | `id / name / shortName / icon / accent / suffix / available / defaultName / blurb / enterStatus` | +| 文档 | `newDocument / loadDocument / encodeDocument / documentName / filePath / isDirty / saveTo / markSaved` | +| 只读 | `isReadOnly(c)` | +| 快捷键 | `buildShortcuts(ui)` | +| UI | `buildWorkspace / buildToolbarCenter / buildToolbarRight / buildLeftPanel / buildRightPanel / buildStatusBar` | +| 侧栏开关 | `hasLeftPanel / hasRightPanel` | +| 规划中 | `PlannedModule` 基类 | + +`ModuleUiContext` 提供 `context / controller / tokens / compact / toolScale / +toolFont / leftRail / rightRail / leftPanelWidth / rightPanelWidth / +panelControls(left)`。 + +### 3.4 发布级模块清单 + +源码模板:`assets/modules/registry.json` + `assets/modules//module.json`。 +构建后复制到发布包 `modules/`(Windows 与 exe 同级;安卓打包进 APK assets)。 + +启动顺序: + +1. 桌面 exe 同级 `modules/registry.json`; +2. 安卓 / 开发环境 `assets/modules/registry.json`; +3. 失败回退 `lib/modules/registry.dart` 的 `kCompiledModules`。 + +清单控制模块顺序、显示名、颜色、启用状态;未编译模块显示「组件未安装」。 +Flutter AOT 限制:清单不能动态加载新的 Dart UI 代码,新增代码仍需重新构建。 + +### 3.5 外壳职责 + +- 首页(`HomeView`):模块卡片、最近打开。 +- 品牌菜单(`BrandMenuButton`):首页 / 已开放模块 / 未开放模块 / 软件设置。 +- 工具栏:品牌、新建 / 打开 / 保存、撤销 / 重做、模块中段工具、模块右侧工具、 + 侧栏开关、帮助 / 更新 / 主题。 +- 文件流程:打开 / 保存 / 另存为 / 最近列表(使用模块 suffix 与生命周期方法)。 +- 侧栏停靠 / 轨道 / 悬浮;模块只提供面板内容。 +- 全局快捷键 + 模块快捷键合并。 +- 窗口标题:`PDS流程设计套件 · <模块名>设计`。 + +--- + +## 4. 目录结构与依赖方向 + +```text 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 同源) +├── main.dart +├── version.dart +├── model/ # 共享文档容器:Project / 单位 +├── state/app_controller.dart # 共享状态:撤销 / 关键路径 / 自动保存 +├── persistence/ # 存储 / 最近列表 / 安卓公共目录 +├── theme/ # Tokens +├── license/ # 授权 +├── update/ # 应用内更新 +├── export/export_geometry.dart# 共享导出几何 / 纯白令牌 +├── ui/ # 共享外壳 +│ ├── app_shell.dart +│ ├── home_view.dart +│ ├── brand_menu.dart +│ ├── dialogs.dart +│ └── app_logo.dart / update_*.dart +└── modules/ + ├── module.dart + ├── registry.dart + ├── README.md + ├── sequence/ # 时序图 + │ ├── sequence_module.dart + │ ├── ai/ export/ layout/ render/ ui/ + ├── architecture/ # 架构图 + │ ├── architecture_module.dart + │ ├── domain/ sketch/ library/ ui/ + └── elec/ io/ topo/ pid/ # 规划中占位 ``` -**依赖方向(单向,无环)** +依赖方向: -``` -model ◄── layout ◄── render - ▲ ▲ ▲ - │ │ │ -state ──────┴──── export - ▲ - │ -ui ──► theme +```text +lib/ui/* ──► modules/registry ──► modules/ + │ │ + └────────► modules/module ◄─────┘ + │ +共享内核:model / state / persistence / theme / update / license ``` -- `model` 是最底层,不依赖任何其它模块。 -- `state` 只依赖 `model` + `persistence`。 -- `render` 依赖 `model` + `layout` + `theme`(纯绘制,无状态)。 -- `ui` 依赖以上全部,负责交互与组合。 +规则: + +- `lib/ui/` 不 import 具体模块内部文件;只通过注册表与契约。 +- 模块之间不互相 import;共享代码上移到公共层。 +- 模块内部统一 `package:sequence_diagram/...` 绝对导入。 +- 新模块不需要修改外壳,也不需要恢复 `AppMode` 枚举。 --- -## 4. 数据模型(`model/models.dart`) +## 5. 文档模型与数据流 -### 4.1 实体 +### 5.1 时序图模型(`lib/model/models.dart`) -| 类型 | 说明 | +| 实体 | 说明 | | --- | --- | -| `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 | +| `Project` | 名称 / schema / Cycle / Station[] / Action[] / UnitSettings / ViewState / PhaseZone[] / 架构图聚合 | +| `Action` | id / name / stationId / driver / startAngle / durationAngle / layer / row / color / deps[] | +| `Dependency` | fromId / toId / type(FS/SS/FF/SF) / offsetAngle(内部角度,界面以时间显示/编辑) / routeOffset | +| `Station` | id / name / order / color | +| `Cycle` | durationMs / startAngle / direction / origin / snapDeg | +| `UnitSettings` | 时间 / 相位单位、精度、吸附、泳道策略 | +| `ViewState` | 视图模式、缩放、平移、显示开关、选择 | -### 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`、`°/%` 不修改任何模型数值。 +- 不可变对象 + `copyWith`,撤销栈保存整份 `Project` 快照。 +- 时间统一毫秒;角度 `0–360°`,允许跨圈 `endAngle > 360`。 +- JSON 协议 `edc/1.3`;新增字段必须有安全默认值。 +- 时序图保存 `includeArch: false`;架构图单独 `*.arch.json`。 + +### 5.2 架构图模型(`lib/modules/architecture/domain/arch_models.dart`) + +- `ArchDoc`:图层 / 图形 / 连线 / 墨迹 / 草图 / 视图状态。 +- 草图模型在 `modules/architecture/sketch/`,求解器与约束独立。 + +### 5.3 数据流 + +```text +用户手势 / 模块 UI + │ + ▼ +AppController(唯一可变状态 + 撤销栈 + 关键路径) + │ notifyListeners + ▼ +模块 UI(CanvasView / ArchView / 侧栏 / 状态栏) + │ + ▼ +布局(layout) → 绘制(render) → 导出(export) +``` + +模块文档生命周期由 `EdcModule` 实现: + +- 新建:`newDocument(c)` +- 打开:`loadDocument(c, source, path:)` +- 保存:`encodeDocument(c)` / `saveTo(c, path)` / `markSaved(c, displayPath)` +- 最近列表:外壳使用模块 id + 路径记录。 --- -## 5. 状态与业务逻辑(`state/app_controller.dart`) +## 6. 关键算法 -`AppController extends ChangeNotifier`,是整个应用唯一的可变状态源。 +### 6.1 条形 / 圆周 / 流程图布局 -### 5.1 职责 +- `modules/sequence/layout/layout.dart`:条形行高、泳道槽位、极坐标与命中测试。 +- `modules/sequence/layout/flow_layout.dart`:流程图节点 / 连线 / 标签布局。 +- `modules/sequence/layout/dep_routes.dart`: + - FS / FF 从源后端(右端)出发,SS / SF 从前端(左端)出发; + - 目标端按 FS/SS 取前端、FF/SF 取后端; + - 默认从端点中心引出;端部被遮挡或语义端背向时退到端部上 / 下角; + - 同泳道 / 相邻泳道 / 跨多行三种走线,含自动错开与手动 `routeOffset`。 +- `modules/sequence/layout/snap.dart`:整体拖拽的起点 / 终点双端吸附。 -- 持有当前 `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`。 +### 6.2 关键路径 -### 5.2 关键路径算法(`_recomputeCritical`) +`AppController._recomputeCritical`: -用于高亮“累计最长链”。步骤: +1. 统计入度 / 邻接表; +2. Kahn 拓扑排序(环时回退原始顺序); +3. 计算最早开始时间(FS / SS / FF / SF 偏移); +4. 回溯最长路径,得到 `criticalActions` / `criticalDeps`。 -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`。 +### 6.3 渲染 -复杂度 `O(V + E)`,每次编辑重算,当前规模(数十动作)无压力。 +- `modules/sequence/render/bar_painter.dart`:条形节拍、泳道分隔线、依赖、标签。 +- `modules/sequence/render/circular_painter.dart`:同心圆弧、相位刻度、依赖弧。 +- `modules/sequence/render/flow_painter.dart`:流程图只读渲染。 +- `modules/architecture/domain/arch_painter.dart` + `sketch/sketch_painter.dart`。 -### 5.3 自动保存 +### 6.4 导出 -- `start()` 启动 `Timer.periodic(5s)` → `Storage.writeAutosave(...)`。 -- 退出时 `AppLifecycleListener.onExitRequested` 调用 `markCleanOnExit()` 写入“干净”快照。 -- 启动时 `main.dart` 检查 `Storage.checkRecovery()`,若上次非正常退出则弹恢复向导。 +- 共享几何:`lib/export/export_geometry.dart`(1920×1080 / 2x / `ExportFit`)。 +- 时序图:SVG / PNG / drawio,位于 `modules/sequence/export/`。 +- 架构图:SVG / PNG / DXF,位于 `modules/architecture/domain/`。 --- -## 6. 布局与坐标系统(`layout/layout.dart`) +## 7. 持久化 / 更新 -纯函数 + 布局类,**不依赖 Flutter Widget**(只用 `Offset/Rect/Size/Path`)。 +### 7.0 发布目录 -### 6.1 条形布局 `BarLayout` +发布根目录与源码根同级:`../release/`,包含 `windows/`、`android/`、`source/` +与 `notes/`。Windows 绿色版内含 `modules/` 清单目录;Android APK 内含 +`assets/modules/`。 -| 常量 | 值 | 说明 | -| --- | --- | --- | -| `leftGutter` | 300 | 左侧标题列宽度(**关键**:避免文字压到条形块) | -| `topPad` | 210 | 第一行动作的 y | -| `barH` | 34 | 条形高度 | -| `rowVisual` | 50 | 行条纹/背景高度 | -| `bottomReserve` | 350 | 为底部统计/工具浮层预留的高度 | -| `pitch` | 动态 46–66 | `(height − topPad − bottomReserve) / n` 后 clamp | +### 7.1 持久化 -- `plotLeft = leftGutter`,`plotRight = width − 56`。 -- `xFor(deg) = plotLeft + deg/360 × span`;`yFor(i) = topPad + i × pitch`。 -- `ordered` 排序键:工位 `order` → `startAngle` → `id`。 -- `hitTest` 线性扫描所有行(见 §12 优化点)。 +- 桌面:`%APPDATA%/EDC`;自动快照、`recent.json`、`library/`。 +- 安卓:公共目录 `Documents/EDC`,MediaStore 写入。 +- 保存时生成 `.bak`;异常退出启动恢复。 +- 数据目录保持 EDC 旧名以兼容历史数据,不随品牌更名。 -### 6.2 圆周布局 `CircularLayout` +### 7.2 应用内更新 -- 圆心默认画布中心(下移 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`。 +- 更新源:Gitea `admin/EasyDesignCollection` 的 Releases。 +- 平台安装包:安卓 `.apk`,Windows `.zip` 绿色版。 +- 版本比较:`lib/update/update_service.dart` 的 `isNewerVersion`。 +- Windows 原地覆盖脚本会同时等待旧 `EasyDesignCollection.exe` 与新 + `ProcessDesignSuite.exe` 退出,并清理旧文件。 --- -## 7. 渲染层(`render/*`) +## 8. 性能与优化点 -### 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 琥珀、关键路径青)。 +- 画布双层缓存 + 脏区重绘 + 空间索引;1000 动作仍保持 60 fps。 +- 条形布局按泳道 / 槽位一次性计算;依赖走线缓存同一份几何供绘制 / 命中 / 拖拽。 +- 布局层纯函数,便于单测与缓存。 +- 大文档导出使用固定画布 + 等比缩放,避免裁切。 --- -## 8. UI 层(`ui/*`) +## 9. 扩展指南 -### 8.1 `AppShell`(外壳) +新增模块请直接阅读 [`../lib/modules/README.md`](../lib/modules/README.md): -- **快捷键**:`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°` 换算、当前状态。 +1. 新建 `lib/modules//`; +2. 实现 `EdcModule` 或继承 `PlannedModule`; +3. 在 `lib/modules/registry.dart` 注册; +4. 补测试。 -### 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 个分页(快速开始 / 界面与侧栏 / 操作与快捷键 / 双视图 / 单位与导出)。 +**禁止**:为新增模块修改 `AppShell`、恢复 `AppMode` 枚举、在共享外壳中写 +模块专属 `if`、模块之间互相 import。 --- -## 9. 导出 +## 10. 已知技术债 -### 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°,跨越循环边界 | -| 泳道 | 条形视图中按工位分组的行 | -| 层 | 圆周视图中动作所在的同心圆环 | +- `lib/ui/dialogs.dart` 仍包含部分时序图专属对话框,后续可迁移到 + `modules/sequence/ui/`。 +- `Project` 作为共享文档容器聚合 `ArchDoc`;模块领域 / UI 已分离。 +- 自动保存仍在 `AppController` 内集中处理,新模块如需自动保存可扩展内核。 +- 历史 golden 截图未随品牌 / 走线更新。 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 8f1a61e..4de4a33 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,3 +1,5 @@ +> 说明:依赖偏移在界面中以**时间**为主显示/编辑(如 `SS+0.33 s`);文中的角度值是内部换算或历史设计示例。 + # 时序图设计(Sequence Diagram Studio)设计文档 > PLC 流程节拍设计 / 相位角设计软件 diff --git a/docs/HELP.md b/docs/HELP.md index 5de6e2f..46ea52a 100644 --- a/docs/HELP.md +++ b/docs/HELP.md @@ -1,7 +1,7 @@ -# EDC易得 · 帮助手册(1.3.5) +# PDS流程设计套件 · 帮助手册(1.3.13) -> 本手册对应 1.3.5 大版本(软件已更名 EDC易得,仓库 EasyDesignCollection)。 -> 本次更新变化较大,**新功能可能仍存在较多 bug 与问题**,欢迎反馈: +> 本手册对应 1.3.13 版本(软件品牌:PDS流程设计套件 · Process Design Suite)。 +> 新功能可能仍存在较多 bug 与问题,欢迎反馈: > 开发者邮箱 liuyu65@126.com · 微信 online-goose。 --- @@ -123,8 +123,14 @@ 右键菜单复制 / 删除 / 加依赖。 - **工位与泳道**:工位 = 谁在做(可增删改排序);泳道 = 执行器轨道; 泳道可加宽 1–5 槽(双击泳道编号),支持换道 + 换槽位拖拽。 -- **依赖**:FS 绿色实线(完成后启动)/ SS 琥珀虚线(可提前启动,+n°); +- **依赖**:FS 绿色实线(完成后启动)/ SS 琥珀虚线(可提前启动,+偏移时间如 +0.33s); + FS / SS / FF / SF 按语义从条块前端 / 后端端点引出,端部被遮挡时自动从 + 上 / 下角绕出;前后动作紧贴时自动隐藏连线与箭头,只在接缝处显示依赖标签; 重叠连线可拖拽错开,双击复位。 +- **依赖编辑**:右侧「前置依赖 / 后续依赖」每行有编辑按钮,可直接修改前置动作、 + 类型与偏移时间,无需删除后重新添加;手动拖拽的走线偏移会保留。 +- **磁吸**:条形整体左右拖动、圆周整体旋转时,起点 / 终点会吸附最近上下游 + 动作端点、整 5° 与相位分区边界,并显示参考虚线;圆周容差按半径自适应。 - **相位分区**:命名工艺阶段(上料 / 加工 / 检测…),条形 / 圆周 / 流程图同步展示。 - **三视图**:条形节拍 / 圆周节拍 / 流程图(流程图自动生成、只读); 切换自动适应窗口;Ctrl+滚轮缩放。 @@ -175,10 +181,10 @@ 按产品约定连线**一律正交**(横平竖直);需要斜段请用「手绘」画直线图形。 **Q:升级后桌面出现两个图标 / 名称还是旧的?** -1.3.12 起应用换了新身份(`cc.sincos.yide`),系统会当作**全新应用**安装: -桌面新图标即 `EDC易得`;旧图标(时序图设计 / EDC|易得设计)长按全部卸载即可。 -项目文件保存在公共文档目录(`Documents/SequenceDiagram`),不受影响。 +1.3.12 起应用使用应用身份 `cc.sincos.yide`,本版品牌更名为 **PDS流程设计套件**: +若桌面名称未刷新,可长按旧图标卸载后重装;项目文件保存在公共文档目录 +(`Documents/SequenceDiagram`),不受影响。 **Q:1.3.12 之后怎么更新?** -仍从首页 / 工具栏「检查更新」下载安装,此后都在新身份上**原地覆盖更新** -(名称已固定为 EDC易得,不会再需要换身份重装)。 +仍从首页 / 工具栏「检查更新」下载安装,此后都在同一身份上**原地覆盖更新** +(品牌固定为 PDS流程设计套件,不需要再换身份重装)。 diff --git a/release/notes/RELEASE_NOTES_v1.3.10.md b/docs/release-notes/RELEASE_NOTES_v1.3.10.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.10.md rename to docs/release-notes/RELEASE_NOTES_v1.3.10.md diff --git a/release/notes/RELEASE_NOTES_v1.3.11.md b/docs/release-notes/RELEASE_NOTES_v1.3.11.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.11.md rename to docs/release-notes/RELEASE_NOTES_v1.3.11.md diff --git a/release/notes/RELEASE_NOTES_v1.3.12.md b/docs/release-notes/RELEASE_NOTES_v1.3.12.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.12.md rename to docs/release-notes/RELEASE_NOTES_v1.3.12.md diff --git a/docs/release-notes/RELEASE_NOTES_v1.3.13.md b/docs/release-notes/RELEASE_NOTES_v1.3.13.md new file mode 100644 index 0000000..4e4cf53 --- /dev/null +++ b/docs/release-notes/RELEASE_NOTES_v1.3.13.md @@ -0,0 +1,77 @@ +# V1.3.13 更新内容 + +> 本次为 **AI 生成修复 + 品牌更名版**:软件更名为 **PDS流程设计套件**(Process Design Suite), +> 同时修复 AI 生成时序图报错、无法修改当前图形的问题。 + +## 1. AI 生成修复(本次核心) + +- **模型接口升级**:DeepSeek 已下线 `deepseek-chat` / `deepseek-reasoner`, + 本版改用当前模型 `deepseek-flash`(快速)与 `deepseek-v4-pro`(深度推理); + 此前旧模型 id 会直接返回 400 错误,导致「一开始生成就报错」。 +- **修改当前工程不再丢图**:AI 修改模式只把时序内容交给模型,返回后与原工程 + 合并,**架构图、画布缩放 / 平移、泳道与自动保存设置原样保留**。 +- **工位兜底**:模型漏写工位或编造不存在的工位时自动补齐 / 归位,避免整组 + 动作在图上消失。 +- **错误提示更清楚**:接口报错时直接显示 DeepSeek 返回的原因,并区分 + Key 无效(401)、余额不足(402)、请求过频(429)。 + +## 2. 品牌更名:PDS流程设计套件 + +- 窗口标题、桌面 / 安卓应用名、应用内品牌、关于页、导出图签统一改为 + **PDS流程设计套件**(英文 **Process Design Suite**,缩写 **PDS**); +- Windows 可执行文件更名为 `ProcessDesignSuite.exe`,发布包更名为 + `ProcessDesignSuite_*`;应用内更新已同步适配新旧文件名; +- 数据目录(`%APPDATA%/EDC`、`Documents/EDC`)保持不变,**不影响已有工程与设置**。 + +## 3. 模块化架构 + +- 全软件改为**注册模块式架构**:每个模块拥有独立目录(`lib/modules//`), + 通过唯一注册表 `lib/modules/registry.dart` 加入;应用外壳不再硬编码具体模块。 +- 首页、品牌菜单、窗口标题、文档打开 / 保存 / 最近列表、工具栏、侧栏与状态栏 + 均自动跟随注册表;后续电气 / IO / 拓扑 / PID 等模块可直接按目录扩展。 +- 详细开发指南见 `README.md` 与 `lib/modules/README.md`。 +- 发布包同步采用模块结构:Windows 绿色版含 `modules/registry.json` + + `modules//module.json`;安卓 APK 内置同一份模块清单。可在发布清单中 + 调整模块顺序 / 显示名 / 启用状态;未编译模块显示「组件未安装」。 + +## 4. 时序图交互完善 + +- **动作条整体磁吸**:左右拖动动作条时,起点 / 终点会同时吸附到最近上下游 + 动作条端点、整 5° 与相位分区边界,并显示竖向参考虚线(此前只有拖拽长度 + 有磁吸)。 +- **依赖连线端点规则**:FS / SS / FF / SF 默认从动作条的前端 / 后端端点引出; + 当端部临近被其它动作条遮挡时,自动改从端部的上 / 下角引出并绕行,避免 + 连线压住条块。 +- **已有依赖可直接编辑**:右侧「前置依赖 / 后续依赖」每行新增编辑按钮,可修改 + 前置动作、依赖类型(FS / SS / FF / SF)与偏移时间,不再需要删除后重新添加; + 手动拖拽过的走线偏移会保留。 +- **泳道分隔线加深**:泳道之间的横向分隔线颜色加深,多槽位泳道的槽位分隔虚线 + 也略微增强,泳道边界更清楚。 +- **泳道标题间距**:主标题与副标题(工位 / 驱动 / 动作数)拉开间距,不再挤在 + 一起。 +- **依赖标签修复**:FS / SS 等依赖标签始终位于两个动作之间,不再因行程过短 + 被挪到目标动作条上方;标签统一避开动作条。 +- **依赖偏移改为时间主显示/编辑**:SS+0.33 s 等,角度仅内部换算;修改循环 + 时长时依赖偏移的时间保持不变。 +- **前后贴紧依赖**:两个动作前后紧贴时,自动隐藏连线与箭头,只在接缝处显示 + FS / SS 等依赖标签,避免线条挤在动作之间。 +- **圆周依赖标签**:紧贴 / 同环依赖自动隐藏圆弧与箭头,标签放在连接位置 + (环间空隙)并沿圆弧切线方向排列;短弧动作标签优先保留动作名。 +- **圆周动作磁吸增强**:整体旋转圆形动作时,起点 / 终点同时吸附动作端点、 + 整 5° 与相位分区边界,容差按半径自适应,并显示径向参考虚线。 + +## 5. 更新方式 + +- 应用内:打开应用 → 首页 / 工具栏「检查更新」→ 立即更新; +- 手动:Release 页下载 + `ProcessDesignSuite_android_v1.3.13_release.apk` 或 + `ProcessDesignSuite_windows_v1.3.13.zip`。 + +## 6. 复验点 + +1. 打开「时序图设计」→ 顶部「AI 生成」→ 填 Key → 选 Flash / Pro → 生成; +2. 「新建工程」应正常生成并替换当前图; +3. 「修改当前工程」应正常增删改动作,且原有架构图与画布视图不被清空; +4. 左右拖动动作条,靠近上下游条端点时应出现磁吸与竖向虚线; +5. 带有前后遮挡的 FS / SS 连线应从端部上下角引出; +6. 关于页与窗口标题应显示 **PDS流程设计套件 / v1.3.13**。 diff --git a/release/notes/RELEASE_NOTES_v1.3.4.md b/docs/release-notes/RELEASE_NOTES_v1.3.4.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.4.md rename to docs/release-notes/RELEASE_NOTES_v1.3.4.md diff --git a/release/notes/RELEASE_NOTES_v1.3.5.md b/docs/release-notes/RELEASE_NOTES_v1.3.5.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.5.md rename to docs/release-notes/RELEASE_NOTES_v1.3.5.md diff --git a/release/notes/RELEASE_NOTES_v1.3.6.md b/docs/release-notes/RELEASE_NOTES_v1.3.6.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.6.md rename to docs/release-notes/RELEASE_NOTES_v1.3.6.md diff --git a/release/notes/RELEASE_NOTES_v1.3.7.md b/docs/release-notes/RELEASE_NOTES_v1.3.7.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.7.md rename to docs/release-notes/RELEASE_NOTES_v1.3.7.md diff --git a/release/notes/RELEASE_NOTES_v1.3.8.md b/docs/release-notes/RELEASE_NOTES_v1.3.8.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.8.md rename to docs/release-notes/RELEASE_NOTES_v1.3.8.md diff --git a/release/notes/RELEASE_NOTES_v1.3.9.md b/docs/release-notes/RELEASE_NOTES_v1.3.9.md similarity index 100% rename from release/notes/RELEASE_NOTES_v1.3.9.md rename to docs/release-notes/RELEASE_NOTES_v1.3.9.md diff --git a/lib/export/export_geometry.dart b/lib/export/export_geometry.dart new file mode 100644 index 0000000..945f5b0 --- /dev/null +++ b/lib/export/export_geometry.dart @@ -0,0 +1,84 @@ +/// 导出画布的共享几何约束:固定 1920×1080、2 倍像素比、内容区与 +/// 缩放/平移结果 [ExportFit]。 +/// +/// 架构位置:`lib/export/` 为共享导出层,不依赖任何具体模块;时序图与 +/// 架构图模块各自的导出逻辑都复用这里的常量与 [ExportFit]。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/theme/tokens.dart'; + +/// 导出画布尺寸(固定逻辑尺寸)。 +const Size kExportSize = Size(1920, 1080); + +/// 导出渲染像素比:按 2 倍渲染成 3840×2160,保证高分辨率打印清晰。 +const double kExportPixelRatio = 2.0; + +/// 导出内容区域(标题/图例之外的内容区)。 +const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016); + +/// 导出内容变换:`scale` + `translate(tx, ty)`。 +class ExportFit { + /// 构造内容变换。 + const ExportFit(this.scale, this.tx, this.ty); + + /// 缩放系数。 + final double scale; + + /// 水平平移。 + final double tx; + + /// 垂直平移。 + final double ty; + + /// SVG transform 属性值。 + String get svgTransform => + 'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})'; +} + +/// 导出专用令牌:始终使用浅色、纯白背景(印刷 / 工艺卡导向), +/// 文字、语义色与屏幕浅色主题保持一致。 +Tokens exportTokens(Tokens base) { + return Tokens( + brightness: Brightness.light, + bg: Colors.white, + canvas1: Colors.white, + canvas2: Colors.white, + chrome: base.chrome, + panel: Colors.white, + panel2: Colors.white, + dialog: Colors.white, + line: base.line, + line2: base.line2, + text: base.text, + text2: base.text2, + sub: base.sub, + dim: base.dim, + accent: base.accent, + accent2: base.accent2, + ok: base.ok, + warn: base.warn, + danger: base.danger, + fs: base.fs, + ss: base.ss, + crit: base.crit, + chip: Colors.white, + dial: Colors.white, + arcText: base.arcText, + onAccent: base.onAccent, + ringA: base.ringA, + ringB: base.ringB, + ringEdge: base.ringEdge, + ringLabel: base.ringLabel, + info: Colors.white, + track: base.track, + sel: base.sel, + grid: base.grid, + shadow: base.shadow, + shadowOp: 0.10, + selOutline: base.selOutline, + overlay: base.overlay, + tailOp: base.tailOp, + ); +} diff --git a/lib/layout/dep_routes.dart b/lib/layout/dep_routes.dart deleted file mode 100644 index 9175333..0000000 --- a/lib/layout/dep_routes.dart +++ /dev/null @@ -1,360 +0,0 @@ -/// 依赖连线的共享走线计算。 -/// -/// 条形视图 / 圆周视图的**画布绘制、标签放置与命中测试**(点选连线、 -/// 沿法线拖拽调整走线)都使用这里的同一份几何,避免绘制与命中不一致: -/// - 自动错开:同一走线分组内的多条依赖依次错开,先解决“完全重叠”; -/// - 手动偏移:[Dependency.routeOffset] 叠加在自动错开之上(拖拽连线的结果)。 -library; - -import 'dart:math' as math; -import 'dart:ui'; - -import '../model/models.dart'; -import 'layout.dart'; - -// ===================== 通用工具 ===================== - -/// 点 [p] 到线段 [a]–[b] 的最短距离。 -double distanceToSegment(Offset p, Offset a, Offset b) { - final Offset ab = b - a; - final double len2 = ab.dx * ab.dx + ab.dy * ab.dy; - if (len2 <= 0) return (p - a).distance; - final double t = (((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2).clamp(0.0, 1.0); - return (p - (a + ab * t)).distance; -} - -/// 点 [p] 到折线 [pts] 的最短距离。 -double distanceToPolyline(List pts, Offset p) { - double best = double.infinity; - for (int i = 0; i + 1 < pts.length; i++) { - final double d = distanceToSegment(p, pts[i], pts[i + 1]); - if (d < best) best = d; - } - return best; -} - -/// 点 [p] 到路径 [path] 的近似最短距离(按弧长采样,步长 [step])。 -double distanceToPath(Path path, Offset p, {double step = 4}) { - double best = double.infinity; - for (final PathMetric m in path.computeMetrics()) { - for (double d = 0; d < m.length; d += step) { - final Tangent? t = m.getTangentForOffset(d); - if (t == null) continue; - final double dist = (t.position - p).distance; - if (dist < best) best = dist; - } - } - return best; -} - -/// 第 [k] 档自动错开量(px):0、−6、+6、−12、+12 … -/// -/// 同一走线分组内第二条起依次错开,避免多条依赖完全重叠。 -double staggerOffset(int k) { - if (k <= 0) return 0; - return (k.isOdd ? -1 : 1) * ((k + 1) ~/ 2) * 6.0; -} - -/// 拖拽调整走线时的移动轴(走线的“法线”方向)。 -/// -/// - [vertical]:上下拖动——平移水平走线段(条形 / 流程图的常见形态); -/// - [horizontal]:左右拖动——平移纵向走线走廊(跨行绕行走廊 / 同层绕行)。 -enum RouteAxis { vertical, horizontal } - -/// 拖拽走线时可用的最大手动偏移(px,双向)。 -const double kMaxRouteOffset = 200; - -// ===================== 条形视图 ===================== - -/// 条形视图的一条依赖走线。 -class BarDepRoute { - /// 构造。 - BarDepRoute(this.dep, this.points, this.arrowTip, this.arrowDir, this.chipCenter, this.axis, - {this.chipRun = double.infinity, - this.chipRunMargin = 0, - this.chipAltAnchor = Offset.zero}); - - /// 对应依赖。 - final Dependency dep; - /// 折线顶点(含起点与箭头端点)。 - final List points; - /// 箭头端点。 - final Offset arrowTip; - /// 箭头方向(分量式)。 - final Offset arrowDir; - /// 标签中心(默认位置,避让前)。 - final Offset chipCenter; - /// 拖拽方向:vertical = 上下拖动平移横线;horizontal = 左右拖动平移纵向走廊。 - final RouteAxis axis; - - /// 标签挂钩的水平行程长度(跑长时用于判断是否需要把标签移到箭头外侧)。 - /// - /// 默认 [double.infinity] 表示不做外移判断(跨行走廊等)。 - final double chipRun; - - /// 外移判断余量:行程 `< 标签宽 + 余量` 时把标签移到 [chipAltAnchor]。 - final double chipRunMargin; - - /// 外移时标签的锚点(绘制端会再加半个标签宽)。 - final Offset chipAltAnchor; - - /// 依赖键 `from->to`。 - String get key => '${dep.fromId}->${dep.toId}'; -} - -/// 计算条形视图的全部依赖走线(含自动错开与手动偏移)。 -/// -/// 走线分三种情形:同泳道(水平线)、相邻泳道(Z 形)、跨多行(外侧纵向走廊), -/// 与绘制旧的实现保持一致;新增:同组自动错开 + [Dependency.routeOffset] 手动偏移。 -List buildBarDepRoutes(Project project, BarLayout layout) { - final Map laneIndex = { - for (final Action a in project.actions) a.id: layout.laneIndexOf(a.layer), - }; - final Map seen = {}; - final List out = []; - for (final Action to in layout.ordered) { - for (final Dependency d in to.deps) { - final Action? from = project.actionById(d.fromId); - if (from == null) continue; - final int ia = laneIndex[from.id] ?? 0; - final int ib = laneIndex[to.id] ?? 0; - final Rect ra = layout.rectFor(from); - final Rect rb = layout.rectFor(to); - const double barHalf = BarLayout.barH / 2; - final double sy = ra.center.dy; - final double ty = rb.center.dy; - final double dir = ty > sy ? 1 : -1; - final double tipY = ty - dir * (barHalf + 3); - final bool sameLane = (ty - sy).abs() < 1; - final bool fs = d.type == DepType.fs; - - if (sameLane) { - // 同泳道:一条水平线;同组多条依次上下错开。 - final int k = seen.putIfAbsent('S$ia', () => 0); - seen['S$ia'] = k + 1; - final double y = sy + staggerOffset(k) + d.routeOffset; - final double startX = fs ? ra.right + 2 : ra.left - 2; - double endX = rb.left - 2; - if (endX < startX) endX = rb.right + 2; - out.add(BarDepRoute( - d, - [Offset(startX, y), Offset(endX, y)], - Offset(endX, y), - Offset(endX >= startX ? 1 : -1, 0), - Offset((startX + endX) / 2, y - (barHalf + 9)), - RouteAxis.vertical, - // 行程太短时标签移出到箭头右侧(宽度由绘制端精确测量)。 - chipRun: (endX - startX).abs(), - chipRunMargin: 8, - chipAltAnchor: Offset(endX + 6, y - (barHalf + 9)), - )); - } else if ((ib - ia).abs() <= 1) { - // 相邻泳道:在两泳道之间的空隙中线走水平线;同组错开 + 手动偏移。 - final int k = seen.putIfAbsent('A$ia→$ib', () => 0); - seen['A$ia→$ib'] = k + 1; - final double mid = (sy + ty) / 2 + staggerOffset(k) + d.routeOffset; - final double sx = fs ? ra.right : ra.left; - final double ex = fs ? sx - 9 : sx + 9; - final double tx = rb.left + 14; - out.add(BarDepRoute( - d, - [ - Offset(ex, sy + dir * (barHalf + 2)), - Offset(ex, mid), - Offset(tx, mid), - Offset(tx, tipY), - ], - Offset(tx, tipY), - Offset(0, dir), - Offset((ex + tx) / 2, mid), - RouteAxis.vertical, - chipRun: (tx - ex).abs(), - chipRunMargin: 10, - chipAltAnchor: Offset(tx + 6, mid), - )); - } else { - // 跨多行:扫描区间内所有条块边界,据此在外侧选一条纵向走廊; - // 同组按 ±12px 错开走廊,手动偏移作用于走廊的横向位置。 - final int k = seen.putIfAbsent('M$ia→$ib', () => 0); - seen['M$ia→$ib'] = k + 1; - final double sx = fs ? ra.right : ra.left; - final double ex = fs ? sx - 9 : sx + 9; - final double tx = rb.left + 14; - double maxRight = 0; - double minLeft = double.infinity; - final List lanes = layout.lanes; - for (int r = math.min(ia, ib) + 1; r < math.max(ia, ib); r++) { - if (r < 0 || r >= lanes.length) continue; - for (final Action aa in layout.actionsInLane(lanes[r])) { - final Rect rr = layout.rectFor(aa); - maxRight = math.max(maxRight, rr.right); - minLeft = math.min(minLeft, rr.left); - } - } - final double shift = staggerOffset(k) * 2 + d.routeOffset; - double lane = math.max(math.max(sx, tx), maxRight) + 28 + shift; - if (lane > layout.plotRight - 16) { - lane = math.min(math.min(sx, tx), minLeft) - 28 - shift; - } - final double srcGapY = sy + dir * (barHalf + 14); - final double gapY = ty - dir * (barHalf + 6); - out.add(BarDepRoute( - d, - [ - Offset(ex, sy + dir * (barHalf + 2)), - Offset(ex, srcGapY), - Offset(lane, srcGapY), - Offset(lane, gapY), - Offset(tx, gapY), - Offset(tx, tipY), - ], - Offset(tx, tipY), - Offset(0, dir), - Offset((lane + tx) / 2, gapY - (barHalf + 1)), - RouteAxis.horizontal, - )); - } - } - } - return out; -} - -/// 命中条形依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。 -BarDepRoute? hitBarDep(List routes, Offset p, double maxDist) { - BarDepRoute? best; - double bestD = maxDist; - for (final BarDepRoute r in routes) { - final double d = distanceToPolyline(r.points, p); - if (d < bestD) { - bestD = d; - best = r; - } - } - return best; -} - -// ===================== 圆周视图 ===================== - -/// 圆周视图的一条依赖走线(径向 → 圆弧 → 径向)。 -class ArcDepRoute { - /// 构造。 - ArcDepRoute(this.dep, this.center, this.rA, this.rB, this.rC, this.rTip, this.aEnd, this.aStart, - this.degenerate, this.cw, this.large, this.chipR, this.chipDeg); - - /// 对应依赖。 - final Dependency dep; - /// 圆心。 - final Offset center; - /// 源环半径。 - final double rA; - /// 目标环半径。 - final double rB; - /// 绕行半径(自动错开 + 手动偏移作用于此)。 - final double rC; - /// 箭头落点半径。 - final double rTip; - /// 源弧末端角(度)。 - final double aEnd; - /// 目标弧起点角(度)。 - final double aStart; - /// 起止角几乎重合(退化)时改画短箭头。 - final bool degenerate; - /// 圆弧是否顺时针。 - final bool cw; - /// 是否大弧。 - final int large; - /// 标签极径。 - final double chipR; - /// 标签极角。 - final double chipDeg; - - /// 依赖键 `from->to`。 - String get key => '${dep.fromId}->${dep.toId}'; - - /// 起点(源环上)。 - Offset get p0 => polar(center, rA, aEnd); - /// 绕行起点(半径 rC 上)。 - Offset get p1 => polar(center, rC, aEnd); - /// 绕行终点(半径 rC 上)。 - Offset get p2 => polar(center, rC, aStart); - /// 箭头端点。 - Offset get p3 => polar(center, rTip, aStart); - /// 退化短箭头的起点。 - Offset get q0 => polar(center, rTip - (rTip > rB ? 28 : -28), aStart); - - /// 生成绘制路径(绘制与命中测试同源)。 - Path buildPath() { - final Path p = Path(); - if (degenerate) { - p.moveTo(q0.dx, q0.dy); - p.lineTo(p3.dx, p3.dy); - return p; - } - final Offset a0 = p0; - final Offset a1 = p1; - final Offset a2 = p2; - final Offset a3 = p3; - p.moveTo(a0.dx, a0.dy); - p.lineTo(a1.dx, a1.dy); - p.arcToPoint(a2, radius: Radius.circular(rC), largeArc: large == 1, clockwise: cw); - p.lineTo(a3.dx, a3.dy); - return p; - } - - /// 箭头方向(分量式)。 - Offset get tipDir => degenerate ? (p3 - q0) : (p3 - p2); -} - -/// 计算圆周视图的全部依赖走线(含自动错开与手动偏移)。 -List buildArcDepRoutes(Project project, CircularLayout layout) { - final Map seen = {}; - final List out = []; - 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, layout.slotOf(a)); - final double rB = layout.radiusFor(b.layer, layout.slotOf(b)); - final double aEnd = math.min(a.endAngle, 360); - final double aStart = b.startAngle; - // 层差大于 1 时从最外圈绕行,避免穿过中间层弧线。 - final bool skip = (a.layer - b.layer).abs() > 1; - final String groupKey = '${skip ? 'K' : 'N'}${a.layer}→${b.layer}'; - final int k = seen.putIfAbsent(groupKey, () => 0); - seen[groupKey] = k + 1; - // 自动错开(步长 9px)+ 手动径向偏移(圆周视图的“法线”即半径方向)。 - double rC = (skip ? layout.rMax + 24 : (rA + rB) / 2) + staggerOffset(k) * 1.5 + d.routeOffset; - rC = rC.clamp(18.0, layout.rMax + 170); - final double rTip = rC < rB ? rB - layout.th / 2 - 4 : rB + layout.th / 2 + 4; - final bool cw = aStart >= aEnd; - final int large = (aStart - aEnd).abs() > 180 ? 1 : 0; - final bool degenerate = (aStart - aEnd).abs() < 0.5; - final double chipDeg = degenerate ? aStart : (aEnd + aStart) / 2; - double chipR; - if (degenerate) { - chipR = (rA + rB) / 2; - } else { - final double span = (aStart - aEnd).abs(); - chipR = skip ? rC : (span < 30 ? rB + layout.th / 2 + 10 : rC); - } - out.add(ArcDepRoute( - d, layout.center, rA, rB, rC, rTip, aEnd, aStart, degenerate, cw, large, chipR, chipDeg)); - } - } - return out; -} - -/// 命中圆周依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。 -ArcDepRoute? hitArcDep(List routes, Offset p, double maxDist) { - ArcDepRoute? best; - double bestD = maxDist; - for (final ArcDepRoute r in routes) { - final double d = distanceToPath(r.buildPath(), p); - if (d < bestD) { - bestD = d; - best = r; - } - } - return best; -} diff --git a/lib/main.dart b/lib/main.dart index 7eaa6c7..8368554 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -14,7 +14,7 @@ import 'package:flutter/services.dart'; import 'license/license_service.dart'; import 'model/models.dart'; -import 'modules/module_registry.dart'; +import 'modules/registry.dart'; import 'persistence/app_paths.dart'; import 'persistence/storage.dart'; import 'state/app_controller.dart'; @@ -32,6 +32,7 @@ Future main() async { await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); } await Storage.instance.init(); + await initModuleRegistry(); runApp(const SequenceDiagramApp()); } @@ -87,18 +88,19 @@ class _SequenceDiagramAppState extends State { /// 更新原生窗口标题为「模块名 - <文件名 | 未命名文件>」, /// 有未保存修改时追加 ` *`。 void _updateWindowTitle() { - final String name = _controller.currentFilePath == null - ? '未命名文件' - : _controller.currentFilePath!.split(RegExp(r'[\\/]')).last; - final String dirty = _controller.dirty ? ' *' : ''; - // 标题走模块注册表(首页显示品牌名,不带文件名)。 - if (_controller.appMode == AppMode.home) { + // 标题走模块注册表:文件路径也由当前模块提供,新增模块无需改这里。 + if (_controller.isHome) { _windowChannel - .invokeMethod('setTitle', 'EDC易得') + .invokeMethod('setTitle', kBrandName) .catchError((Object _) {}); return; } - final String brand = appModeLabel(_controller.appMode); + final EdcModule? module = moduleById(_controller.activeModuleId); + final String? path = module?.filePath(_controller) ?? _controller.currentFilePath; + final String name = + path == null ? '未命名文件' : path.split(RegExp(r'[\\/]')).last; + final String dirty = _controller.dirty ? ' *' : ''; + final String brand = moduleTitle(_controller.activeModuleId); _windowChannel .invokeMethod('setTitle', '$brand - $name$dirty') .catchError((Object _) {}); @@ -158,7 +160,7 @@ class _SequenceDiagramAppState extends State { // 恢复流程:choice == 1 走 .bak 备份,否则走自动快照;解码失败时静默忽略。 // 当前快照仅为时序图文档:恢复前先切到对应模块(避免停留在首页看不到内容)。 try { - _controller.setAppMode(AppMode.sequence); + _controller.setModuleId('sequence', status: '时序图设计'); if (choice == 1 && info.bakContent != null) { _controller.loadProject(Project.decode(info.bakContent!), path: info.projectPath, dirty: true); } else { @@ -177,7 +179,7 @@ class _SequenceDiagramAppState extends State { builder: (BuildContext context, Widget? child) { final Tokens tokens = Tokens.of(_controller.brightness); return MaterialApp( - title: 'EDC易得 · Easy Design Collection', + title: 'PDS流程设计套件 · Process Design Suite', debugShowCheckedModeBanner: false, theme: buildTheme(tokens), // 固定文本缩放;系统栏图标随主题亮度自动切换(透明系统栏, diff --git a/lib/model/models.dart b/lib/model/models.dart index 6a7b340..ed3835c 100644 --- a/lib/model/models.dart +++ b/lib/model/models.dart @@ -10,7 +10,7 @@ library; import 'dart:convert'; -import '../arch/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; /// 主视图模式。 enum ViewMode { @@ -24,18 +24,6 @@ enum ViewMode { flow, } -/// 顶层设计模块(左上角 logo「设计合集」菜单切换的对象)。 -enum AppMode { - /// 首页(空白启动:新建 / 打开文档前的工作台)。 - home, - - /// 时序图设计(条形 / 圆周 / 流程图)。 - sequence, - - /// 架构图设计(手绘识别 / 系统架构)。 - architecture, -} - /// 时间单位。 enum TimeUnit { /// 毫秒。 diff --git a/lib/modules/README.md b/lib/modules/README.md new file mode 100644 index 0000000..6aa96b0 --- /dev/null +++ b/lib/modules/README.md @@ -0,0 +1,150 @@ +# 模块开发速查 + +> 本目录下每个子目录 = 一个功能模块。模块入口实现 `EdcModule`,然后在 +> `registry.dart` 注册。**不要修改 `lib/ui/app_shell.dart` 来加入模块专属逻辑。** + +## 目录约定 + +```text +modules/ +├── module.dart # 契约:EdcModule / ModuleUiContext / PlannedModule +├── registry.dart # ★ 唯一注册表 +├── / +│ ├── _module.dart # 模块入口(元数据 / 文档生命周期 / UI 委托) +│ ├── domain/ # 可选:模块领域模型 +│ ├── layout/ # 可选:几何布局 +│ ├── render/ # 可选:绘制 +│ ├── export/ # 可选:导出 +│ └── ui/ # 可选:模块 UI(工作区 / 工具栏 / 侧栏 / 状态栏) +``` + +## 最小模块模板 + +```dart +import 'package:flutter/material.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +const FooModule fooModule = FooModule(); + +class FooModule extends EdcModule { + const FooModule(); + + @override + String get id => 'foo'; + @override + String get name => '示例图'; + @override + String get shortName => '示例'; + @override + IconData get icon => Icons.widgets_outlined; + @override + int get accent => 0xFF38BDF8; + @override + String get suffix => '.foo.json'; + @override + bool get available => true; + @override + String get defaultName => '未命名-示例图'; + @override + String get blurb => '一句话简介'; + + @override + void newDocument(AppController c) {} + @override + void loadDocument(AppController c, String source, {String? path}) {} + @override + String encodeDocument(AppController c) => '{}'; + @override + String documentName(AppController c) => '示例图'; + @override + String? filePath(AppController c) => null; + @override + bool isDirty(AppController c) => false; + @override + Future saveTo(AppController c, String path) async {} + @override + Future markSaved(AppController c, String displayPath) async {} + + @override + Widget buildWorkspace(ModuleUiContext ui) => + const Center(child: Text('Foo module')); + + @override + Widget buildStatusBar(ModuleUiContext ui) => + Text('示例图', style: TextStyle(color: ui.tokens.dim, fontSize: 11)); +} +``` + +注册: + +```dart +// registry.dart +import 'package:sequence_diagram/modules/foo/foo_module.dart'; + +const List kModules = [ + architectureModule, + sequenceModule, + fooModule, + ... +]; +``` + +## 可选扩展点 + +| 方法 / 属性 | 作用 | +| --- | --- | +| `buildToolbarCenter(ui, compact:)` | 工具栏中段工具(视图切换 / 模块工具) | +| `buildToolbarRight(ui)` | 工具栏右侧工具(导出 / 缩放 / 适应视图 / 单位) | +| `buildLeftPanel(ui, floating:)` | 左侧栏;`hasLeftPanel` 控制外壳是否显示停靠 / 轨道 | +| `buildRightPanel(ui, floating:)` | 右侧栏;`hasRightPanel` 同上 | +| `buildStatusBar(ui)` | 底部状态栏 | +| `buildShortcuts(ui)` | 模块快捷键,与外壳公共快捷键合并 | +| `isReadOnly(c)` | 只读视图(撤销 / 重做置灰) | +| `enterStatus` | 进入模块时的状态栏提示 | + +`ModuleUiContext` 提供: + +- `context / controller / tokens` +- `compact / toolScale / toolFont` +- `leftRail / rightRail / leftPanelWidth / rightPanelWidth` +- `panelControls(left)`(外壳的钉住 / 收起按钮) + +## 规范 + +1. 模块内使用 `package:sequence_diagram/...` 绝对导入。 +2. 模块之间禁止互相 import;共享代码上移到 `lib/` 公共层或 `lib/export/`。 +3. 不要在模块 UI 里硬编码品牌名 / 模块名;使用 `ui.controller.activeModuleId` + + `registry` 或模块元数据。 +4. 文档新增字段必须可缺省,保证旧 JSON 可打开。 +5. 新增模块必须补测试:注册表唯一性、打开 / 保存、首页与品牌菜单。 +6. 只改 `registry.dart` 一处全局文件;如果发现必须改 `AppShell`,说明契约缺少 + 扩展点,应优先扩展契约而不是加分支。 + +## 发布级模块清单 + +发布包内包含: + +```text +ProcessDesignSuite/modules/ +├── registry.json # 顺序 / 显示名 / 颜色 / 启用状态 +├── architecture/module.json +├── sequence/module.json +└── elec/io/topo/pid/module.json +``` + +- 源码模板在 `assets/modules/`,构建时复制到发布包 `modules/`。 +- 启动时桌面优先读取 exe 同级 `modules/registry.json`,安卓读取内置 + `assets/modules/registry.json`;失败回退 `registry.dart`。 +- 清单可以调整顺序 / 名称 / 颜色 / 启用状态;未编译进应用的模块显示为 + 「组件未安装」。**新增 UI 代码仍需重新构建应用(Flutter AOT 限制)**。 + +## 规划中模块 + +`elec` / `io` / `topo` / `pid` 已用 `PlannedModule` 占位并注册,首页灰显。 +实现时: + +1. 在对应目录新增领域模型与 UI; +2. 把 `extends PlannedModule` 改为 `extends EdcModule`(或继承新的真实模块类); +3. 补齐文档生命周期与 `available => true`; +4. 注册表无需变动(已经登记)。 diff --git a/lib/modules/architecture/architecture_module.dart b/lib/modules/architecture/architecture_module.dart new file mode 100644 index 0000000..8899a13 --- /dev/null +++ b/lib/modules/architecture/architecture_module.dart @@ -0,0 +1,130 @@ +/// 架构图设计模块:手绘识别、系统架构图与参数化草图。 +/// +/// 模块入口:`lib/modules/architecture/`。新增模块请参考本文件与 +/// `lib/modules/README.md`,然后在 `lib/modules/registry.dart` 注册。 +library; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/ui/architecture_ui.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +/// 架构图模块单例。 +const ArchitectureModule architectureModule = ArchitectureModule(); + +/// 架构图设计模块。 +class ArchitectureModule extends EdcModule { + /// 构造模块。 + const ArchitectureModule(); + + /// 稳定 id。 + static const String moduleId = 'architecture'; + + @override + String get id => moduleId; + @override + String get name => '架构图'; + @override + String get shortName => '架构图'; + @override + IconData get icon => Icons.account_tree_outlined; + @override + int get accent => 0xFF34D399; + @override + String get suffix => '.arch.json'; + @override + bool get available => true; + @override + String get defaultName => '未命名-架构图'; + @override + String get blurb => '手绘识别 · 图形库'; + + @override + String get enterStatus => '架构图设计 · 手绘识别'; + + @override + void newDocument(AppController controller) { + controller.newArchProject(); + } + + @override + void loadDocument(AppController controller, String source, {String? path}) { + controller.loadArchDoc(ArchDoc.decode(source), path: path); + } + + @override + String encodeDocument(AppController controller) => controller.arch.encode(); + + @override + String documentName(AppController controller) => controller.project.name; + + @override + String? filePath(AppController controller) => controller.archFilePath; + + @override + bool isDirty(AppController controller) => controller.dirty; + + @override + Future saveTo(AppController controller, String path) => + controller.saveArchAs(path); + + @override + Future markSaved(AppController controller, String displayPath) => + controller.markArchSaved(displayPath); + + @override + bool isReadOnly(AppController controller) => false; + + @override + Map buildShortcuts(ModuleUiContext ui) { + final AppController c = ui.controller; + return { + const SingleActivator(LogicalKeyboardKey.keyA, control: true): () { + if (c.sketchMode) { + c.selectAllSketch(); + } else { + c.selectAllArch(); + } + }, + const SingleActivator(LogicalKeyboardKey.delete): () { + if (c.sketchMode) { + c.deleteSketchSelection(); + } else { + c.removeArchSelection(); + } + }, + const SingleActivator(LogicalKeyboardKey.escape): () { + if (c.sketchMode && + (c.sketchPendingCons != null || c.sketchPendingDim != null)) { + c.cancelSketchCommand(); + } + }, + }; + } + + @override + Widget buildWorkspace(ModuleUiContext ui) => ArchitectureUi(ui).buildWorkspace(); + + @override + Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) => + ArchitectureUi(ui).buildLeftPanel(ui.tokens, floating: floating); + + @override + Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) => + ArchitectureUi(ui).buildRightPanel(ui.tokens, floating: floating); + + @override + List buildToolbarCenter(ModuleUiContext ui, {required bool compact}) => + ArchitectureUi(ui).buildToolbarCenter(ui.tokens, compact: compact); + + @override + List buildToolbarRight(ModuleUiContext ui) => + ArchitectureUi(ui).buildToolbarRight(ui.tokens, compact: ui.compact); + + @override + Widget buildStatusBar(ModuleUiContext ui) => + ArchitectureUi(ui).buildStatusBar(ui.tokens); +} diff --git a/lib/arch/arch_dxf.dart b/lib/modules/architecture/domain/arch_dxf.dart similarity index 99% rename from lib/arch/arch_dxf.dart rename to lib/modules/architecture/domain/arch_dxf.dart index 54ca27a..8be7f84 100644 --- a/lib/arch/arch_dxf.dart +++ b/lib/modules/architecture/domain/arch_dxf.dart @@ -11,7 +11,7 @@ library; import 'dart:math' as math; import 'dart:ui'; -import '../library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; import 'arch_models.dart'; import 'arch_painter.dart'; diff --git a/lib/arch/arch_export.dart b/lib/modules/architecture/domain/arch_export.dart similarity index 98% rename from lib/arch/arch_export.dart rename to lib/modules/architecture/domain/arch_export.dart index cf5b1c0..6e25ebc 100644 --- a/lib/arch/arch_export.dart +++ b/lib/modules/architecture/domain/arch_export.dart @@ -12,9 +12,9 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; -import '../export/export_fit.dart'; -import '../library/symbol_library.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/export/export_geometry.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'arch_models.dart'; import 'arch_painter.dart'; @@ -40,7 +40,7 @@ Future renderArchPng({ // 标题与副标题(固定左上角)。 _text(canvas, '架构图设计', const Offset(48, 36), color: et.text, size: 34, weight: FontWeight.w700); - _text(canvas, 'EDC易得 · Easy Design Collection · 手绘识别架构图', const Offset(48, 88), + _text(canvas, 'PDS流程设计套件 · Process Design Suite · 手绘识别架构图', const Offset(48, 88), color: et.sub, size: 16, weight: FontWeight.w400); // 内容适配(白底令牌 + 关闭网格点阵)。 @@ -56,7 +56,7 @@ Future renderArchPng({ _text( canvas, - 'EDC易得 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 ' + 'PDS流程设计套件 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 ' '${doc.connectors.length} · 墨迹 ${doc.strokes.length}', Offset(48, h - 38), color: et.sub, diff --git a/lib/arch/arch_models.dart b/lib/modules/architecture/domain/arch_models.dart similarity index 99% rename from lib/arch/arch_models.dart rename to lib/modules/architecture/domain/arch_models.dart index a5b8dbc..863642b 100644 --- a/lib/arch/arch_models.dart +++ b/lib/modules/architecture/domain/arch_models.dart @@ -16,7 +16,7 @@ import 'dart:convert'; import 'dart:math' as math; import 'dart:ui' show Offset, Path, Rect, Size; -import '../sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; /// 架构图画布当前工具。 enum ArchTool { diff --git a/lib/arch/arch_painter.dart b/lib/modules/architecture/domain/arch_painter.dart similarity index 99% rename from lib/arch/arch_painter.dart rename to lib/modules/architecture/domain/arch_painter.dart index 34456c0..0d25f76 100644 --- a/lib/arch/arch_painter.dart +++ b/lib/modules/architecture/domain/arch_painter.dart @@ -11,9 +11,9 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; -import '../library/symbol_library.dart'; -import '../sketch/sketch_painter.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_painter.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'arch_models.dart'; /// 一次「墨迹 → 标准图形」的转化动画记录。 diff --git a/lib/arch/arch_recognizer.dart b/lib/modules/architecture/domain/arch_recognizer.dart similarity index 100% rename from lib/arch/arch_recognizer.dart rename to lib/modules/architecture/domain/arch_recognizer.dart diff --git a/lib/arch/arch_samples.dart b/lib/modules/architecture/domain/arch_samples.dart similarity index 100% rename from lib/arch/arch_samples.dart rename to lib/modules/architecture/domain/arch_samples.dart diff --git a/lib/arch/arch_symbol_recognizer.dart b/lib/modules/architecture/domain/arch_symbol_recognizer.dart similarity index 98% rename from lib/arch/arch_symbol_recognizer.dart rename to lib/modules/architecture/domain/arch_symbol_recognizer.dart index eedd749..95754a0 100644 --- a/lib/arch/arch_symbol_recognizer.dart +++ b/lib/modules/architecture/domain/arch_symbol_recognizer.dart @@ -11,7 +11,7 @@ library; import 'dart:math' as math; import 'dart:ui' show Offset, Path, PathMetric, Rect, Tangent; -import '../library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; /// 图元匹配结果。 class ArchSymbolMatch { diff --git a/lib/library/symbol_library.dart b/lib/modules/architecture/library/symbol_library.dart similarity index 100% rename from lib/library/symbol_library.dart rename to lib/modules/architecture/library/symbol_library.dart diff --git a/lib/sketch/sketch_models.dart b/lib/modules/architecture/sketch/sketch_models.dart similarity index 100% rename from lib/sketch/sketch_models.dart rename to lib/modules/architecture/sketch/sketch_models.dart diff --git a/lib/sketch/sketch_painter.dart b/lib/modules/architecture/sketch/sketch_painter.dart similarity index 99% rename from lib/sketch/sketch_painter.dart rename to lib/modules/architecture/sketch/sketch_painter.dart index bf5925c..9c801ad 100644 --- a/lib/sketch/sketch_painter.dart +++ b/lib/modules/architecture/sketch/sketch_painter.dart @@ -9,7 +9,7 @@ import 'dart:typed_data'; import 'package:flutter/material.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'sketch_models.dart'; /// 草图配色(浅 / 深色主题下都可读)。 diff --git a/lib/sketch/sketch_solver.dart b/lib/modules/architecture/sketch/sketch_solver.dart similarity index 100% rename from lib/sketch/sketch_solver.dart rename to lib/modules/architecture/sketch/sketch_solver.dart diff --git a/lib/ui/arch_panel.dart b/lib/modules/architecture/ui/arch_panel.dart similarity index 98% rename from lib/ui/arch_panel.dart rename to lib/modules/architecture/ui/arch_panel.dart index 8b0f7c0..901ac99 100644 --- a/lib/ui/arch_panel.dart +++ b/lib/modules/architecture/ui/arch_panel.dart @@ -8,12 +8,12 @@ library; import 'package:flutter/material.dart'; -import '../arch/arch_models.dart'; -import '../sketch/sketch_models.dart'; -import '../sketch/sketch_solver.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import 'dialogs.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; /// 小节标题。 Widget _sec(Tokens t, String s) => Text( diff --git a/lib/ui/arch_view.dart b/lib/modules/architecture/ui/arch_view.dart similarity index 98% rename from lib/ui/arch_view.dart rename to lib/modules/architecture/ui/arch_view.dart index 79e24db..7a298a1 100644 --- a/lib/ui/arch_view.dart +++ b/lib/modules/architecture/ui/arch_view.dart @@ -14,17 +14,17 @@ import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import '../arch/arch_models.dart'; -import '../arch/arch_painter.dart'; -import '../arch/arch_recognizer.dart'; -import '../arch/arch_symbol_recognizer.dart'; -import '../library/symbol_library.dart'; -import '../sketch/sketch_models.dart'; -import '../sketch/sketch_painter.dart'; -import '../sketch/sketch_solver.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import 'dialogs.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_painter.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_recognizer.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_symbol_recognizer.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_painter.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; /// 连线拖拽吸附结果:吸附后的坐标 + 对齐导引(null = 该轴无对齐)。 typedef ConnSnap = ({double x, double y, double? gx, double? gy}); diff --git a/lib/modules/architecture/ui/architecture_ui.dart b/lib/modules/architecture/ui/architecture_ui.dart new file mode 100644 index 0000000..8a7f5aa --- /dev/null +++ b/lib/modules/architecture/ui/architecture_ui.dart @@ -0,0 +1,617 @@ +/// 架构图模块 UI:工具栏中段 / 右侧工具、左右侧栏、状态栏。 +/// +/// 由 `ArchitectureModule` 通过 `lib/modules/registry.dart` 注册后由外壳调用。 +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart' hide Action; + +import 'package:sequence_diagram/modules/architecture/domain/arch_dxf.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_export.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/modules/architecture/ui/arch_panel.dart'; +import 'package:sequence_diagram/modules/architecture/ui/arch_view.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/persistence/android_docs.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; + +/// 架构图模块 UI 构建器。 +class ArchitectureUi { + /// 构造 UI 构建器。 + const ArchitectureUi(this.ui); + + /// 外壳上下文。 + final ModuleUiContext ui; + + AppController get c => ui.controller; + BuildContext get context => ui.context; + Tokens get t => ui.tokens; + double get _toolScale => ui.toolScale; + double _toolFont(double size) => ui.toolFont(size); + double get _leftPanelWidth => ui.leftPanelWidth; + double get _rightPanelWidth => ui.rightPanelWidth; + Widget _panelControls(Tokens t, bool left) => ui.panelControls(left); + + /// 工具栏中段:选择 / 手绘 / 连线 / 橡皮 + 识别。 + List buildToolbarCenter(Tokens t, {required bool compact}) => + [_archTools(t, compact)]; + + /// 工具栏右侧:导出 / 缩放 / 适应视图。 + List buildToolbarRight(Tokens t, {required bool compact}) => [ + _exportMenu(t), + SizedBox(width: (compact ? 4 : 6) * _toolScale), + _zoomBox(t), + SizedBox(width: (compact ? 4 : 6) * _toolScale), + _iconBtn(t, Icons.crop_free, c.archFit, tooltip: '适应视图'), + ]; + + /// 左侧栏。 + Widget buildLeftPanel(Tokens t, {bool floating = false}) => + _archLeftPanel(t, floating: floating); + + /// 右侧栏。 + Widget buildRightPanel(Tokens t, {bool floating = false}) => + _archRightPanel(t, floating: floating); + + /// 底部状态栏。 + Widget buildStatusBar(Tokens t) => _archStatusBar(t); + + /// 工作区:架构图画布。 + Widget buildWorkspace() => Container( + color: t.canvas2, + child: ArchView(controller: c), + ); + + + /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮。 + Widget _zoomBox(Tokens t) { + final double s = _toolScale; + final double zoom = c.arch.zoom; + final String pct = '${(zoom * 100).round()}%'; + return Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 4 * s), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: t.line2), + ), + child: Row( + children: [ + _miniIcon(t, Icons.remove, () => c.archZoomBy(0.9)), + SizedBox( + width: 52 * s, + child: Text(pct, + textAlign: TextAlign.center, + style: TextStyle(color: t.text, fontSize: _toolFont(11))), + ), + _miniIcon(t, Icons.add, () => c.archZoomBy(1.1)), + ], + ), + ); + } + + /// 导出菜单:SVG / PNG / DXF。 + Widget _exportMenu(Tokens t) { + final double s = _toolScale; + final bool licensed = c.licensed; + final Color fg = licensed ? Colors.white : t.dim; + return Padding( + padding: EdgeInsets.symmetric(horizontal: 3 * s), + child: PopupMenuButton( + tooltip: '导出(SVG / PNG / DXF)· 架构图', + color: t.panel2, + position: PopupMenuPosition.under, + onSelected: (String v) { + if (v == 'svg') _exportArchSvg(); + if (v == 'png') _exportArchPng(); + if (v == 'dxf') _exportArchDxf(); + }, + itemBuilder: (BuildContext ctx) => >[ + _exportItem(t, 'svg', Icons.code, '导出 SVG', + '矢量图:架构图无损缩放 / 二次编辑', licensed), + _exportItem(t, 'png', Icons.image_outlined, '导出 PNG', + '位图(3840×2160):分享 / 汇报', licensed), + _exportItem(t, 'dxf', Icons.architecture, '导出 DXF', + 'AutoCAD / DraftSight 等可编辑的 CAD 图纸', licensed), + ], + child: Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 12 * s), + decoration: BoxDecoration( + color: licensed ? t.accent2 : t.panel2, + borderRadius: BorderRadius.circular(9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.ios_share, size: 15 * s, color: fg), + SizedBox(width: 6 * s), + Text('导出', + style: TextStyle( + fontSize: _toolFont(11), + fontWeight: FontWeight.w600, + color: fg)), + Icon(Icons.arrow_drop_down, size: 18 * s, color: fg), + ], + ), + ), + ), + ); + } + + Widget _archTools(Tokens t, bool compact) { + // 草图模式:工具在左侧栏,这里显示状态与快捷退出。 + if (c.sketchMode) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), + height: 34 * _toolScale, + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.accent), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.edit_note, size: 15 * _toolScale, color: t.accent), + SizedBox(width: 6 * _toolScale), + Text( + '参数化草图 · ${sketchToolLabel(c.sketchTool)}', + style: TextStyle( + color: t.accent, + fontSize: _toolFont(11), + fontWeight: FontWeight.w600, + ), + ), + SizedBox(width: 10 * _toolScale), + InkWell( + onTap: () => c.setSketchMode(false), + borderRadius: BorderRadius.circular(7), + child: Container( + padding: EdgeInsets.symmetric( + horizontal: 8 * _toolScale, vertical: 3 * _toolScale), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line), + ), + child: Text('退出草图', + style: + TextStyle(color: t.sub, fontSize: _toolFont(10.5))), + ), + ), + ], + ), + ); + } + final ArchTool tool = c.archTool; + Widget seg(String label, IconData icon, ArchTool value, String tip) { + final bool active = tool == value; + return Tooltip( + message: tip, + child: InkWell( + onTap: () => c.setArchTool(value), + borderRadius: BorderRadius.circular(10), + child: Container( + width: (compact ? 74 : 90) * _toolScale, + height: 34 * _toolScale, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent, + borderRadius: BorderRadius.circular(10), + border: active ? Border.all(color: t.accent, width: 1.4) : null, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 15 * _toolScale, color: active ? t.accent : t.sub), + SizedBox(width: 4 * _toolScale), + Text(label, + style: TextStyle( + color: active ? t.accent : t.sub, + fontWeight: active ? FontWeight.w600 : FontWeight.normal, + fontSize: _toolFont(12), + )), + ], + ), + ), + ), + ); + } + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: EdgeInsets.all(3 * _toolScale), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line2), + ), + child: Row( + children: [ + seg('选择', Icons.near_me_outlined, ArchTool.select, '选择 / 移动 / 缩放'), + seg('手绘', Icons.gesture, ArchTool.pen, + c.archAutoRecognize ? '按住拖动绘制,松手自动识别' : '按住拖动绘制;画完点「识别」确认识别'), + seg('连线', Icons.arrow_right_alt, ArchTool.connect, + '从图形拖到另一个图形(横平竖直正交走线,角点可拖拽)'), + seg('橡皮', Icons.cleaning_services_outlined, ArchTool.eraser, + '擦除图形 / 墨迹 / 连线(拖动连擦,一次撤销可整体回退)'), + ], + ), + ), + SizedBox(width: 6 * _toolScale), + // 「识别」确认按钮:手动模式下把待识别墨迹统一识别(自动模式下也可用)。 + Container( + padding: EdgeInsets.all(3 * _toolScale), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line2), + ), + child: InkWell( + onTap: c.arch.strokes.isEmpty ? null : c.archRecognizeInk, + borderRadius: BorderRadius.circular(9), + child: Container( + height: 34 * _toolScale, + padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), + alignment: Alignment.center, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.auto_fix_high, + size: 15 * _toolScale, + color: c.arch.strokes.isEmpty ? t.dim : t.accent), + SizedBox(width: 5 * _toolScale), + Text( + '识别(${c.arch.strokes.length})', + style: TextStyle( + color: c.arch.strokes.isEmpty ? t.dim : t.accent, + fontSize: _toolFont(11), + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ), + ), + ], + ); + } + + Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: EdgeInsets.all(6 * _toolScale), + child: Icon(icon, size: 15 * _toolScale, color: t.sub), + ), + ); + } + + PopupMenuItem _exportItem( + Tokens t, String value, IconData icon, String label, String hint, bool enabled) { + final Color main = enabled ? t.text : t.dim; + return PopupMenuItem( + value: value, + enabled: enabled, + height: 46, + child: Row( + children: [ + Icon(icon, size: 17, color: enabled ? t.accent : t.dim), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)), + Text(hint, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)), + ], + ), + ), + ], + ), + ); + } + + Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) { + final double s = _toolScale; + return IconButton( + onPressed: onTap, + icon: Icon(icon, size: 18 * s, color: onTap == null ? t.dim : (color ?? t.text)), + tooltip: tooltip, + splashRadius: 16 * s, + padding: EdgeInsets.zero, + constraints: BoxConstraints(minWidth: 34 * s, minHeight: 34 * s), + // 新版 Flutter 的 IconButton 已移除 tapTargetSize 形参,改由 style 提供。 + style: IconButton.styleFrom(tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null), + ); + } + + Future _exportArchSvg() async { + if (!c.licensed) { + if (context.mounted) { + await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); + } + return; + } + final String svg = buildArchSvg(doc: c.arch, baseTokens: Tokens.of(c.brightness)); + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}-架构图.svg', + suffix: '.svg', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), + mime: 'image/svg+xml'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}-架构图.svg', + suffix: '.svg', + ); + if (path == null) return; + try { + await File(path).writeAsString(svg, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Future _exportArchPng() async { + if (!c.licensed) { + if (context.mounted) { + await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); + } + return; + } + final Uint8List bytes; + try { + bytes = await renderArchPng( + doc: c.arch, + baseTokens: Tokens.of(c.brightness), + projectName: c.project.name, + ); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + return; + } + if (!context.mounted) return; + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}-架构图.png', + suffix: '.png', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}-架构图.png', + suffix: '.png', + ); + if (path == null) return; + try { + await File(path).writeAsBytes(bytes, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Future _exportArchDxf() async { + if (!c.licensed) { + if (context.mounted) { + await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 DXF。'); + } + return; + } + final String dxf = buildArchDxf(doc: c.arch); + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}-架构图.dxf', + suffix: '.dxf', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(dxf)), + mime: 'application/dxf'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}-架构图.dxf', + suffix: '.dxf', + ); + if (path == null) return; + try { + await File(path).writeAsString(dxf, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Widget _archLeftPanel(Tokens t, {bool floating = false}) { + return Container( + width: _leftPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] + : null, + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _sectionLabel(t, '架构图 · 设计工具'), + const Spacer(), + _panelControls(t, true), + ], + ), + const SizedBox(height: 10), + ArchLeftBody(controller: c), + ], + ), + ), + ); + } + + Widget _archRightPanel(Tokens t, {bool floating = false}) { + return Container( + width: _rightPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] + : null, + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), + child: Row( + children: [ + _sectionLabel(t, '属性 · 架构图'), + const Spacer(), + _panelControls(t, false), + ], + ), + ), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), + child: ArchRightBody(controller: c), + ), + ), + ], + ), + ); + } + + Widget _sectionLabel(Tokens t, String s) => Text( + s, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text2, fontSize: 11.5, letterSpacing: 1.2, fontWeight: FontWeight.w600), + ); + + Widget _archStatusBar(Tokens t) { + final ArchDoc doc = c.arch; + final String toolLabel = c.sketchMode + ? '草图·${sketchToolLabel(c.sketchTool)}' + : switch (c.archTool) { + ArchTool.select => '选择', + ArchTool.pen => c.archAutoRecognize ? '手绘识别' : '手绘(待确认)', + ArchTool.connect => '连线', + ArchTool.eraser => '橡皮', + }; + final List items = [ + c.sketchMode ? '参数化草图' : '架构图模式', + if (c.sketchMode) ...[ + '实体 ${doc.sketch.entities.length}', + '约束 ${doc.sketch.constraints.where((SketchConstraint k) => !k.internal).length}', + '尺寸 ${doc.sketch.dims.length}', + '自由度 ${sketchDofCount(doc.sketch)}', + ] else ...[ + '元件 ${doc.shapes.length}', + '连线 ${doc.connectors.length}', + '墨迹 ${doc.strokes.length}', + '图层 ${doc.layerById(doc.activeLayer).name}', + ], + '工具 $toolLabel', + if (!c.sketchMode && c.archOrtho) '正交 开', + if (!c.sketchMode && c.archPolar) '极轴 ${c.archPolarDeg.round()}°', + '缩放 ${(doc.zoom * 100).round()}%', + c.status, + ]; + return Container( + height: 32, + padding: const EdgeInsets.symmetric(horizontal: 16), + decoration: BoxDecoration( + color: t.chrome, + border: Border(top: BorderSide(color: t.line2)), + ), + child: Row( + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: items.map((String s) { + final bool last = s == items.last; + return Padding( + padding: const EdgeInsets.only(right: 22), + child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)), + ); + }).toList(), + ), + ), + ), + if (c.dirty) + Padding( + padding: const EdgeInsets.only(right: 14), + child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)), + ), + Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ); + } +} diff --git a/lib/modules/elec/elec_module.dart b/lib/modules/elec/elec_module.dart new file mode 100644 index 0000000..d73b6ff --- /dev/null +++ b/lib/modules/elec/elec_module.dart @@ -0,0 +1,28 @@ +/// 电器原理图模块(规划中)。 +/// +/// 当前仅注册元数据与占位实现;实现时在 `lib/modules/elec/` 下补齐文档模型 +/// 与 UI,并在本类中替换 `PlannedModule` 为真实 [EdcModule] 实现即可。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/modules/module.dart'; + +/// 电器原理图模块单例(未开放)。 +const ElecModule elecModule = ElecModule(); + +/// 电器原理图模块。 +class ElecModule extends PlannedModule { + /// 构造模块。 + const ElecModule() + : super( + id: 'elec', + name: '电器原理图', + shortName: '电气', + icon: Icons.electric_bolt, + accent: 0xFFFFB020, + suffix: '.elec.json', + defaultName: '未命名-电器原理图', + blurb: '回路 · 元件 · 线号', + ); +} diff --git a/lib/modules/io/io_module.dart b/lib/modules/io/io_module.dart new file mode 100644 index 0000000..e1913f0 --- /dev/null +++ b/lib/modules/io/io_module.dart @@ -0,0 +1,28 @@ +/// IO 表模块(规划中)。 +/// +/// 当前仅注册元数据与占位实现;实现时在 `lib/modules/io/` 下补齐文档模型 +/// 与 UI,并在本类中替换 `PlannedModule` 为真实 [EdcModule] 实现即可。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/modules/module.dart'; + +/// IO 表模块单例(未开放)。 +const IoModule ioModule = IoModule(); + +/// IO 表模块。 +class IoModule extends PlannedModule { + /// 构造模块。 + const IoModule() + : super( + id: 'io', + name: 'IO 表', + shortName: 'IO表', + icon: Icons.grid_on, + accent: 0xFFA78BFA, + suffix: '.io.json', + defaultName: '未命名-IO表', + blurb: '点位 · 符号 · 注释', + ); +} diff --git a/lib/modules/manifest.dart b/lib/modules/manifest.dart new file mode 100644 index 0000000..bef15bf --- /dev/null +++ b/lib/modules/manifest.dart @@ -0,0 +1,267 @@ +/// 发布级模块清单:`modules/registry.json` + 每模块 `module.json` 的解析与合并。 +/// +/// 源码注册表(`lib/modules/registry.dart`)决定**编译进应用**的模块实现; +/// 发布清单决定**发布包**里的模块顺序、显示名、启用状态与元数据。应用启动时: +/// +/// 1. 桌面优先读取 exe 同级 `modules/registry.json`(发布包可见、可编辑); +/// 2. 安卓 / 开发环境回退到内置资源 `assets/modules/registry.json`; +/// 3. 清单缺失或损坏时回退到编译期注册表。 +/// +/// 注意:Flutter release 的 Dart 代码是 AOT 编译的,清单不能动态加载新的 +/// Dart 实现;清单中未编译的模块会显示为「组件未安装」(未开放)。 +library; + +import 'dart:convert'; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +/// 发布清单中的单个模块配置。 +class ModuleManifestEntry { + /// 构造模块清单项。 + const ModuleManifestEntry({ + required this.id, + required this.name, + required this.shortName, + required this.icon, + required this.accent, + required this.suffix, + required this.available, + required this.defaultName, + required this.blurb, + this.enterStatus = '', + this.version = '', + }); + + /// 模块稳定 id。 + final String id; + /// 模块显示名。 + final String name; + /// 短名。 + final String shortName; + /// 图标名称(见 [moduleIconFromName])。 + final String icon; + /// 品牌色(ARGB int)。 + final int accent; + /// 文档后缀。 + final String suffix; + /// 是否启用。 + final bool available; + /// 新建文档默认文件名。 + final String defaultName; + /// 一句话简介。 + final String blurb; + /// 进入模块状态提示。 + final String enterStatus; + /// 模块版本(发布包展示 / 升级判断用)。 + final String version; + + /// 从 JSON 解析;缺失字段使用安全默认值。 + static ModuleManifestEntry fromJson(Map j) { + return ModuleManifestEntry( + id: (j['id'] as String?)?.trim() ?? '', + name: (j['name'] as String?)?.trim() ?? '', + shortName: (j['shortName'] as String?)?.trim() ?? '', + icon: (j['icon'] as String?)?.trim() ?? '', + accent: parseModuleAccent(j['accent']), + suffix: (j['suffix'] as String?)?.trim() ?? '', + available: j['available'] as bool? ?? true, + defaultName: (j['defaultName'] as String?)?.trim() ?? '', + blurb: (j['blurb'] as String?)?.trim() ?? '', + enterStatus: (j['enterStatus'] as String?)?.trim() ?? '', + version: (j['version'] as String?)?.trim() ?? '', + ); + } +} + +/// 发布清单根对象。 +class ModuleManifest { + /// 构造清单。 + const ModuleManifest({ + required this.schema, + required this.version, + required this.modules, + }); + + /// 协议标识(`pds.modules/1`)。 + final String schema; + /// 发布版本。 + final String version; + /// 模块列表(顺序即首页 / 菜单顺序)。 + final List modules; + + /// 从 JSON 解析清单。 + /// + /// 支持两种写法:`{"modules":[...]}` 或直接数组 `[...]`。 + static ModuleManifest parse(String source) { + final Object? decoded = jsonDecode(source); + final Map? root = + decoded is Map ? decoded : null; + final List raw = root != null + ? (root['modules'] as List? ?? const []) + : (decoded is List ? decoded : const []); + final List modules = [ + for (final dynamic e in raw) + if (e is Map) + ModuleManifestEntry.fromJson(e), + ]..removeWhere((ModuleManifestEntry e) => e.id.isEmpty); + return ModuleManifest( + schema: (root?['schema'] as String?) ?? 'pds.modules/1', + version: (root?['version'] as String?) ?? '', + modules: modules, + ); + } +} + +/// 把发布清单与编译期模块合并为实际可用的模块列表。 +/// +/// - 清单顺序决定展示顺序; +/// - 编译期存在的模块使用清单元数据覆盖显示名 / 颜色 / 启用状态; +/// - 清单中有、但未编译进应用的模块生成为「组件未安装」占位; +/// - 清单为空时回退编译期列表。 +List resolveModulesFromManifest( + ModuleManifest manifest, + List compiled, +) { + if (manifest.modules.isEmpty) return compiled; + final Map byId = { + for (final EdcModule m in compiled) m.id: m, + }; + final List out = []; + for (final ModuleManifestEntry entry in manifest.modules) { + final EdcModule? base = byId.remove(entry.id); + if (base == null) { + out.add(ManifestOnlyModule(entry)); + } else { + out.add(ConfiguredModule(base: base, entry: entry)); + } + } + return out; +} + +/// 编译期模块 + 发布清单元数据的包装。 +class ConfiguredModule extends EdcModule { + /// 构造包装。 + const ConfiguredModule({required this.base, required this.entry}); + + /// 编译期实现。 + final EdcModule base; + + /// 发布清单配置。 + final ModuleManifestEntry entry; + + @override + String get id => base.id; + @override + String get name => entry.name.isEmpty ? base.name : entry.name; + @override + String get shortName => entry.shortName.isEmpty ? base.shortName : entry.shortName; + @override + IconData get icon => moduleIconFromName(entry.icon) ?? base.icon; + @override + int get accent => entry.accent == 0 ? base.accent : entry.accent; + @override + String get suffix => entry.suffix.isEmpty ? base.suffix : entry.suffix; + @override + bool get available => entry.available && base.available; + @override + String get defaultName => entry.defaultName.isEmpty ? base.defaultName : entry.defaultName; + @override + String get blurb => entry.blurb.isEmpty ? base.blurb : entry.blurb; + @override + String get enterStatus => + entry.enterStatus.isEmpty ? base.enterStatus : entry.enterStatus; + + @override + bool get hasLeftPanel => base.hasLeftPanel; + @override + bool get hasRightPanel => base.hasRightPanel; + + @override + void newDocument(AppController controller) => base.newDocument(controller); + @override + void loadDocument(AppController controller, String source, {String? path}) => + base.loadDocument(controller, source, path: path); + @override + String encodeDocument(AppController controller) => base.encodeDocument(controller); + @override + String documentName(AppController controller) => base.documentName(controller); + @override + String? filePath(AppController controller) => base.filePath(controller); + @override + bool isDirty(AppController controller) => base.isDirty(controller); + @override + Future saveTo(AppController controller, String path) => + base.saveTo(controller, path); + @override + Future markSaved(AppController controller, String displayPath) => + base.markSaved(controller, displayPath); + @override + bool isReadOnly(AppController controller) => base.isReadOnly(controller); + @override + Map buildShortcuts(ModuleUiContext ui) => + base.buildShortcuts(ui); + @override + Widget buildWorkspace(ModuleUiContext ui) => base.buildWorkspace(ui); + @override + Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) => + base.buildLeftPanel(ui, floating: floating); + @override + Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) => + base.buildRightPanel(ui, floating: floating); + @override + Widget buildStatusBar(ModuleUiContext ui) => base.buildStatusBar(ui); + @override + List buildToolbarCenter(ModuleUiContext ui, {required bool compact}) => + base.buildToolbarCenter(ui, compact: compact); + @override + List buildToolbarRight(ModuleUiContext ui) => + base.buildToolbarRight(ui); +} + +/// 发布清单中存在、但应用未编译该模块实现时的占位。 +class ManifestOnlyModule extends PlannedModule { + /// 构造未安装模块。 + ManifestOnlyModule(ModuleManifestEntry entry) + : super( + id: entry.id, + name: entry.name.isEmpty ? entry.id : entry.name, + shortName: entry.shortName.isEmpty ? entry.id : entry.shortName, + icon: moduleIconFromName(entry.icon) ?? Icons.widgets_outlined, + accent: entry.accent == 0 ? 0xFF94A3B8 : entry.accent, + suffix: entry.suffix, + defaultName: entry.defaultName, + blurb: entry.blurb.isEmpty ? '组件未安装' : '${entry.blurb} · 组件未安装', + ); +} + +/// 清单图标名称 → Material 图标。 +IconData? moduleIconFromName(String name) { + return switch (name) { + 'account_tree_outlined' => Icons.account_tree_outlined, + 'waterfall_chart' => Icons.waterfall_chart, + 'electric_bolt' => Icons.electric_bolt, + 'grid_on' => Icons.grid_on, + 'hub_outlined' => Icons.hub_outlined, + 'plumbing' => Icons.plumbing, + 'widgets_outlined' => Icons.widgets_outlined, + 'dashboard_outlined' => Icons.dashboard_outlined, + 'schema_outlined' => Icons.schema_outlined, + _ => null, + }; +} + +/// 解析清单颜色:`#RRGGBB` / `#AARRGGBB` / `0xAARRGGBB` / 十进制整数。 +int parseModuleAccent(Object? value) { + if (value is int) return value; + if (value is! String) return 0; + String s = value.trim(); + if (s.isEmpty) return 0; + if (s.startsWith('#')) s = s.substring(1); + if (s.startsWith('0x') || s.startsWith('0X')) s = s.substring(2); + if (s.length == 6) s = 'FF$s'; + final int? v = int.tryParse(s, radix: 16); + return v ?? 0; +} diff --git a/lib/modules/module.dart b/lib/modules/module.dart new file mode 100644 index 0000000..df52af9 --- /dev/null +++ b/lib/modules/module.dart @@ -0,0 +1,236 @@ +/// 模块契约:所有功能模块(时序图、架构图、后续电气 / IO / 拓扑 / PID 等) +/// 都实现 [EdcModule],并在 `lib/modules/registry.dart` 的注册表中登记。 +/// +/// 设计目标: +/// - **新增模块只改注册表**:应用外壳只依赖本契约,不出现具体模块的 +/// `if / switch`;新模块在独立目录实现后加入注册表即可出现首页卡片、 +/// 品牌菜单、窗口标题、文件打开 / 保存与工作区。 +/// - **模块自治**:模块拥有自己的文档读写、工作区 UI、工具栏、左右侧栏、 +/// 状态栏与快捷键;外壳只负责公共窗口框架、主题、文件对话框与侧栏停靠。 +/// - **共享内核**:主题、持久化、更新、授权、通用对话框仍由 `lib/` 公共层 +/// 提供;模块通过 [ModuleUiContext] 获取当前上下文。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; + +/// 模块 UI 构建上下文:外壳传给模块的共享服务与布局信息。 +class ModuleUiContext { + /// 构造上下文。 + const ModuleUiContext({ + required this.context, + required this.controller, + required this.tokens, + required this.compact, + required this.leftRail, + required this.rightRail, + required this.leftPanelWidth, + required this.rightPanelWidth, + required this.toolScale, + required this.toolFont, + required this.panelControls, + }); + + /// Flutter 构建上下文。 + final BuildContext context; + + /// 全局应用控制器(共享文档 / 撤销 / 状态)。 + final AppController controller; + + /// 当前主题令牌。 + final Tokens tokens; + + /// 是否为紧凑工具栏布局。 + final bool compact; + + /// 左侧栏是否收起为贴边轨道。 + final bool leftRail; + + /// 右侧栏是否收起为贴边轨道。 + final bool rightRail; + + /// 左侧栏宽度。 + final double leftPanelWidth; + + /// 右侧栏宽度。 + final double rightPanelWidth; + + /// 工具栏缩放系数(触屏平台更紧凑)。 + final double toolScale; + + /// 工具栏字号换算。 + final double Function(double base) toolFont; + + /// 侧栏「钉住 / 收起」按钮(外壳维护)。 + final Widget Function(bool left) panelControls; +} + +/// 功能模块契约。 +/// +/// 模块 id 是稳定标识(保存到文档 / 最近列表 / 窗口标题),不要复用。 +abstract class EdcModule { + /// 构造模块。 + const EdcModule(); + + // ===================== 元数据 ===================== + + /// 稳定 id(如 `sequence` / `architecture`)。 + String get id; + + /// 模块全名(首页卡片、菜单、窗口标题)。 + String get name; + + /// 模块短名(状态栏、紧凑菜单)。 + String get shortName; + + /// 首页 / 菜单图标。 + IconData get icon; + + /// 品牌色(ARGB)。 + int get accent; + + /// 文档后缀(如 `.seq.json`)。 + String get suffix; + + /// 是否已开放;false 时首页卡片灰显,不可进入。 + bool get available; + + /// 新建文档默认文件名(含后缀)。 + String get defaultName; + + /// 一句话简介(首页卡片)。 + String get blurb; + + /// 进入模块时的状态栏提示。 + String get enterStatus => '$name设计'; + + // ===================== 文档生命周期 ===================== + + /// 在控制器上新建模块文档。 + void newDocument(AppController controller); + + /// 从 JSON 文本加载模块文档;[path] 为源文件路径(Android 可为 null)。 + void loadDocument(AppController controller, String source, {String? path}); + + /// 把当前模块文档编码为 JSON 文本。 + String encodeDocument(AppController controller); + + /// 当前文档名(用于保存默认文件名)。 + String documentName(AppController controller); + + /// 当前文档路径(未保存时为 null)。 + String? filePath(AppController controller); + + /// 是否有未保存修改。 + bool isDirty(AppController controller); + + /// 保存到桌面路径(模块可写入自己的文档段 / .bak)。 + Future saveTo(AppController controller, String path); + + /// 外部通道保存成功后回写路径与干净状态(Android 公共目录)。 + Future markSaved(AppController controller, String displayPath); + + /// 当前视图是否只读(如时序图流程图视图)。 + bool isReadOnly(AppController controller) => false; + + /// 模块级快捷键:与外壳公共快捷键合并,模块可覆盖同名组合。 + Map buildShortcuts(ModuleUiContext ui) => + const {}; + + // ===================== UI 扩展点 ===================== + + /// 工作区(画布)内容;外壳负责在外层叠加侧栏轨道 / 浮动面板。 + Widget buildWorkspace(ModuleUiContext ui); + + /// 是否提供左侧栏(外壳据此显示停靠 / 轨道按钮)。 + bool get hasLeftPanel => true; + + /// 是否提供右侧栏。 + bool get hasRightPanel => true; + + /// 左侧栏内容;返回 null 表示该模块不需要左侧栏。 + Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) => null; + + /// 右侧栏内容;返回 null 表示该模块不需要右侧栏。 + Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) => null; + + /// 底部状态栏内容。 + Widget buildStatusBar(ModuleUiContext ui); + + /// 工具栏中段(模块专属工具:视图切换 / AI / 架构工具等)。 + List buildToolbarCenter(ModuleUiContext ui, {required bool compact}) => + const []; + + /// 工具栏右侧的模块专属工具(导出菜单 / 缩放 / 适应视图 / 单位等)。 + List buildToolbarRight(ModuleUiContext ui) => const []; +} + +/// 未开放模块占位实现:目录与注册项先建好,后续实现时替换为真实模块。 +/// +/// 这样规划中的模块(电气 / IO / 拓扑 / PID)从第一天起就拥有独立路径与 +/// 稳定 id,首页和菜单由注册表自动生成;实现时只需补全文档与 UI 方法。 +class PlannedModule extends EdcModule { + /// 构造占位模块。 + const PlannedModule({ + required this.id, + required this.name, + required this.shortName, + required this.icon, + required this.accent, + required this.suffix, + required this.defaultName, + required this.blurb, + }); + + @override + final String id; + @override + final String name; + @override + final String shortName; + @override + final IconData icon; + @override + final int accent; + @override + final String suffix; + @override + final String defaultName; + @override + final String blurb; + + @override + bool get available => false; + + @override + void newDocument(AppController controller) {} + + @override + void loadDocument(AppController controller, String source, {String? path}) {} + + @override + String encodeDocument(AppController controller) => ''; + + @override + String documentName(AppController controller) => name; + + @override + String? filePath(AppController controller) => null; + + @override + bool isDirty(AppController controller) => false; + + @override + Future saveTo(AppController controller, String path) async {} + + @override + Future markSaved(AppController controller, String displayPath) async {} + + @override + Widget buildWorkspace(ModuleUiContext ui) => const SizedBox.shrink(); + + @override + Widget buildStatusBar(ModuleUiContext ui) => const SizedBox.shrink(); +} diff --git a/lib/modules/module_registry.dart b/lib/modules/module_registry.dart deleted file mode 100644 index 53c9454..0000000 --- a/lib/modules/module_registry.dart +++ /dev/null @@ -1,149 +0,0 @@ -/// 设计模块注册表:模块元数据的唯一事实来源。 -/// -/// 首页「新建文档」网格、品牌菜单、窗口标题、文档后缀与导出能力 -/// 全部从这里读取;新增模块只需注册一条记录(未完成的模块 -/// [EdcModule.available] 为 false,界面统一灰显「未开放」)。 -library; - -import 'package:flutter/material.dart' show IconData, Icons; - -import '../model/models.dart' show AppMode; - -/// 设计模块元数据。 -class EdcModule { - /// 构造模块记录。 - const EdcModule({ - required this.id, - required this.name, - required this.shortName, - required this.icon, - required this.accent, - required this.suffix, - required this.available, - required this.defaultName, - required this.blurb, - }); - - /// 模块 id(稳定标识;文档 meta.docType 使用该值)。 - final String id; - - /// 完整中文名(首页 / 标题)。 - final String name; - - /// 短名(状态栏 / 菜单)。 - final String shortName; - - /// 图标。 - final IconData icon; - - /// 品牌色(ARGB)。 - final int accent; - - /// 文档后缀(如 `.seq.json`)。 - final String suffix; - - /// 是否已开放(false 时界面灰显「未开放」且不可进入)。 - final bool available; - - /// 新建文档的默认文件名(不含后缀)。 - final String defaultName; - - /// 一句话介绍(首页卡片)。 - final String blurb; -} - -/// 全部设计模块(顺序即首页与菜单的展示顺序:架构图在前,时序图第二)。 -const List kModules = [ - EdcModule( - id: 'architecture', - name: '架构图', - shortName: '架构图', - icon: Icons.account_tree_outlined, - accent: 0xFF34D399, - suffix: '.arch.json', - available: true, - defaultName: '未命名-架构图', - blurb: '手绘识别 · 图形库', - ), - EdcModule( - id: 'sequence', - name: '时序图', - shortName: '时序图', - icon: Icons.waterfall_chart, - accent: 0xFF4CC9F0, - suffix: '.seq.json', - available: true, - defaultName: '未命名-时序图', - blurb: 'PLC 节拍 · 三视图', - ), - EdcModule( - id: 'elec', - name: '电器原理图', - shortName: '电气', - icon: Icons.electric_bolt, - accent: 0xFFFFB020, - suffix: '.elec.json', - available: false, - defaultName: '未命名-电气原理图', - blurb: '符号 · 连线 · 线号', - ), - EdcModule( - id: 'io', - name: 'IO 表', - shortName: 'IO表', - icon: Icons.grid_on, - accent: 0xFFA78BFA, - suffix: '.io.json', - available: false, - defaultName: '未命名-IO表', - blurb: '点位 · 符号 · 注释', - ), - EdcModule( - id: 'topo', - name: '拓扑图', - shortName: '拓扑', - icon: Icons.hub_outlined, - accent: 0xFFF472B6, - suffix: '.topo.json', - available: false, - defaultName: '未命名-拓扑图', - blurb: '网络设备 · 链路', - ), - EdcModule( - id: 'pid', - name: 'PID 图', - shortName: 'PID', - icon: Icons.plumbing, - accent: 0xFFFF8A5C, - suffix: '.pid.json', - available: false, - defaultName: '未命名-PID图', - blurb: '管道 · 仪表 · 回路', - ), -]; - -/// 按 id 查找模块;找不到返回 null。 -EdcModule? moduleById(String id) { - for (final EdcModule m in kModules) { - if (m.id == id) return m; - } - return null; -} - -/// AppMode → 模块(home 或未映射值返回 null)。 -EdcModule? moduleOf(AppMode m) { - switch (m) { - case AppMode.sequence: - return moduleById('sequence'); - case AppMode.architecture: - return moduleById('architecture'); - case AppMode.home: - return null; - } -} - -/// AppMode → 窗口标题用模块名(首页用品牌名)。 -String appModeLabel(AppMode m) { - final EdcModule? mod = moduleOf(m); - return mod == null ? 'EDC易得' : 'EDC易得 · ${mod.name}设计'; -} diff --git a/lib/modules/pid/pid_module.dart b/lib/modules/pid/pid_module.dart new file mode 100644 index 0000000..9c6597f --- /dev/null +++ b/lib/modules/pid/pid_module.dart @@ -0,0 +1,28 @@ +/// PID 图模块(规划中)。 +/// +/// 当前仅注册元数据与占位实现;实现时在 `lib/modules/pid/` 下补齐文档模型 +/// 与 UI,并在本类中替换 `PlannedModule` 为真实 [EdcModule] 实现即可。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/modules/module.dart'; + +/// PID 图模块单例(未开放)。 +const PidModule pidModule = PidModule(); + +/// PID 图模块。 +class PidModule extends PlannedModule { + /// 构造模块。 + const PidModule() + : super( + id: 'pid', + name: 'PID 图', + shortName: 'PID', + icon: Icons.plumbing, + accent: 0xFFFF8A5C, + suffix: '.pid.json', + defaultName: '未命名-PID图', + blurb: '管道 · 仪表 · 回路', + ); +} diff --git a/lib/modules/registry.dart b/lib/modules/registry.dart new file mode 100644 index 0000000..7076c85 --- /dev/null +++ b/lib/modules/registry.dart @@ -0,0 +1,141 @@ +/// 模块注册表:**唯一**需要修改的模块清单文件。 +/// +/// 新增模块步骤: +/// 1. 在 `lib/modules//` 下实现 `EdcModule`(或先用 `PlannedModule` 占位); +/// 2. 在本文件顶部 import 模块单例; +/// 3. 加入下方 [kModules] 列表。 +/// +/// 首页卡片、品牌菜单、窗口标题、文档打开 / 保存后缀、最近列表与工作区 +/// 都会自动跟随注册表,不需要修改 `AppShell` / `HomeView`。 +/// +/// 发布级注册:`assets/modules/registry.json`(构建时复制到发布包 `modules/`) +/// 可覆盖模块顺序 / 显示名 / 颜色 / 启用状态;应用启动时优先读取发布清单, +/// 失败回退本文件。Flutter AOT 不能动态加载新的 Dart UI 代码,新增实现仍需 +/// 重新构建;清单只负责发布装配与可见结构。 +library; + +import 'dart:io' show File, Platform; + +import 'package:flutter/services.dart' show rootBundle; + +import 'package:sequence_diagram/modules/architecture/architecture_module.dart'; +import 'package:sequence_diagram/modules/elec/elec_module.dart'; +import 'package:sequence_diagram/modules/io/io_module.dart'; +import 'package:sequence_diagram/modules/manifest.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/modules/pid/pid_module.dart'; +import 'package:sequence_diagram/modules/sequence/sequence_module.dart'; +import 'package:sequence_diagram/modules/topo/topo_module.dart'; + +export 'package:sequence_diagram/modules/module.dart'; + +/// 编译进应用的模块(顺序 = 默认首页 / 菜单展示顺序)。 +/// +/// 发布包可通过 `modules/registry.json` 覆盖顺序 / 显示名 / 启用状态; +/// 未在清单中出现的编译期模块会被隐藏。 +const List kCompiledModules = [ + architectureModule, + sequenceModule, + elecModule, + ioModule, + topoModule, + pidModule, +]; + +List _modules = List.unmodifiable(kCompiledModules); +String _moduleRegistrySource = 'compiled'; + +/// 当前生效的模块列表(发布清单已合并)。 +List get kModules => _modules; + +/// 当前模块清单来源(排查发布包问题用)。 +String get moduleRegistrySource => _moduleRegistrySource; + +/// 初始化发布级模块清单。 +/// +/// 桌面优先读取 exe 同级 `modules/registry.json`;安卓 / 开发环境回退到 +/// `assets/modules/registry.json`;失败时回退 [kCompiledModules]。 +/// 必须在 `runApp` 前调用;运行中修改清单需要重启应用。 +Future initModuleRegistry({ + String? manifestText, + String? manifestPath, +}) async { + String? text = manifestText; + String source = manifestText != null ? 'override' : ''; + if (text == null && manifestPath != null) { + try { + final File f = File(manifestPath); + if (await f.exists()) { + text = await f.readAsString(); + source = manifestPath; + } + } catch (_) {} + } + if (text == null && + (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { + try { + final String exeDir = File(Platform.resolvedExecutable).parent.path; + final File external = File( + '$exeDir${Platform.pathSeparator}modules${Platform.pathSeparator}registry.json', + ); + if (await external.exists()) { + text = await external.readAsString(); + source = external.path; + } + } catch (_) {} + } + if (text == null) { + try { + text = await rootBundle.loadString('assets/modules/registry.json'); + source = 'assets/modules/registry.json'; + } catch (_) {} + } + if (text == null) { + _modules = List.unmodifiable(kCompiledModules); + _moduleRegistrySource = 'compiled'; + return; + } + try { + final ModuleManifest manifest = ModuleManifest.parse(text); + final List resolved = + resolveModulesFromManifest(manifest, kCompiledModules); + if (resolved.isEmpty) { + _modules = List.unmodifiable(kCompiledModules); + _moduleRegistrySource = 'compiled (empty manifest)'; + } else { + _modules = List.unmodifiable(resolved); + _moduleRegistrySource = source; + } + } catch (_) { + _modules = List.unmodifiable(kCompiledModules); + _moduleRegistrySource = 'compiled (invalid manifest)'; + } +} + +/// 恢复编译期注册表(测试 / 重置用)。 +void resetModuleRegistry() { + _modules = List.unmodifiable(kCompiledModules); + _moduleRegistrySource = 'compiled'; +} + +/// 按 id 查找模块;id 为 null / 未注册时返回 null(首页)。 +EdcModule? moduleById(String? id) { + if (id == null || id.isEmpty) return null; + for (final EdcModule m in kModules) { + if (m.id == id) return m; + } + return null; +} + +/// 已开放模块(首页可进入)。 +Iterable get availableModules => + kModules.where((EdcModule m) => m.available); + +/// 品牌名(首页 / 窗口标题)。 +const String kBrandName = 'PDS流程设计套件'; + +/// 窗口标题:首页显示品牌,模块显示「品牌 · 模块设计」。 +String moduleTitle(String? moduleId) { + final EdcModule? m = moduleById(moduleId); + return m == null ? kBrandName : '$kBrandName · ${m.name}设计'; +} diff --git a/lib/ai/ai_client.dart b/lib/modules/sequence/ai/ai_client.dart similarity index 80% rename from lib/ai/ai_client.dart rename to lib/modules/sequence/ai/ai_client.dart index 0506232..c424f46 100644 --- a/lib/ai/ai_client.dart +++ b/lib/modules/sequence/ai/ai_client.dart @@ -19,7 +19,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import '../model/models.dart'; +import 'package:sequence_diagram/model/models.dart'; /// AI 请求参数。 class AiSettings { @@ -53,9 +53,13 @@ class AiModelOption { } /// 预设模型列表:Flash(快速)与 Pro(深度推理)。 +/// +/// 模型 id 必须与 DeepSeek 当前 API 保持一致(`deepseek-flash` / +/// `deepseek-v4-pro`);旧 id(`deepseek-chat` / `deepseek-reasoner`) +/// 已下线,继续使用会直接返回 400 Model Not Exist。 const List kAiModels = [ - AiModelOption('deepseek-chat', 'Flash · 快速'), - AiModelOption('deepseek-reasoner', 'Pro · 深度推理'), + AiModelOption('deepseek-flash', 'Flash · 快速'), + AiModelOption('deepseek-v4-pro', 'Pro · 深度推理'), ]; /// AI 调用异常(携带可读信息,便于界面直接展示)。 @@ -130,9 +134,9 @@ class AiClient { static const String _systemPrompt = ''' 你是工业节拍 / 相位角设计助手。请把用户的自然语言描述转换成严格的 JSON,且**只能输出 JSON**,不要输出解释、注释或 Markdown 代码块。 -JSON 结构(协议 seqdiagram/1.2): +JSON 结构(协议 edc/1.3): { - "schema": "seqdiagram/1.2", + "schema": "edc/1.3", "project": { "name": "项目名称", "units": { "timeUnit": "s", "phaseUnit": "deg", "precision": -1, "snapAngle": 1, "snapTime": 0.1, "cycleInputPolicy": "keepAngle" }, @@ -162,6 +166,8 @@ JSON 结构(协议 seqdiagram/1.2): 6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。 7. 动作命名简洁(不超过 8 个汉字);不要编造不存在的工位,stationId 必须引用 stations 中已有的 id。 8. 只输出 JSON 本体,且必须是单个可直接 JSON 解析的对象。 +9. 只需要输出时序图数据(name / units / cycle / stations / actions / viewState / phaseZones), + 不需要也没有 `arch`、`keepEmptyLanes`、`laneSlots` 等字段;修改模式由程序负责保留原有架构图数据。 '''; /// 根据自然语言 [prompt] 生成或修改项目(流式、可取消、带自动纠错)。 @@ -189,7 +195,9 @@ JSON 结构(协议 seqdiagram/1.2): throw AiException('请输入自然语言描述'); } - final String baseJson = base == null ? '' : jsonEncode(base.toJson()); + // 修改模式只发送时序部分:架构图 / 画布设置(arch、泳道、自动保存) + // 体积大且与本次修改无关,不回传给模型,也能避免模型丢掉原有架构图。 + final String baseJson = base == null ? '' : jsonEncode(base.toJson(includeArch: false)); final String firstUser = base == null ? prompt.trim() : '现有工程 JSON:\n$baseJson\n\n' @@ -232,7 +240,20 @@ JSON 结构(协议 seqdiagram/1.2): if (fixed.actions.isEmpty) { throw const FormatException('没有任何动作'); } - return AiResult(fixed, warnings); + // 修改模式:只采纳 AI 返回的时序内容,架构图 / 画布设置 / 泳道设置 + // 一律沿用原工程,避免一次 AI 修改把架构图或用户视图状态清空。 + final Project result = base == null + ? fixed + : base.copyWith( + name: fixed.name, + schema: fixed.schema, + cycle: fixed.cycle, + stations: fixed.stations, + actions: fixed.actions, + units: fixed.units, + phaseZones: fixed.phaseZones, + ); + return AiResult(result, warnings); } on AiException { rethrow; // 网络 / 鉴权 / 超时 / 取消等错误不重试 } on FormatException catch (e) { @@ -270,14 +291,16 @@ JSON 结构(协议 seqdiagram/1.2): 'messages': messages, 'stream': true, 'temperature': 0.2, + 'max_tokens': 131072, 'response_format': {'type': 'json_object'}, - // 兼容支持推理强度的接口;不支持时会被忽略。 + // 当前 DeepSeek 模型默认开启思考,这里显式开启并按 UI 选择传推理强度。 + 'thinking': {'type': 'enabled'}, 'reasoning_effort': settings.effort, })); final HttpClientResponse res = await req.close(); if (res.statusCode != 200) { final String text = await res.transform(utf8.decoder).join(); - throw AiException('接口返回 ${res.statusCode}:${_brief(text)}'); + throw AiException(_apiError(res.statusCode, text)); } final StringBuffer content = StringBuffer(); final StringBuffer reasoning = StringBuffer(); @@ -332,10 +355,21 @@ JSON 结构(协议 seqdiagram/1.2): } } - /// 结果清洗:修正非法时长与越界角度、剔除指向不存在动作的依赖、归一化层号。 + /// 结果清洗:补齐工位、修正非法时长与越界角度、剔除指向不存在动作的 + /// 依赖、归一化层号。 /// /// 返回修正后的项目与人类可读的修正说明(供状态栏提示)。 static (Project, List) _sanitize(Project p) { + // 工位是动作的归属单元:模型偶发漏写 stations 或编造 stationId 时, + // 直接引用会让条形视图整组动作消失,这里兜底并提示。 + final List stations = p.stations.isEmpty + ? const [ + Station(id: 'ST1', name: '工位1', order: 0, color: 0xFF4CC9F0), + ] + : p.stations; + final Set stationIds = {for (final Station s in stations) s.id}; + final String fallbackStation = stations.first.id; + int fixedStation = 0; final Set ids = {for (final Action a in p.actions) a.id}; int fixedDur = 0; int droppedDeps = 0; @@ -353,6 +387,11 @@ JSON 结构(协议 seqdiagram/1.2): dur = 720; fixedDur++; } + String stationId = a.stationId; + if (!stationIds.contains(stationId)) { + stationId = fallbackStation; + fixedStation++; + } final List deps = []; for (final Dependency d in a.deps) { if (d.fromId == a.id || !ids.contains(d.fromId) || !ids.contains(d.toId)) { @@ -361,7 +400,12 @@ JSON 结构(协议 seqdiagram/1.2): } deps.add(d); } - actions.add(a.copyWith(startAngle: start, durationAngle: dur, deps: deps)); + actions.add(a.copyWith( + stationId: stationId, + startAngle: start, + durationAngle: dur, + deps: deps, + )); } // 层号归一化为连续的 0..N-1(保持相对顺序),避免稀疏层号造成空白轨道。 final List layers = {for (final Action a in actions) a.layer}.toList()..sort(); @@ -373,8 +417,36 @@ JSON 结构(协议 seqdiagram/1.2): ]; final List warnings = []; if (fixedDur > 0) warnings.add('修正 $fixedDur 处非法时长'); + if (fixedStation > 0) warnings.add('修正 $fixedStation 处无效工位'); if (droppedDeps > 0) warnings.add('剔除 $droppedDeps 条无效依赖'); - return (p.copyWith(actions: normalized), warnings); + return (p.copyWith(stations: stations, actions: normalized), warnings); + } + + /// 把非 200 响应转换为可读错误:优先取 DeepSeek 的 `error.message`, + /// 并对常见状态码给出排查提示(模型下线 / Key 无效 / 余额不足)。 + static String _apiError(int code, String raw) { + String detail = _brief(raw); + try { + final Object? j = jsonDecode(raw); + if (j is Map) { + final Object? err = j['error']; + if (err is Map && err['message'] is String) { + detail = _brief(err['message'] as String); + } else if (j['message'] is String) { + detail = _brief(j['message'] as String); + } + } + } catch (_) {} + switch (code) { + case 401: + return 'API Key 无效或已过期(401):$detail'; + case 402: + return 'DeepSeek 账户余额不足(402):$detail'; + case 429: + return '请求过于频繁(429):$detail'; + default: + return '接口返回 $code:$detail'; + } } /// 从模型输出中剥离 Markdown 代码围栏并截取首个 JSON 对象。 diff --git a/lib/export/drawio_writer.dart b/lib/modules/sequence/export/drawio_writer.dart similarity index 94% rename from lib/export/drawio_writer.dart rename to lib/modules/sequence/export/drawio_writer.dart index e284f74..3eac542 100644 --- a/lib/export/drawio_writer.dart +++ b/lib/modules/sequence/export/drawio_writer.dart @@ -5,7 +5,7 @@ /// - 几何完全复用 [FlowLayout](与屏幕画布、SVG 导出同一套坐标与走线), /// 保证三种载体(画布 / drawio / SVG)内容一致; /// - 输出标准 `` 文档:节点保留动作颜色与「时长 · 工位」语义, -/// 连线保留 FS / SS 类型与偏移角标签,泳道为背景带、相位为竖排文字带, +/// 连线保留 FS / SS 类型与偏移时间标签,泳道为背景带、相位为竖排文字带, /// 导入 draw.io 后可直接继续排布与编辑。 /// /// 输出约定: @@ -16,9 +16,10 @@ library; import 'dart:ui'; -import '../layout/flow_layout.dart'; -import '../model/models.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'export_fit.dart'; /// drawio 文档写入器。 @@ -163,7 +164,7 @@ class DrawioWriter { /// 写入依赖连线:以 source / target 引用节点,drawio 自动正交布线并可再编辑。 /// - /// 样式与画布一致:FS 绿实线、SS 琥珀虚线(标签标注偏移角)、关键路径加粗。 + /// 样式与画布一致:FS 绿实线、SS 琥珀虚线(标签标注偏移时间)、关键路径加粗。 void _edges(FlowLayout layout) { int i = 0; for (final FlowEdge e in layout.edges) { @@ -174,7 +175,9 @@ class DrawioWriter { final String label = switch (e.type) { null => '', DepType.fs => 'FS', - DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°', + DepType.ss => e.offset == 0 + ? 'SS' + : 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}', DepType.ff => 'FF', DepType.sf => 'SF', }; diff --git a/lib/export/export_fit.dart b/lib/modules/sequence/export/export_fit.dart similarity index 56% rename from lib/export/export_fit.dart rename to lib/modules/sequence/export/export_fit.dart index 9c57178..ad158d9 100644 --- a/lib/export/export_fit.dart +++ b/lib/modules/sequence/export/export_fit.dart @@ -12,38 +12,14 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; -import '../layout/layout.dart'; -import '../layout/flow_layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../render/bar_painter.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/export/export_geometry.dart'; -/// 导出画布尺寸(固定,逻辑单位)。 -const Size kExportSize = Size(1920, 1080); - -/// 导出渲染像素比:按 2 倍像素渲染(3840×2160),保证高分辨率屏幕下清晰锐利。 -const double kExportPixelRatio = 2.0; - -/// 内容区(标题下方、图例上方)。 -const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016); - -/// 导出适配结果:内容变换 `scale` + `translate(tx, ty)`。 -class ExportFit { - /// 构造适配结果。 - const ExportFit(this.scale, this.tx, this.ty); - - /// 缩放系数。 - final double scale; - /// 水平平移。 - final double tx; - /// 垂直平移。 - final double ty; - - /// SVG transform 属性值。 - String get svgTransform => - 'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})'; -} +export 'package:sequence_diagram/export/export_geometry.dart' show ExportFit, kExportContentArea, kExportPixelRatio, kExportSize, exportTokens; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/modules/sequence/render/bar_painter.dart'; /// 计算内容在 [area] 内的适配变换。 /// @@ -94,51 +70,3 @@ String exportSubtitle(ViewMode mode) => switch (mode) { String exportLegend(Project project) => '时序图设计 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°'; -/// 导出专用令牌:始终使用浅色、**纯白背景**(印刷 / 工艺卡导向), -/// 文字、语义色与屏幕浅色主题保持一致。 -/// -/// 无论当前屏幕主题是深是浅,导出的 PNG / SVG 背景都是纯白、文字深色, -/// 避免「导出背景不是纯白」的问题。 -Tokens exportTokens(Tokens base) { - return Tokens( - brightness: Brightness.light, - bg: Colors.white, - canvas1: Colors.white, - canvas2: Colors.white, - chrome: base.chrome, - panel: Colors.white, - panel2: Colors.white, - dialog: Colors.white, - line: base.line, - line2: base.line2, - text: base.text, - text2: base.text2, - sub: base.sub, - dim: base.dim, - accent: base.accent, - accent2: base.accent2, - ok: base.ok, - warn: base.warn, - danger: base.danger, - fs: base.fs, - ss: base.ss, - crit: base.crit, - chip: Colors.white, - dial: Colors.white, - arcText: base.arcText, - onAccent: base.onAccent, - ringA: base.ringA, - ringB: base.ringB, - ringEdge: base.ringEdge, - ringLabel: base.ringLabel, - info: Colors.white, - track: base.track, - sel: base.sel, - grid: base.grid, - shadow: base.shadow, - shadowOp: 0.10, - selOutline: base.selOutline, - overlay: base.overlay, - tailOp: base.tailOp, - ); -} diff --git a/lib/export/export_renderer.dart b/lib/modules/sequence/export/export_renderer.dart similarity index 91% rename from lib/export/export_renderer.dart rename to lib/modules/sequence/export/export_renderer.dart index c83608f..a625644 100644 --- a/lib/export/export_renderer.dart +++ b/lib/modules/sequence/export/export_renderer.dart @@ -11,11 +11,11 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart' hide Action; -import '../model/models.dart'; -import '../render/bar_painter.dart'; -import '../render/circular_painter.dart'; -import '../render/flow_painter.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/modules/sequence/render/bar_painter.dart'; +import 'package:sequence_diagram/modules/sequence/render/circular_painter.dart'; +import 'package:sequence_diagram/modules/sequence/render/flow_painter.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'export_fit.dart'; /// 渲染导出 PNG 并返回字节。 diff --git a/lib/export/svg_writer.dart b/lib/modules/sequence/export/svg_writer.dart similarity index 97% rename from lib/export/svg_writer.dart rename to lib/modules/sequence/export/svg_writer.dart index 6c0a70b..6817ab6 100644 --- a/lib/export/svg_writer.dart +++ b/lib/modules/sequence/export/svg_writer.dart @@ -20,11 +20,11 @@ library; import 'dart:math' as math; import 'dart:ui'; -import '../layout/layout.dart'; -import '../layout/flow_layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; import 'export_fit.dart'; /// SVG 文档写入器。 @@ -164,7 +164,7 @@ class SvgWriter { } _b.write(''); - // 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移角语义。 + // 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移时间语义。 if (project.viewState.showDeps) { _b.write(''); final Map index = {}; @@ -339,7 +339,9 @@ class SvgWriter { if (e.type != null) { final String text = switch (e.type!) { DepType.fs => 'FS', - DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°', + DepType.ss => e.offset == 0 + ? 'SS' + : 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}', DepType.ff => 'FF', DepType.sf => 'SF', }; diff --git a/lib/modules/sequence/layout/dep_routes.dart b/lib/modules/sequence/layout/dep_routes.dart new file mode 100644 index 0000000..5c665db --- /dev/null +++ b/lib/modules/sequence/layout/dep_routes.dart @@ -0,0 +1,565 @@ +/// 依赖连线的共享走线计算。 +/// +/// 条形视图 / 圆周视图的**画布绘制、标签放置与命中测试**(点选连线、 +/// 沿法线拖拽调整走线)都使用这里的同一份几何,避免绘制与命中不一致: +/// - 自动错开:同一走线分组内的多条依赖依次错开,先解决“完全重叠”; +/// - 手动偏移:[Dependency.routeOffset] 叠加在自动错开之上(拖拽连线的结果)。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:sequence_diagram/model/models.dart'; +import 'layout.dart'; + +// ===================== 通用工具 ===================== + +/// 点 [p] 到线段 [a]–[b] 的最短距离。 +double distanceToSegment(Offset p, Offset a, Offset b) { + final Offset ab = b - a; + final double len2 = ab.dx * ab.dx + ab.dy * ab.dy; + if (len2 <= 0) return (p - a).distance; + final double t = (((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2).clamp(0.0, 1.0); + return (p - (a + ab * t)).distance; +} + +/// 点 [p] 到折线 [pts] 的最短距离。 +double distanceToPolyline(List pts, Offset p) { + double best = double.infinity; + for (int i = 0; i + 1 < pts.length; i++) { + final double d = distanceToSegment(p, pts[i], pts[i + 1]); + if (d < best) best = d; + } + return best; +} + +/// 点 [p] 到路径 [path] 的近似最短距离(按弧长采样,步长 [step])。 +double distanceToPath(Path path, Offset p, {double step = 4}) { + double best = double.infinity; + for (final PathMetric m in path.computeMetrics()) { + for (double d = 0; d < m.length; d += step) { + final Tangent? t = m.getTangentForOffset(d); + if (t == null) continue; + final double dist = (t.position - p).distance; + if (dist < best) best = dist; + } + } + return best; +} + +/// 第 [k] 档自动错开量(px):0、−6、+6、−12、+12 … +/// +/// 同一走线分组内第二条起依次错开,避免多条依赖完全重叠。 +double staggerOffset(int k) { + if (k <= 0) return 0; + return (k.isOdd ? -1 : 1) * ((k + 1) ~/ 2) * 6.0; +} + +/// 拖拽调整走线时的移动轴(走线的“法线”方向)。 +/// +/// - [vertical]:上下拖动——平移水平走线段(条形 / 流程图的常见形态); +/// - [horizontal]:左右拖动——平移纵向走线走廊(跨行绕行走廊 / 同层绕行)。 +enum RouteAxis { vertical, horizontal } + +/// 拖拽走线时可用的最大手动偏移(px,双向)。 +const double kMaxRouteOffset = 200; + +// ===================== 条形视图 ===================== + +/// 条形视图的一条依赖走线。 +class BarDepRoute { + /// 构造。 + BarDepRoute(this.dep, this.points, this.arrowTip, this.arrowDir, this.chipCenter, this.axis, + {this.chipRun = double.infinity, + this.chipRunMargin = 0, + this.chipAltAnchor = Offset.zero, + this.junctionOnly = false}); + + /// 对应依赖。 + final Dependency dep; + /// 折线顶点(含起点与箭头端点)。 + final List points; + /// 箭头端点。 + final Offset arrowTip; + /// 箭头方向(分量式)。 + final Offset arrowDir; + /// 标签中心(默认位置,避让前)。 + final Offset chipCenter; + /// 拖拽方向:vertical = 上下拖动平移横线;horizontal = 左右拖动平移纵向走廊。 + final RouteAxis axis; + + /// 标签挂钩的水平行程长度(跑长时用于判断是否需要把标签移到箭头外侧)。 + /// + /// 默认 [double.infinity] 表示不做外移判断(跨行走廊等)。 + final double chipRun; + + /// 外移判断余量:行程 `< 标签宽 + 余量` 时把标签移到 [chipAltAnchor]。 + final double chipRunMargin; + + /// 外移时标签的锚点(绘制端会再加半个标签宽)。 + final Offset chipAltAnchor; + + /// 动作紧贴时只显示连接点标签,隐藏连线与箭头(由绘制层处理)。 + final bool junctionOnly; + + /// 依赖键 `from->to`。 + String get key => '${dep.fromId}->${dep.toId}'; +} + +/// 条形依赖在动作条一端的锚点。 +/// +/// [point] 为线条端点(目标端为箭头尖端);[dir] 为箭头进入方向(源端为 +/// 离开方向);[corner] 表示端点已退到条块的上/下角;[vSide] 为角点所在 +/// 一侧(-1 上、+1 下)。 +class _BarEnd { + const _BarEnd(this.point, this.dir, this.corner, this.vSide); + + final Offset point; + final Offset dir; + final bool corner; + final int vSide; +} + +/// 判断端点前的水平通道是否被其它动作条遮挡(宽 8px,条高中间 ±3px)。 +/// +/// 遮挡时把端点退到端部的上/下角,保证线条从角上引出而不是贴着邻条走。 +bool _barEndBlocked(double edge, double outward, double centerY, Iterable obstacles) { + const double clearance = 9; + final Rect probe = Rect.fromLTRB( + math.min(edge, edge + outward * clearance), + centerY - 3, + math.max(edge, edge + outward * clearance), + centerY + 3, + ); + for (final Rect r in obstacles) { + if (r.overlaps(probe)) return true; + } + return false; +} + +/// 源端锚点:默认取条块左/右端点中心;端部有遮挡时取朝向目标一侧的上下角。 +_BarEnd _startEnd(Rect bar, int side, int cornerSide, Iterable obstacles, + {bool forceCorner = false}) { + final double edge = side > 0 ? bar.right : bar.left; + final double outward = side > 0 ? 1 : -1; + final double cy = bar.center.dy; + if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) { + return _BarEnd(Offset(edge + outward * 2, cy), Offset(outward, 0), false, 0); + } + final int vs = cornerSide == 0 ? 1 : cornerSide; + final double y = vs > 0 ? bar.bottom - 2 : bar.top + 2; + return _BarEnd(Offset(edge + outward * 1.5, y), Offset(0, vs.toDouble()), true, vs); +} + +/// 目标端锚点:默认取条块左/右端点中心(箭头停在端点外 2px);端部有遮挡 +/// 时取朝向源条一侧的上下角,箭头从角外垂直指向条块。 +_BarEnd _targetEnd(Rect bar, int side, int cornerSide, Iterable obstacles, + {bool forceCorner = false}) { + final double edge = side > 0 ? bar.right : bar.left; + final double outward = side > 0 ? 1 : -1; + final double cy = bar.center.dy; + if (!forceCorner && !_barEndBlocked(edge, outward, cy, obstacles)) { + return _BarEnd(Offset(edge + outward * 2, cy), Offset(-outward, 0), false, 0); + } + final int vs = cornerSide == 0 ? 1 : cornerSide; + final double y = vs > 0 ? bar.bottom + 2 : bar.top - 2; + return _BarEnd( + Offset(edge + outward * 1.5, y), Offset(0, -vs.toDouble()), true, vs); +} + +/// 计算条形视图的全部依赖走线(含自动错开与手动偏移)。 +/// +/// 端点规则(FS / SS / FF / SF 均按语义取条块前端或后端): +/// 1. 默认从条块的左/右端点中心引出;FS/FF 从后端(右端)出发, +/// SS/SF 从前端(左端)出发;目标端按 FS/SS 取前端、FF/SF 取后端; +/// 2. 当端点临近被其它动作条遮挡(或同泳道走线会穿过条块)时,退到该端部 +/// 的上/下角引出,再从角外绕行。 +/// +/// 走线分三种情形:同泳道(水平线或上下绕行)、相邻泳道(Z 形)、跨多行 +/// (外侧纵向走廊);同组自动错开 + [Dependency.routeOffset] 手动偏移。 +List buildBarDepRoutes(Project project, BarLayout layout) { + final Map rectById = { + for (final Action a in project.actions) a.id: layout.rectFor(a), + }; + final Map laneIndex = { + for (final Action a in project.actions) a.id: layout.laneIndexOf(a.layer), + }; + final Map seen = {}; + final List out = []; + for (final Action to in layout.ordered) { + for (final Dependency d in to.deps) { + final Action? from = project.actionById(d.fromId); + if (from == null) continue; + final Rect? ra = rectById[from.id]; + final Rect? rb = rectById[to.id]; + if (ra == null || rb == null) continue; + // 端点遮挡检查要包含“对方条块”:动作前后贴紧时,源端被目标条块 + // 挡住、目标端被源条块挡住,此时应退到上下角并从条块外侧绕行。 + final List obstaclesForStart = [ + for (final MapEntry e in rectById.entries) + if (e.key != from.id) e.value, + ]; + final List obstaclesForEnd = [ + for (final MapEntry e in rectById.entries) + if (e.key != to.id) e.value, + ]; + final int ia = laneIndex[from.id] ?? 0; + final int ib = laneIndex[to.id] ?? 0; + const double barHalf = BarLayout.barH / 2; + final double sy = ra.center.dy; + final double ty = rb.center.dy; + final int dirY = ty > sy ? 1 : (ty < sy ? -1 : 0); + final bool sameRow = dirY == 0; + final bool adjacentLane = (ib - ia).abs() <= 1; + // 端点语义:FS/FF 从后端出发,SS/SF 从前端出发;目标端 FS/SS 为前端, + // FF/SF 为后端。 + final int fromSide = + (d.type == DepType.fs || d.type == DepType.ff) ? 1 : -1; + final int toSide = + (d.type == DepType.fs || d.type == DepType.ss) ? -1 : 1; + final String groupKey = + sameRow ? 'S$ia' : (adjacentLane ? 'A$ia→$ib' : 'M$ia→$ib'); + final int k = seen.putIfAbsent(groupKey, () => 0); + seen[groupKey] = k + 1; + final double stagger = staggerOffset(k); + // 同泳道无上下方向时,按走线偏移/错开量决定绕上还是绕下。 + final int cornerSide = dirY != 0 + ? dirY + : (stagger + d.routeOffset >= 0 ? 1 : -1); + + if (sameRow) { + // 前后动作紧贴(首尾相接)时,连线/箭头会挤在接缝处且不可读: + // 隐藏走线,只在接缝处显示依赖标签。 + final bool tight = + (rb.left - ra.right).abs() <= 4 || (ra.left - rb.right).abs() <= 4; + if (tight) { + final bool toRight = rb.center.dx >= ra.center.dx; + final double junctionX = + toRight ? (ra.right + rb.left) / 2 : (ra.left + rb.right) / 2; + out.add(BarDepRoute( + d, + const [], + Offset.zero, + const Offset(1, 0), + Offset(junctionX, ra.top - 10), + RouteAxis.vertical, + junctionOnly: true, + )); + continue; + } + // 同泳道:默认一条水平线;端点被遮挡或语义端点背向对方时,从 + // 端部上/下角绕行(避免线穿过两个条块)。 + final bool sourceFaces = + (rb.center.dx - ra.center.dx) * fromSide >= 0; + final bool targetFaces = + (ra.center.dx - rb.center.dx) * toSide >= 0; + _BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart); + _BarEnd t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd); + final bool straight = !s.corner && !t.corner && sourceFaces && targetFaces; + if (straight) { + final double y = sy + stagger + d.routeOffset; + final Offset sp = Offset(s.point.dx, y); + final Offset tp = Offset(t.point.dx, y); + out.add(BarDepRoute( + d, + [sp, tp], + tp, + t.dir, + Offset((sp.dx + tp.dx) / 2, y - (barHalf + 9)), + RouteAxis.vertical, + chipRun: (tp.dx - sp.dx).abs(), + chipRunMargin: 8, + chipAltAnchor: Offset(tp.dx + 6, y - (barHalf + 9)), + )); + } else { + // 只对背向对方 / 被遮挡的那一端退角,另一端仍从端点中心进出。 + if (!sourceFaces || s.corner) { + s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart, forceCorner: true); + } + if (!targetFaces || t.corner) { + t = _targetEnd(rb, toSide, cornerSide, obstaclesForEnd, forceCorner: true); + } + final int side = s.corner + ? s.vSide + : (t.corner ? t.vSide : cornerSide); + double runY = sy + side * (barHalf + 10) + stagger + d.routeOffset; + runY = side > 0 + ? math.max(runY, ra.bottom + 6) + : math.min(runY, ra.top - 6); + final double tx = + t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10; + final List pts = [s.point, Offset(s.point.dx, runY), Offset(tx, runY)]; + if (t.corner) { + pts.add(t.point); + } else { + pts.add(Offset(tx, t.point.dy)); + pts.add(t.point); + } + out.add(BarDepRoute( + d, + pts, + t.point, + t.dir, + // 绕行线在条块外侧,标签也放到线外侧,避免压住动作条。 + Offset((ra.center.dx + rb.center.dx) / 2, runY + side * (barHalf + 9)), + RouteAxis.vertical, + chipRun: (tx - s.point.dx).abs(), + chipRunMargin: 8, + chipAltAnchor: Offset( + t.point.dx + 6, + t.corner ? t.point.dy + side * 10 : t.point.dy - 12, + ), + )); + } + continue; + } + + final _BarEnd s = _startEnd(ra, fromSide, cornerSide, obstaclesForStart); + final _BarEnd t = _targetEnd(rb, toSide, -cornerSide, obstaclesForEnd); + if (adjacentLane) { + // 相邻泳道:端部引出后在两泳道之间的中线走水平段;同组错开 + 手动偏移。 + final double mid = (sy + ty) / 2 + stagger + d.routeOffset; + final List pts = [s.point]; + if (!s.corner) { + final double sx2 = s.point.dx + s.dir.dx * 10; + pts.add(Offset(sx2, s.point.dy)); + pts.add(Offset(sx2, mid)); + } else { + pts.add(Offset(s.point.dx, mid)); + } + final double tx2 = t.corner ? t.point.dx : t.point.dx - t.dir.dx * 10; + pts.add(Offset(tx2, mid)); + if (t.corner) { + pts.add(t.point); + } else { + pts.add(Offset(tx2, t.point.dy)); + pts.add(t.point); + } + out.add(BarDepRoute( + d, + pts, + t.point, + t.dir, + Offset((ra.center.dx + rb.center.dx) / 2, mid), + RouteAxis.vertical, + chipRun: (tx2 - s.point.dx).abs(), + chipRunMargin: 10, + chipAltAnchor: Offset( + t.point.dx + 6, + t.point.dy + (t.corner ? t.dir.dy * 10 : -12), + ), + )); + } else { + // 跨多行:扫描区间内所有条块边界,在外侧选一条纵向走廊;同组按 + // ±12px 错开走廊,手动偏移作用于走廊横向位置。 + final double sx = s.point.dx; + final double tx = t.point.dx; + double maxRight = 0; + double minLeft = double.infinity; + final List lanes = layout.lanes; + for (int r = math.min(ia, ib) + 1; r < math.max(ia, ib); r++) { + if (r < 0 || r >= lanes.length) continue; + for (final Action aa in layout.actionsInLane(lanes[r])) { + final Rect rr = layout.rectFor(aa); + maxRight = math.max(maxRight, rr.right); + minLeft = math.min(minLeft, rr.left); + } + } + final double shift = stagger * 2 + d.routeOffset; + double lane = math.max(math.max(sx, tx), maxRight) + 28 + shift; + if (lane > layout.plotRight - 16) { + lane = math.min(math.min(sx, tx), minLeft) - 28 - shift; + } + final double srcGapY = sy + dirY * (barHalf + 14); + final double gapY = ty - dirY * (barHalf + 6); + final List pts = [s.point]; + if (!s.corner) { + final double sx2 = s.point.dx + s.dir.dx * 10; + pts.add(Offset(sx2, s.point.dy)); + pts.add(Offset(sx2, srcGapY)); + } else { + pts.add(Offset(s.point.dx, srcGapY)); + } + pts.add(Offset(lane, srcGapY)); + pts.add(Offset(lane, gapY)); + if (t.corner) { + pts.add(Offset(t.point.dx, gapY)); + pts.add(t.point); + } else { + final double tx2 = t.point.dx - t.dir.dx * 10; + pts.add(Offset(tx2, gapY)); + pts.add(Offset(tx2, t.point.dy)); + pts.add(t.point); + } + out.add(BarDepRoute( + d, + pts, + t.point, + t.dir, + Offset((lane + tx) / 2, gapY - (barHalf + 1)), + RouteAxis.horizontal, + )); + } + } + } + return out; +} + +/// 命中条形依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。 +BarDepRoute? hitBarDep(List routes, Offset p, double maxDist) { + BarDepRoute? best; + double bestD = maxDist; + for (final BarDepRoute r in routes) { + final double d = distanceToPolyline(r.points, p); + if (d < bestD) { + bestD = d; + best = r; + } + } + return best; +} + +// ===================== 圆周视图 ===================== + +/// 圆周视图的一条依赖走线(径向 → 圆弧 → 径向)。 +class ArcDepRoute { + /// 构造。 + ArcDepRoute(this.dep, this.center, this.rA, this.rB, this.rC, this.rTip, this.aEnd, this.aStart, + this.degenerate, this.cw, this.large, this.chipR, this.chipDeg, + {this.junctionOnly = false}); + + /// 对应依赖。 + final Dependency dep; + /// 圆心。 + final Offset center; + /// 源环半径。 + final double rA; + /// 目标环半径。 + final double rB; + /// 绕行半径(自动错开 + 手动偏移作用于此)。 + final double rC; + /// 箭头落点半径。 + final double rTip; + /// 源弧末端角(度)。 + final double aEnd; + /// 目标弧起点角(度)。 + final double aStart; + /// 起止角几乎重合(退化)时改画短箭头。 + final bool degenerate; + /// 圆弧是否顺时针。 + final bool cw; + /// 是否大弧。 + final int large; + /// 标签极径。 + final double chipR; + /// 标签极角。 + final double chipDeg; + + /// 动作紧贴时只显示连接点标签,隐藏圆弧与箭头。 + final bool junctionOnly; + + /// 依赖键 `from->to`。 + String get key => '${dep.fromId}->${dep.toId}'; + + /// 起点(源环上)。 + Offset get p0 => polar(center, rA, aEnd); + /// 绕行起点(半径 rC 上)。 + Offset get p1 => polar(center, rC, aEnd); + /// 绕行终点(半径 rC 上)。 + Offset get p2 => polar(center, rC, aStart); + /// 箭头端点。 + Offset get p3 => polar(center, rTip, aStart); + /// 退化短箭头的起点。 + Offset get q0 => polar(center, rTip - (rTip > rB ? 28 : -28), aStart); + + /// 生成绘制路径(绘制与命中测试同源)。 + Path buildPath() { + final Path p = Path(); + if (degenerate) { + p.moveTo(q0.dx, q0.dy); + p.lineTo(p3.dx, p3.dy); + return p; + } + final Offset a0 = p0; + final Offset a1 = p1; + final Offset a2 = p2; + final Offset a3 = p3; + p.moveTo(a0.dx, a0.dy); + p.lineTo(a1.dx, a1.dy); + p.arcToPoint(a2, radius: Radius.circular(rC), largeArc: large == 1, clockwise: cw); + p.lineTo(a3.dx, a3.dy); + return p; + } + + /// 箭头方向(分量式)。 + Offset get tipDir => degenerate ? (p3 - q0) : (p3 - p2); +} + +/// 计算圆周视图的全部依赖走线(含自动错开与手动偏移)。 +List buildArcDepRoutes(Project project, CircularLayout layout) { + final Map seen = {}; + final List out = []; + 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, layout.slotOf(a)); + final double rB = layout.radiusFor(b.layer, layout.slotOf(b)); + final double aEnd = math.min(a.endAngle, 360); + final double aStart = b.startAngle; + // 层差大于 1 时从最外圈绕行,避免穿过中间层弧线。 + final bool skip = (a.layer - b.layer).abs() > 1; + final String groupKey = '${skip ? 'K' : 'N'}${a.layer}→${b.layer}'; + final int k = seen.putIfAbsent(groupKey, () => 0); + seen[groupKey] = k + 1; + // 同一环 / 相邻环的依赖如果画在环半径上会压住动作弧:把绕行半径 + // 放到环间空隙(同一环时即为外侧空隙),标签也跟随到空隙里。 + final double ringGap = math.max(layout.pitch - layout.th, 8); + final bool sameRing = (rA - rB).abs() < layout.pitch * 0.35; + final double baseC = skip + ? layout.rMax + 24 + : (sameRing ? rA + ringGap * 0.55 : (rA + rB) / 2); + // 自动错开(步长 9px)+ 手动径向偏移(圆周视图的“法线”即半径方向)。 + double rC = baseC + staggerOffset(k) * 1.5 + d.routeOffset; + rC = rC.clamp(18.0, layout.rMax + 170); + final double rTip = rC < rB ? rB - layout.th / 2 - 4 : rB + layout.th / 2 + 4; + final bool cw = aStart >= aEnd; + final int large = (aStart - aEnd).abs() > 180 ? 1 : 0; + final bool degenerate = (aStart - aEnd).abs() < 0.5; + final bool junctionOnly = (aStart - aEnd).abs() <= 2.0; + final double chipDeg = degenerate ? aStart : (aEnd + aStart) / 2; + final double chipR = rC; + out.add(ArcDepRoute( + d, + layout.center, + rA, + rB, + rC, + rTip, + aEnd, + aStart, + degenerate, + cw, + large, + chipR, + chipDeg, + junctionOnly: junctionOnly)); + } + } + return out; +} + +/// 命中圆周依赖走线:返回最近且距离小于 [maxDist] 的走线(无命中返回 null)。 +ArcDepRoute? hitArcDep(List routes, Offset p, double maxDist) { + ArcDepRoute? best; + double bestD = maxDist; + for (final ArcDepRoute r in routes) { + final double d = distanceToPath(r.buildPath(), p); + if (d < bestD) { + bestD = d; + best = r; + } + } + return best; +} diff --git a/lib/layout/flow_layout.dart b/lib/modules/sequence/layout/flow_layout.dart similarity index 99% rename from lib/layout/flow_layout.dart rename to lib/modules/sequence/layout/flow_layout.dart index 81bb8fd..caa68fa 100644 --- a/lib/layout/flow_layout.dart +++ b/lib/modules/sequence/layout/flow_layout.dart @@ -12,8 +12,8 @@ library; import 'dart:math' as math; import 'dart:ui'; -import '../model/models.dart'; -import '../model/units.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; import 'dep_routes.dart'; import 'layout.dart'; diff --git a/lib/layout/layout.dart b/lib/modules/sequence/layout/layout.dart similarity index 99% rename from lib/layout/layout.dart rename to lib/modules/sequence/layout/layout.dart index 318a73c..20707f6 100644 --- a/lib/layout/layout.dart +++ b/lib/modules/sequence/layout/layout.dart @@ -10,7 +10,7 @@ library; import 'dart:math' as math; import 'dart:ui'; -import '../model/models.dart'; +import 'package:sequence_diagram/model/models.dart'; /// 极坐标转直角坐标:以 [c] 为圆心、[r] 为半径、[deg] 为角度(0° 指向正上方)。 Offset polar(Offset c, double r, double deg) { diff --git a/lib/modules/sequence/layout/snap.dart b/lib/modules/sequence/layout/snap.dart new file mode 100644 index 0000000..b32dd69 --- /dev/null +++ b/lib/modules/sequence/layout/snap.dart @@ -0,0 +1,61 @@ +/// 动作条拖拽吸附:把整体拖动的水平位移吸附到最近的动作条端点、整 5°、 +/// 0/360 或相位分区边界。 +/// +/// 架构位置:布局层纯函数,不依赖 UI 状态;`CanvasView` 在整体拖动时调用, +/// 单元测试可直接验证吸附结果。 +library; + +import 'package:sequence_diagram/model/models.dart'; + +/// 计算整体拖动后的动作起始角。 +/// +/// - [project]:当前工程; +/// - [excludeId]:正在拖动的动作 id(不参与吸附,避免自吸附); +/// - [rawStart]:未吸附的起始角; +/// - [duration]:动作持续角(整体拖动不改变长度); +/// - [toleranceDeg]:吸附容差(度)。 +/// +/// 返回 `(吸附后的起始角, 参考角度)`;参考角度用于绘制竖向虚线, +/// 未吸附时为 null。 +(double, double?) snapActionStart({ + required Project project, + required String excludeId, + required double rawStart, + required double duration, + required double toleranceDeg, +}) { + final double tol = toleranceDeg <= 0 ? 0 : toleranceDeg; + final List candidates = [0, 360]; + for (int d = 0; d <= 360; d += 5) { + candidates.add(d.toDouble()); + } + for (final Action a in project.actions) { + if (a.id == excludeId) continue; + candidates.add(a.startAngle); + candidates.add(a.endAngle); + } + for (final PhaseZone z in project.phaseZones) { + candidates.add(z.startAngle); + candidates.add(z.endAngle); + } + final double end = rawStart + duration; + double best = rawStart; + double bestD = tol; + double? guide; + // 起点与终点同时参与匹配:取绝对调整量最小的一条候选。 + for (final double cand in candidates) { + final double ds = (cand - rawStart).abs(); + if (ds < bestD) { + bestD = ds; + best = cand; + guide = cand; + } + final double de = (cand - end).abs(); + if (de < bestD) { + bestD = de; + best = cand - duration; + guide = cand; + } + } + return (best.clamp(0, 360 - duration), guide); +} diff --git a/lib/render/bar_painter.dart b/lib/modules/sequence/render/bar_painter.dart similarity index 91% rename from lib/render/bar_painter.dart rename to lib/modules/sequence/render/bar_painter.dart index 94b0799..44986ea 100644 --- a/lib/render/bar_painter.dart +++ b/lib/modules/sequence/render/bar_painter.dart @@ -4,7 +4,7 @@ /// 横轴同时表达相位角度与等价的绝对时间,纵轴按工位顺序排列动作行。 /// /// 架构位置: -/// - 全部几何计算委托给 [BarLayout](`lib/layout/layout.dart`), +/// - 全部几何计算委托给 [BarLayout](`modules/sequence/layout/layout.dart`), /// 本绘制器只负责取几何结果并落笔,不自行推导坐标。 /// - 颜色一律取自 [Tokens],因此与圆形视图及 SVG 导出保持同一视觉体系。 /// - 关键路径信息([criticalActions]、[criticalDeps])由上层分析后传入, @@ -19,11 +19,11 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart' hide Action; -import '../layout/dep_routes.dart'; -import '../layout/layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; /// 条形时间轴视图的 [CustomPainter] 实现。 /// @@ -298,7 +298,7 @@ class BarPainter extends CustomPainter { Offset(layout.plotLeft, sy), Offset(layout.plotRight, sy), Paint() - ..color = tokens.line2.withValues(alpha: 0.5) + ..color = tokens.line2.withValues(alpha: 0.75) ..strokeWidth = 1, ); } @@ -306,13 +306,13 @@ class BarPainter extends CustomPainter { // 泳道标题(合并显示;单槽最多两行,多槽位按泳道高度持续换行)。 _laneHeader(canvas, layout, li, acts, slots == 1 ? y : y + laneH / 2 - BarLayout.rowVisual / 2, slots, laneH); - // 泳道底分隔线(单槽时与旧版一致)。 + // 泳道底分隔线(单槽时与旧版一致;加深颜色便于区分泳道)。 canvas.drawLine( Offset(layout.plotLeft, slots == 1 ? y + BarLayout.rowVisual - 4 : y + laneH - 4), Offset(layout.plotRight, slots == 1 ? y + BarLayout.rowVisual - 4 : y + laneH - 4), Paint() - ..color = tokens.line2.withValues(alpha: 0.6) - ..strokeWidth = 1, + ..color = tokens.line2 + ..strokeWidth = 1.3, ); // 该泳道内的所有动作条(按槽位分行放置)。 for (final Action a in acts) { @@ -374,8 +374,9 @@ class BarPainter extends CustomPainter { '${acts.length > 1 ? ' · 共 ${acts.length} 个' : ''}'; // 副标题紧随实际标题高度;单槽保持旧版下边距(y+32)但绝不高于标题底部, // 多槽位下若剩余高度不足则不再绘制,避免压住标题文字。 - final double subY = - single ? math.max(y + 32, y + 2 + tp.height + 2) : y + 2 + tp.height + 2; + final double subY = single + ? math.max(y + 36, y + 2 + tp.height + 6) + : y + 2 + tp.height + 6; if (single || subY + 11 <= y + laneH) { _textMax(canvas, sub, Offset(60, subY), labelMax, color: tokens.dim, size: 10); } @@ -467,7 +468,7 @@ class BarPainter extends CustomPainter { /// 作为竖直通道,泳道位置按区间内条块的最右/最左边界外扩, /// 并叠加 `(k % 3) * 16` 的错位,避免多条线完全重叠。 /// - 关键路径依赖先画一层加粗低透明度的“光晕”,再画主线。 - /// - 末端绘制箭头与类型标签(FS 顺序 / SS +偏移角)。 + /// - 末端绘制箭头与类型标签(FS 顺序 / SS +偏移时间)。 /// /// 参数 [layout] 提供条块矩形;[u] 当前未直接使用,保留以对齐调用接口。 void _deps(Canvas canvas, BarLayout layout, UnitSettings u) { @@ -482,46 +483,46 @@ class BarPainter extends CustomPainter { final bool crit = criticalDeps.contains(r.key); final bool sel = selectedDep == r.key; final Color draw = sel ? tokens.accent : col; - final Path p = Path() - ..moveTo(r.points.first.dx, r.points.first.dy); - for (int i = 1; i < r.points.length; i++) { - p.lineTo(r.points[i].dx, r.points[i].dy); - } - // 关键路径依赖:先铺一层加粗低透明度光晕,再画主线。 - if (crit) { + if (!r.junctionOnly) { + final Path p = Path() + ..moveTo(r.points.first.dx, r.points.first.dy); + for (int i = 1; i < r.points.length; i++) { + p.lineTo(r.points[i].dx, r.points[i].dy); + } + // 关键路径依赖:先铺一层加粗低透明度光晕,再画主线。 + if (crit) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 5 + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.18), + ); + } canvas.drawPath( p, Paint() ..style = PaintingStyle.stroke - ..strokeWidth = 5 + ..strokeWidth = sel ? 2.0 : (crit ? 1.1 : 0.85) ..strokeCap = StrokeCap.round - ..color = col.withValues(alpha: 0.18), + ..color = sel ? draw : draw.withValues(alpha: 0.95), ); + _arrow(canvas, r.arrowTip, r.arrowDir, draw); } - canvas.drawPath( - p, - Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = sel ? 2.0 : (crit ? 1.1 : 0.85) - ..strokeCap = StrokeCap.round - ..color = sel ? draw : draw.withValues(alpha: 0.95), - ); - _arrow(canvas, r.arrowTip, r.arrowDir, draw); final String label = switch (d.type) { DepType.fs => 'FS', - DepType.ss => 'SS+${d.offsetAngle.toStringAsFixed(0)}°', + DepType.ss => d.offsetAngle == 0 + ? 'SS' + : 'SS+${deg2msStr(d.offsetAngle, project.units, project.cycle.durationMs, dec: 2)}', DepType.ff => 'FF', DepType.sf => 'SF', }; - // 行程太短的连线:标签移到箭头外侧(宽度按真实字号精确测量)。 - final double chipW = _tp(label, 8.5, draw, FontWeight.w600).width + 12; - final Offset chipCenter = r.chipRun < chipW + r.chipRunMargin - ? Offset(r.chipAltAnchor.dx + chipW / 2, r.chipAltAnchor.dy) - : r.chipCenter; - // 先记录标签位置,所有依赖线画完后统一避让放置(避免标签互相重叠)。 - chips.add(_ChipSpec(chipCenter, label, draw)); + // 标签固定在两端动作之间的走线中点;不再因为行程短而横向挪到 + // 目标条块上方。统一避让时会同时避开动作条与其它标签。 + chips.add(_ChipSpec(r.chipCenter, label, draw)); } - _placeChips(canvas, chips); + _placeChips(canvas, layout, chips); } /// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。 @@ -544,8 +545,11 @@ class BarPainter extends CustomPainter { /// 对每个标签依次尝试:原位 → 上下错开 → 上下再错开 → 左右错开 → 斜向错开, /// 取第一个不与已放置标签相交的位置,实现“智能避让”。标签内不再绘制五角星 /// (关键路径改用线条光晕表示),字号与色块同时收小,画面更干净。 - void _placeChips(Canvas canvas, List<_ChipSpec> chips) { + void _placeChips(Canvas canvas, BarLayout layout, List<_ChipSpec> chips) { final List placed = []; + final List bars = [ + for (final Action a in project.actions) layout.rectFor(a).inflate(1), + ]; for (final _ChipSpec chip in chips) { final TextPainter tp = _tp(chip.label, 8.5, chip.color, FontWeight.w600); final double w = tp.width + 12; @@ -562,7 +566,10 @@ class BarPainter extends CustomPainter { Rect r = Rect.fromCenter(center: chip.center, width: w, height: h); for (final Offset t in trials) { final Rect cand = r.shift(t); - if (!placed.any((Rect o) => o.inflate(1.5).overlaps(cand))) { + final bool hitChip = + placed.any((Rect o) => o.inflate(1.5).overlaps(cand)); + final bool hitBar = bars.any((Rect o) => o.overlaps(cand)); + if (!hitChip && !hitBar) { r = cand; break; } @@ -665,7 +672,7 @@ class _ChipSpec { /// 期望的标签中心(逻辑坐标)。 final Offset center; - /// 标签文本(如 `FS` / `SS+30°`)。 + /// 标签文本(如 `FS` / `SS+0.20 s`)。 final String label; /// 边框与文字颜色(按依赖类型区分)。 final Color color; diff --git a/lib/render/circular_painter.dart b/lib/modules/sequence/render/circular_painter.dart similarity index 90% rename from lib/render/circular_painter.dart rename to lib/modules/sequence/render/circular_painter.dart index db02e61..56f6003 100644 --- a/lib/render/circular_painter.dart +++ b/lib/modules/sequence/render/circular_painter.dart @@ -15,11 +15,11 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart' hide Action; -import '../layout/dep_routes.dart'; -import '../layout/layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; /// 圆形视图的 [CustomPainter] 实现。 /// @@ -409,12 +409,35 @@ class CircularPainter extends CustomPainter { } } - // 文字沿圆弧排列并按弧长截断,保证始终位于动作色带之内。 + // 文字沿圆弧排列并按弧长截断;短弧优先保留动作名,避免只剩 + // “1. A1 动…” 这类难以辨认的省略文本。 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)); + final double maxW = math.max(arcLen - 12, 20); + double widthOf(String text) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: text, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + fontFamily: 'Microsoft YaHei UI', + ), + ), + textDirection: ui.TextDirection.ltr, + maxLines: 1, + )..layout(); + final double w = tp.width; + tp.dispose(); + return w; + } + String label = '$step. ${a.id} ${a.name}'; + if (widthOf(label) > maxW) label = '$step. ${a.name}'; + if (widthOf(label) > maxW) label = a.name; + if (widthOf(label) > maxW) label = '$step. ${a.id}'; + _arcLabel(canvas, c, r, mid, label, tokens.arcText, 11, maxW); } /// 构造「方头 + 小圆角」的圆环动作带(填充路径)。 @@ -486,28 +509,34 @@ class CircularPainter extends CustomPainter { final bool sel = selectedDep == r.key; final Color draw = sel ? tokens.accent : col; - final Path p = r.buildPath(); - if (crit) { + if (!r.junctionOnly) { + final Path p = r.buildPath(); + if (crit) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 5 + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.2), + ); + } canvas.drawPath( p, Paint() ..style = PaintingStyle.stroke - ..strokeWidth = 5 + ..strokeWidth = sel ? 2.2 : (crit ? 1.2 : (d.type == DepType.fs ? 1.0 : 0.9)) ..strokeCap = StrokeCap.round - ..color = col.withValues(alpha: 0.2), + ..color = draw, ); + _arrow(canvas, r.p3, r.tipDir, draw); } - canvas.drawPath( - p, - Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = sel ? 2.2 : (crit ? 1.2 : (d.type == DepType.fs ? 1.0 : 0.9)) - ..strokeCap = StrokeCap.round - ..color = draw, - ); - _arrow(canvas, r.p3, r.tipDir, draw); - String label = d.type == DepType.fs ? 'FS' : 'SS+${d.offsetAngle.toStringAsFixed(0)}°'; + String label = d.type == DepType.fs + ? 'FS' + : (d.offsetAngle == 0 + ? 'SS' + : 'SS+${deg2msStr(d.offsetAngle, project.units, project.cycle.durationMs, dec: 2)}'); if (d.type == DepType.ff) label = 'FF'; if (d.type == DepType.sf) label = 'SF'; return _ArcChip(r.chipR, r.chipDeg, '${d.fromId}→${d.toId} $label', draw); @@ -522,8 +551,9 @@ class CircularPainter extends CustomPainter { final List placed = []; const double size = 8.5; for (final _ArcChip chip in chips) { - final double w = chip.text.runes.length * size * 0.62 + 8; - final double h = size * 1.7; + final TextPainter tp = _tp(chip.text, size, chip.color, FontWeight.w600); + final double w = tp.width + 10; + const double h = 14; double r = chip.r; Rect rect = Rect.fromCenter(center: polar(c, r, chip.deg), width: w, height: h); for (int i = 1; i <= 10; i++) { @@ -533,9 +563,31 @@ class CircularPainter extends CustomPainter { rect = Rect.fromCenter(center: polar(c, r, chip.deg), width: w, height: h); } placed.add(rect); - final double arcLen = 2 * math.pi * r * 0.9; - _arcLabel(canvas, c, r, chip.deg, chip.text, chip.color, size, - math.max(math.min(arcLen, 200), 40)); + // 标签沿圆弧切线方向旋转(与动作弧同向),放在环间空隙中。 + final Offset pos = polar(c, r, chip.deg); + final double rad = chip.deg * math.pi / 180; + final bool flip = chip.deg > 90 && chip.deg < 270; + canvas.save(); + canvas.translate(pos.dx, pos.dy); + canvas.rotate(flip ? rad + math.pi : rad); + final Rect local = Rect.fromCenter( + center: Offset.zero, + width: w, + height: h, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(local, const Radius.circular(5)), + Paint()..color = tokens.chip, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(local, const Radius.circular(5)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = chip.color, + ); + tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2)); + canvas.restore(); } } @@ -724,7 +776,7 @@ class _ArcChip { final double r; /// 期望的标签角度(度,0° = 12 点钟、顺时针)。 final double deg; - /// 标签文本(如 `A1→A2 SS+30°`)。 + /// 标签文本(如 `A1→A2 SS+0.20 s`)。 final String text; /// 文本颜色(按依赖类型区分)。 final Color color; diff --git a/lib/render/flow_painter.dart b/lib/modules/sequence/render/flow_painter.dart similarity index 95% rename from lib/render/flow_painter.dart rename to lib/modules/sequence/render/flow_painter.dart index 3166b5b..fafeb53 100644 --- a/lib/render/flow_painter.dart +++ b/lib/modules/sequence/render/flow_painter.dart @@ -9,9 +9,10 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; -import '../layout/flow_layout.dart'; -import '../model/models.dart'; -import '../theme/tokens.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; /// 流程图 [CustomPainter] 实现。 class FlowchartPainter extends CustomPainter { @@ -102,7 +103,7 @@ class FlowchartPainter extends CustomPainter { } } - /// 绘制连线:FS 实线、SS 虚线(带偏移角标注)、关键路径加粗光晕。 + /// 绘制连线:FS 实线、SS 虚线(带偏移时间标注)、关键路径加粗光晕。 /// /// 走线由 [FlowLayout.routes] 统一计算(与 SVG / drawio 导出共用同一几何)。 void _edges(Canvas canvas, FlowLayout layout) { @@ -145,7 +146,9 @@ class FlowchartPainter extends CustomPainter { if (e.type != null) { final String text = switch (e.type!) { DepType.fs => 'FS', - DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°', + DepType.ss => e.offset == 0 + ? 'SS' + : 'SS+${deg2msStr(e.offset, project.units, project.cycle.durationMs, dec: 2)}', DepType.ff => 'FF', DepType.sf => 'SF', }; diff --git a/lib/modules/sequence/sequence_module.dart b/lib/modules/sequence/sequence_module.dart new file mode 100644 index 0000000..60c32f1 --- /dev/null +++ b/lib/modules/sequence/sequence_module.dart @@ -0,0 +1,113 @@ +/// 时序图设计模块:PLC 流程节拍 / 相位角、条形 / 圆周 / 流程图三视图。 +/// +/// 模块入口:`lib/modules/sequence/`。新增模块请参考本文件与 +/// `lib/modules/README.md`,然后在 `lib/modules/registry.dart` 注册。 +library; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/modules/sequence/ui/sequence_ui.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +/// 时序图模块单例。 +const SequenceModule sequenceModule = SequenceModule(); + +/// 时序图设计模块。 +class SequenceModule extends EdcModule { + /// 构造模块。 + const SequenceModule(); + + /// 稳定 id。 + static const String moduleId = 'sequence'; + + @override + String get id => moduleId; + @override + String get name => '时序图'; + @override + String get shortName => '时序图'; + @override + IconData get icon => Icons.waterfall_chart; + @override + int get accent => 0xFF4CC9F0; + @override + String get suffix => '.seq.json'; + @override + bool get available => true; + @override + String get defaultName => '未命名-时序图'; + @override + String get blurb => 'PLC 节拍 · 三视图'; + + @override + void newDocument(AppController controller) { + controller.newProject(); + } + + @override + void loadDocument(AppController controller, String source, {String? path}) { + controller.loadProject(Project.decode(source), path: path); + } + + @override + String encodeDocument(AppController controller) => + controller.project.encode(includeArch: false); + + @override + String documentName(AppController controller) => controller.project.name; + + @override + String? filePath(AppController controller) => controller.filePath; + + @override + bool isDirty(AppController controller) => controller.dirty; + + @override + Future saveTo(AppController controller, String path) => + controller.saveAs(path); + + @override + Future markSaved(AppController controller, String displayPath) => + controller.markSaved(displayPath); + + @override + bool isReadOnly(AppController controller) => + controller.project.viewState.mode == ViewMode.flow; + + @override + Map buildShortcuts(ModuleUiContext ui) { + return { + const SingleActivator(LogicalKeyboardKey.delete): () { + if (!isReadOnly(ui.controller) && ui.controller.selectedId != null) { + ui.controller.deleteAction(ui.controller.selectedId!); + } + }, + }; + } + + @override + Widget buildWorkspace(ModuleUiContext ui) => SequenceUi(ui).buildWorkspace(); + + @override + Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) => + SequenceUi(ui).buildLeftPanel(ui.tokens, floating: floating); + + @override + Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) => + SequenceUi(ui).buildRightPanel(ui.tokens, floating: floating); + + @override + List buildToolbarCenter(ModuleUiContext ui, {required bool compact}) => + SequenceUi(ui).buildToolbarCenter(ui.tokens, compact: compact); + + @override + List buildToolbarRight(ModuleUiContext ui) => + SequenceUi(ui).buildToolbarRight(ui.tokens, compact: ui.compact); + + @override + Widget buildStatusBar(ModuleUiContext ui) => + SequenceUi(ui).buildStatusBar(ui.tokens); +} diff --git a/lib/ui/ai_dialog.dart b/lib/modules/sequence/ui/ai_dialog.dart similarity index 98% rename from lib/ui/ai_dialog.dart rename to lib/modules/sequence/ui/ai_dialog.dart index a3abacd..24596ce 100644 --- a/lib/ui/ai_dialog.dart +++ b/lib/modules/sequence/ui/ai_dialog.dart @@ -15,10 +15,10 @@ import 'dart:async'; import 'package:flutter/material.dart'; -import '../ai/ai_client.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import 'dialogs.dart'; +import 'package:sequence_diagram/modules/sequence/ai/ai_client.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; class AiGenerateDialog extends StatefulWidget { const AiGenerateDialog({super.key, required this.controller}); diff --git a/lib/ui/canvas_overlays.dart b/lib/modules/sequence/ui/canvas_overlays.dart similarity index 99% rename from lib/ui/canvas_overlays.dart rename to lib/modules/sequence/ui/canvas_overlays.dart index 240c6ba..7e22c9a 100644 --- a/lib/ui/canvas_overlays.dart +++ b/lib/modules/sequence/ui/canvas_overlays.dart @@ -9,12 +9,12 @@ 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'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; /// 条形缩略预览的固定绘制区高度:卡片尺寸不随动作数量变化, /// 动作越多只会在内部压缩行距、把色条画得更细。 diff --git a/lib/ui/canvas_view.dart b/lib/modules/sequence/ui/canvas_view.dart similarity index 96% rename from lib/ui/canvas_view.dart rename to lib/modules/sequence/ui/canvas_view.dart index 7991a2e..182bc94 100644 --- a/lib/ui/canvas_view.dart +++ b/lib/modules/sequence/ui/canvas_view.dart @@ -15,16 +15,17 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' hide Action; import 'package:flutter/services.dart'; -import '../layout/dep_routes.dart'; -import '../layout/flow_layout.dart'; -import '../layout/layout.dart'; -import '../model/models.dart'; -import '../render/bar_painter.dart'; -import '../render/circular_painter.dart'; -import '../render/flow_painter.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import 'dialogs.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/snap.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/modules/sequence/render/bar_painter.dart'; +import 'package:sequence_diagram/modules/sequence/render/circular_painter.dart'; +import 'package:sequence_diagram/modules/sequence/render/flow_painter.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; /// 当前拖拽行为类型:无操作 / 平移相位 / 拖右端改时长 / 拖左端改起始 / /// 拖拽依赖走线(沿法线平移整条线)。 @@ -697,7 +698,19 @@ class _CanvasViewState extends State { ); } else { // 整体移动:水平改起始相位 + 垂直跟随泳道 / 槽位,两者可同时进行。 - c.setActionStart(_dragAction!.id, _startAngle + dx / layout.span * 360); + // 起点/终点同时参与磁吸:靠近上下游动作条端点、整 5° 或分区边界时 + // 自动贴合,并显示竖向参考虚线(与改时长的手感一致)。 + final double rawStart = _startAngle + dx / layout.span * 360; + final double tolDeg = math.max(2.5, 10 / layout.span * 360); + final (double ns, double? guide) = snapActionStart( + project: c.project, + excludeId: _dragAction!.id, + rawStart: rawStart, + duration: _startDuration, + toleranceDeg: tolDeg, + ); + _zoneGuideAngle = guide; + c.setActionStart(_dragAction!.id, ns, snap: false); final Action? cur = c.project.actionById(_dragAction!.id); final int curLane = cur?.layer ?? _dragAction!.layer; final int curSlot = cur == null ? 0 : layout.slotOf(cur); diff --git a/lib/modules/sequence/ui/sequence_ui.dart b/lib/modules/sequence/ui/sequence_ui.dart new file mode 100644 index 0000000..a10f3a7 --- /dev/null +++ b/lib/modules/sequence/ui/sequence_ui.dart @@ -0,0 +1,1588 @@ +/// 时序图模块 UI:工具栏中段 / 右侧工具、左右侧栏、状态栏。 +/// +/// 所有方法由 `SequenceModule` 在 `lib/modules/registry.dart` 注册后由外壳调用; +/// 本文件只依赖模块自身代码与共享内核(主题 / 持久化 / 通用对话框)。 +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:flutter/material.dart' hide Action; +import 'package:flutter/services.dart'; + +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/modules/module.dart'; +import 'package:sequence_diagram/modules/sequence/export/drawio_writer.dart'; +import 'package:sequence_diagram/modules/sequence/export/export_renderer.dart'; +import 'package:sequence_diagram/modules/sequence/export/svg_writer.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/ui/ai_dialog.dart'; +import 'package:sequence_diagram/modules/sequence/ui/canvas_overlays.dart'; +import 'package:sequence_diagram/modules/sequence/ui/canvas_view.dart'; +import 'package:sequence_diagram/persistence/android_docs.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/dialogs.dart'; + +/// 时序图模块 UI 构建器。 +class SequenceUi { + /// 构造 UI 构建器。 + const SequenceUi(this.ui); + + /// 外壳上下文。 + final ModuleUiContext ui; + + AppController get c => ui.controller; + BuildContext get context => ui.context; + Tokens get t => ui.tokens; + double get _toolScale => ui.toolScale; + double _toolFont(double size) => ui.toolFont(size); + double get _leftPanelWidth => ui.leftPanelWidth; + double get _rightPanelWidth => ui.rightPanelWidth; + Widget _panelControls(Tokens t, bool left) => ui.panelControls(left); + + /// 工具栏中段:AI 生成 + 视图切换。 + List buildToolbarCenter(Tokens t, {required bool compact}) => [ + _aiBtn(t), + SizedBox(width: (compact ? 8 : 12) * _toolScale), + _segmented(t, compact: compact), + ]; + + /// 工具栏右侧:导出 / 缩放 / 适应视图 / 时间单位。 + List buildToolbarRight(Tokens t, {required bool compact}) => [ + _exportMenu(t), + SizedBox(width: (compact ? 4 : 6) * _toolScale), + _zoomBox(t), + SizedBox(width: (compact ? 4 : 6) * _toolScale), + _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), + SizedBox(width: (compact ? 4 : 8) * _toolScale), + _unitDropdown(t), + ]; + + /// 左侧栏。 + Widget buildLeftPanel(Tokens t, {bool floating = false}) => + _leftPanel(t, floating: floating); + + /// 右侧栏。 + Widget buildRightPanel(Tokens t, {bool floating = false}) => + _rightPanel(t, floating: floating); + + /// 底部状态栏。 + Widget buildStatusBar(Tokens t) => _statusBar(t); + + /// 工作区:可交互画布 + 画布浮层。 + Widget buildWorkspace() => Stack( + children: [ + Positioned.fill( + child: Container( + color: t.canvas2, + child: CanvasView(controller: c), + ), + ), + Positioned.fill( + child: CanvasOverlays( + controller: c, + leftInset: ui.leftRail ? 22 : 0, + rightInset: ui.rightRail ? 22 : 0, + ), + ), + ], + ); + + Widget _segmented(Tokens t, {bool compact = false}) { + final ViewMode mode = c.project.viewState.mode; + Widget seg(String label, bool active, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + width: (compact ? 84 : 118) * _toolScale, + height: 34 * _toolScale, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent, + borderRadius: BorderRadius.circular(10), + border: active ? Border.all(color: t.accent, width: 1.4) : null, + ), + child: Text(label, + style: TextStyle( + color: active ? t.accent : t.sub, + fontWeight: active ? FontWeight.w600 : FontWeight.normal, + fontSize: _toolFont(12), + )), + ), + ); + } + + return Container( + padding: EdgeInsets.all(3 * _toolScale), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line2), + ), + child: Row( + children: [ + seg('条形节拍', mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar)), + seg('圆周节拍', mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular)), + seg('流程图', mode == ViewMode.flow, () => c.setViewMode(ViewMode.flow)), + ], + ), + ); + } + + Widget _zoomBox(Tokens t) { + final double s = _toolScale; + final double zoom = c.project.viewState.zoom; + final String pct = '${(zoom * 100).round()}%'; + return Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 4 * s), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: t.line2), + ), + child: Row( + children: [ + _miniIcon(t, Icons.remove, () => c.zoomBy(0.9)), + SizedBox( + width: 52 * s, + child: Text(pct, + textAlign: TextAlign.center, + style: TextStyle(color: t.text, fontSize: _toolFont(11))), + ), + _miniIcon(t, Icons.add, () => c.zoomBy(1.1)), + ], + ), + ); + } + + Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: EdgeInsets.all(6 * _toolScale), + child: Icon(icon, size: 15 * _toolScale, color: t.sub), + ), + ); + } + + Widget _unitDropdown(Tokens t) { + final double s = _toolScale; + return Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 10 * s), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: t.accent, width: 1.2), + ), + child: DropdownButton( + value: c.project.units.timeUnit, + underline: const SizedBox.shrink(), + dropdownColor: t.dialog, + borderRadius: BorderRadius.circular(9), + style: TextStyle(color: t.accent, fontSize: _toolFont(11), fontWeight: FontWeight.w600), + icon: Icon(Icons.keyboard_arrow_down, color: t.accent, size: 18 * s), + items: TimeUnit.values + .map((TimeUnit u) => DropdownMenuItem(value: u, child: Text(timeUnitLabel(u)))) + .toList(), + onChanged: (TimeUnit? u) { + if (u != null) c.setUnits(c.project.units.copyWith(timeUnit: u)); + }, + ), + ); + } + + Widget _exportMenu(Tokens t) { + final double s = _toolScale; + final bool licensed = c.licensed; + final bool flow = c.project.viewState.mode == ViewMode.flow; + final Color fg = licensed ? Colors.white : t.dim; + return Padding( + padding: EdgeInsets.symmetric(horizontal: 3 * s), + child: PopupMenuButton( + tooltip: '导出(SVG / PNG${flow ? ' / drawio' : ''})', + color: t.panel2, + position: PopupMenuPosition.under, + onSelected: (String v) { + if (v == 'svg') _exportSvg(); + if (v == 'png') _exportPng(); + if (v == 'drawio') _exportDrawio(); + }, + itemBuilder: (BuildContext ctx) => >[ + _exportItem(t, 'svg', Icons.code, '导出 SVG', + '矢量图:无损缩放 / 打印 / 二次编辑', licensed), + _exportItem(t, 'png', Icons.image_outlined, '导出 PNG', + '位图(3840×2160):分享 / 汇报', licensed), + if (flow) + _exportItem(t, 'drawio', Icons.account_tree_outlined, '导出 drawio', + 'diagrams.net 可编辑工程', licensed), + ], + child: Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 12 * s), + decoration: BoxDecoration( + color: licensed ? t.accent2 : t.panel2, + borderRadius: BorderRadius.circular(9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.ios_share, size: 15 * s, color: fg), + SizedBox(width: 6 * s), + Text('导出', + style: TextStyle(fontSize: _toolFont(11), fontWeight: FontWeight.w600, color: fg)), + Icon(Icons.arrow_drop_down, size: 18 * s, color: fg), + ], + ), + ), + ), + ); + } + + PopupMenuItem _exportItem( + Tokens t, String value, IconData icon, String label, String hint, bool enabled) { + final Color main = enabled ? t.text : t.dim; + return PopupMenuItem( + value: value, + enabled: enabled, + height: 46, + child: Row( + children: [ + Icon(icon, size: 17, color: enabled ? t.accent : t.dim), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)), + Text(hint, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)), + ], + ), + ), + ], + ), + ); + } + + Widget _aiBtn(Tokens t) { + final double s = _toolScale; + final bool enabled = c.project.viewState.mode != ViewMode.flow; + final Widget btn = FilledButton.icon( + onPressed: enabled + ? () => showDialog( + context: context, + builder: (_) => AiGenerateDialog(controller: c), + ) + : null, + icon: Icon(Icons.auto_awesome, size: 16 * s), + label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), + style: FilledButton.styleFrom( + backgroundColor: enabled ? t.accent2 : t.panel2, + foregroundColor: enabled ? Colors.white : t.dim, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), + padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), + minimumSize: Size(0, 34 * s), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ); + return Padding( + padding: EdgeInsets.symmetric(horizontal: 3 * s), + child: enabled ? btn : Tooltip(message: 'AI 生成仅针对时序图(条形 / 圆周视图)', child: btn), + ); + } + + Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) { + final double s = _toolScale; + return IconButton( + onPressed: onTap, + icon: Icon(icon, size: 18 * s, color: onTap == null ? t.dim : (color ?? t.text)), + tooltip: tooltip, + splashRadius: 16 * s, + padding: EdgeInsets.zero, + constraints: BoxConstraints(minWidth: 34 * s, minHeight: 34 * s), + // 新版 Flutter 的 IconButton 已移除 tapTargetSize 形参,改由 style 提供。 + style: IconButton.styleFrom(tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null), + ); + } + + Future _exportSvg() async { + if (!c.licensed) { + if (context.mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); + return; + } + // 安卓版:写入公共 Documents/EDC。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.svg', + suffix: '.svg', + ), + ); + if (name == null) return; + try { + final String svg = SvgWriter( + project: c.project, + tokens: Tokens.of(c.brightness), + mode: c.project.viewState.mode, + ).build(); + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.svg', + suffix: '.svg', + ); + if (path == null) return; + try { + final String svg = SvgWriter( + project: c.project, + tokens: Tokens.of(c.brightness), + mode: c.project.viewState.mode, + ).build(); + await File(path).writeAsString(svg, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Future _exportPng() async { + if (!c.licensed) { + if (context.mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); + return; + } + final Uint8List bytes; + try { + bytes = await renderExportPng( + project: c.project, + tokens: Tokens.of(c.brightness), + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + ); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + return; + } + if (!context.mounted) return; + // 安卓版:写入配置的公共目录。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.png', + suffix: '.png', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.png', + suffix: '.png', + ); + if (path == null) return; + try { + await File(path).writeAsBytes(bytes, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Future _exportDrawio() async { + if (c.project.viewState.mode != ViewMode.flow) { + if (context.mounted) { + await showMessage(context, '导出 drawio', '仅流程图视图支持导出 drawio;条形 / 圆周视图请导出 SVG 或 PNG。'); + } + return; + } + if (!c.licensed) { + if (context.mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 drawio。'); + return; + } + final String xml = DrawioWriter(project: c.project, tokens: Tokens.of(c.brightness)).build(); + // 安卓版:写入公共 Documents 目录。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.drawio', + suffix: '.drawio', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(xml)), mime: 'application/xml'); + if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.drawio', + suffix: '.drawio', + ); + if (path == null) return; + try { + await File(path).writeAsString(xml, flush: true); + if (context.mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (context.mounted) await showMessage(context, '导出失败', '$e'); + } + } + + Widget _leftPanel(Tokens t, {bool floating = false}) { + final bool bar = c.project.viewState.mode == ViewMode.bar; + final bool flow = c.project.viewState.mode == ViewMode.flow; + return Container( + width: _leftPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] + : null, + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _sectionLabel(t, '文档设置'), + const Spacer(), + _panelControls(t, true), + ], + ), + const SizedBox(height: 8), + _editEntry( + t, + icon: Icons.edit_note, + label: '文档设置', + enabled: !flow, + onTap: () => showDialog( + context: context, + builder: (_) => SettingsDialog(controller: c), + ), + ), + // 较浅的分隔横线,区分上方「文档设置」与下方「动作和执行编辑」。 + const SizedBox(height: 14), + Divider(height: 1, thickness: 1, color: t.line), + const SizedBox(height: 14), + Row( + children: [ + // 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。 + Expanded(child: _sectionLabel(t, '动作和执行编辑')), + _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, + flow ? null : () => c.addAction(startAngle: 0)), + const SizedBox(width: 6), + // 至少保留一个动作 / 泳道:只剩一个时禁用删除;流程图只读时禁用。 + _headerAction( + t, + Icons.delete_outline, + '删除', + t.danger, + Colors.white, + (flow || c.selectedId == null || c.project.actions.length <= 1) + ? null + : () => c.deleteAction(c.selectedId!), + ), + ], + ), + const SizedBox(height: 8), + // 按泳道 / 轨道分组:同一泳道内的多个动作合并显示(最多两行,/ 分隔)。 + ..._laneRows(t, bar), + const SizedBox(height: 8), + // 工位 / 相位分区管理入口,同属「动作和执行编辑」区域。 + // 工位:一个流程可包含多个工位,可增删改与排序。 + _editEntry( + t, + icon: Icons.precision_manufacturing_outlined, + label: '编辑工位', + badge: c.project.stations.length, + enabled: !flow, + onTap: () => showDialog( + context: context, + builder: (_) => StationDialog(controller: c), + ), + ), + const SizedBox(height: 8), + // 相位分区:可任意增删、改名、改起止角;流程图只读时置灰。 + _editEntry( + t, + icon: Icons.tune, + label: '编辑相位分区', + badge: c.project.phaseZones.length, + enabled: !flow, + onTap: () => showDialog( + context: context, + builder: (_) => PhaseZoneDialog(controller: c), + ), + ), + const SizedBox(height: 12), + _sectionLabel(t, '视图模式'), + const SizedBox(height: 8), + // 该栏永久只保留条形 / 圆周两个时序视图的切换; + // 流程图由时序图生成、属独立载体,入口在顶部工具栏(不在本栏混排)。 + Row( + children: [ + Expanded(child: _modeButton(t, '条形节拍(甘特)', c.project.viewState.mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar))), + const SizedBox(width: 8), + Expanded(child: _modeButton(t, '圆周节拍(同心)', c.project.viewState.mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular))), + ], + ), + const SizedBox(height: 12), + _sectionLabel(t, '显示选项'), + const SizedBox(height: 6), + ..._displayOptions(t, bar), + const SizedBox(height: 8), + _sectionLabel(t, '工位负载 / 相位占用'), + const SizedBox(height: 10), + ..._stationLoads(t), + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), + const SizedBox(height: 6), + // 提示随视图模式切换:流程图是只读预览,给出交互方式说明。 + if (flow) ...[ + Text('流程图只读:点击节点可选中对应动作', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('滚轮缩放 · 拖拽平移 · Ctrl+滚轮连续缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('需要修改请切回条形 / 圆周视图', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ] else ...[ + Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('双击空白新建动作 · F1 打开帮助', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ], + ], + ), + ), + ], + ), + ), + ); + } + + Widget _sectionLabel(Tokens t, String s) => Text( + s, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text2, fontSize: 11.5, letterSpacing: 1.2, fontWeight: FontWeight.w600), + ); + + Widget _editEntry( + Tokens t, { + required IconData icon, + required String label, + required VoidCallback onTap, + int? badge, + bool enabled = true, + }) { + final Widget card = InkWell( + onTap: enabled ? onTap : null, + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Icon(icon, size: 16, color: enabled ? t.accent : t.dim), + const SizedBox(width: 8), + Expanded(child: Text(label, style: TextStyle(color: enabled ? t.text2 : t.dim, fontSize: 12))), + if (badge != null) ...[ + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: enabled ? t.accent.withValues(alpha: 0.14) : t.line.withValues(alpha: 0.35), + borderRadius: BorderRadius.circular(6), + ), + child: Text('$badge', + style: TextStyle( + color: enabled ? t.accent : t.dim, fontSize: 10.5, fontWeight: FontWeight.w700)), + ), + const SizedBox(width: 4), + ], + Icon(Icons.chevron_right, size: 16, color: t.dim), + ], + ), + ), + ); + if (enabled) return card; + return Tooltip(message: '流程图只读:修改请切回条形 / 圆周视图', child: card); + } + + Widget _laneSlotChip(Tokens t, int lane) { + final int n = c.project.slotsOf(lane); + return Builder( + builder: (BuildContext ctx) => Tooltip( + message: '泳道 L${lane + 1} 槽位数:$n(点击调整,最多 5)', + child: InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () async { + final RenderBox box = ctx.findRenderObject()! as RenderBox; + await showLaneSlotMenu(context, c, box.localToGlobal(Offset.zero), lane); + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: n > 1 ? t.accent.withValues(alpha: 0.14) : t.panel2, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: n > 1 ? t.accent.withValues(alpha: 0.4) : t.line2), + ), + child: Text('$n 槽', + style: TextStyle(color: n > 1 ? t.accent : t.dim, fontSize: 10)), + ), + ), + ), + ); + } + + Widget _headerAction(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback? onTap) { + final bool enabled = onTap != null; + return Opacity( + opacity: enabled ? 1 : 0.4, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(8)), + child: Row( + children: [ + Icon(icon, size: 14, color: fg), + const SizedBox(width: 4), + Text(label, style: TextStyle(color: fg, fontSize: 11, fontWeight: FontWeight.w700)), + ], + ), + ), + ), + ); + } + + List _laneRows(Tokens t, bool bar) { + final List lanes = c.project.renderLanes; + final List out = []; + for (int li = 0; li < lanes.length; li++) { + final int lane = lanes[li]; + final List acts = c.project.actions.where((Action a) => a.layer == lane).toList() + ..sort((Action a, Action b) => a.startAngle.compareTo(b.startAngle)); + // 空泳道(开启「保留空泳道」后动作被全部移走):显示占位行。 + if (acts.isEmpty) { + out.add(_emptyLaneRow(t, lane, li)); + continue; + } + // 单动作泳道沿用普通动作行;多动作泳道合并显示。 + out.add(acts.length == 1 + ? _actionRow(t, acts.first, li, bar) + : _laneRow(t, lane, li, acts, bar)); + } + return out; + } + + Widget _emptyLaneRow(Tokens t, int lane, int li) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Container( + width: 22, + height: 22, + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: t.line2), + ), + alignment: Alignment.center, + child: Text('${li + 1}', + style: TextStyle(color: t.dim, fontSize: 11, fontWeight: FontWeight.w700)), + ), + const SizedBox(width: 9), + Expanded( + child: Text('空泳道(已保留,可拖入动作)', + style: TextStyle(color: t.dim, fontSize: 11)), + ), + _laneSlotChip(t, lane), + ], + ), + ), + ); + } + + Widget _laneRow(Tokens t, int lane, int li, List acts, bool bar) { + if (acts.isEmpty) return const SizedBox.shrink(); + final bool flow = c.project.viewState.mode == ViewMode.flow; + final Action primary = + acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first); + final bool sel = c.isSelected(primary.id); + final Station? st = c.project.stationById(primary.stationId); + final String joined = acts.map((Action a) => '${a.id} ${a.name}').join(' / '); + double a0 = acts.first.startAngle; + double a1 = acts.first.endAngle; + for (final Action a in acts) { + a0 = math.min(a0, a.startAngle); + a1 = math.max(a1, a.endAngle); + } + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: InkWell( + onTap: () => c.select( + primary.id, + toggle: HardwareKeyboard.instance.isControlPressed || + HardwareKeyboard.instance.isShiftPressed, + ), + // 双击泳道行直接编辑该泳道的主动作(流程图只读时禁用)。 + onDoubleTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: sel ? t.sel : t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), + ), + child: Row( + children: [ + Container( + width: 22, + height: 22, + decoration: BoxDecoration( + color: Color(primary.color).withValues(alpha: 0.9), + borderRadius: BorderRadius.circular(6), + ), + alignment: Alignment.center, + child: Text('${li + 1}', style: TextStyle(color: t.chip, fontSize: 11, fontWeight: FontWeight.w700)), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + joined, + // 多槽位泳道允许更多行(最多与槽位数一致),持续自动换行。 + maxLines: math.max(2, c.project.slotsOf(lane)), + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: sel ? t.text : t.text2, + fontSize: 12.5, + height: 1.25, + fontWeight: sel ? FontWeight.w600 : FontWeight.normal, + ), + ), + Text( + '${st?.name ?? primary.stationId} · ${primary.driver}' + '${acts.length > 1 ? ' · 共 ${acts.length} 个' : ''}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10), + ), + ], + ), + ), + const SizedBox(width: 6), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 11), + ), + Text('${acts.length} 个动作', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ), + const SizedBox(width: 6), + _laneSlotChip(t, lane), + const SizedBox(width: 4), + InkWell( + onTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), + borderRadius: BorderRadius.circular(7), + child: Container( + width: 28, + height: 24, + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line2), + ), + child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _actionRow(Tokens t, Action a, int i, bool bar) { + final bool flow = c.project.viewState.mode == ViewMode.flow; + final bool sel = c.isSelected(a.id); + final Station? st = c.project.stationById(a.stationId); + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: InkWell( + // Ctrl / Shift 点击可多选,用于批量对齐等操作。 + onTap: () => c.select( + a.id, + toggle: HardwareKeyboard.instance.isControlPressed || + HardwareKeyboard.instance.isShiftPressed, + ), + // 双击动作行直接进入编辑(流程图只读时禁用)。 + onDoubleTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: sel ? t.sel : t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), + ), + child: Row( + children: [ + Container( + width: 22, + height: 22, + decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6)), + alignment: Alignment.center, + child: Text('${i + 1}', style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(a.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: sel ? t.text : t.text2, fontSize: 12, fontWeight: sel ? FontWeight.w600 : FontWeight.normal)), + Text( + '${a.id} · ${st?.name ?? a.stationId} · ${a.driver}' + '${c.project.slotsOf(a.layer) > 1 ? ' · 槽 ${effectiveSlot(c.project, a) + 1}' : ''}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ), + const SizedBox(width: 6), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + bar + ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' + : 'L${a.layer + 1}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 10), + ), + Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ), + const SizedBox(width: 6), + _laneSlotChip(t, a.layer), + const SizedBox(width: 4), + InkWell( + onTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), + borderRadius: BorderRadius.circular(7), + child: Container( + width: 28, + height: 24, + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line2), + ), + child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), + ), + ), + // 选中该动作时才出现删除入口;至少保留一个动作 / 泳道;流程图只读时隐藏。 + if (sel && !flow && c.project.actions.length > 1) ...[ + const SizedBox(width: 4), + InkWell( + onTap: () => c.deleteAction(a.id), + borderRadius: BorderRadius.circular(7), + child: Container( + width: 28, + height: 24, + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.danger.withValues(alpha: 0.6)), + ), + child: Icon(Icons.delete_outline, size: 13, color: t.danger), + ), + ), + ], + ], + ), + ), + ), + ); + } + + Widget _modeButton(Tokens t, String label, bool active, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + height: 44, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.16) : t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: active ? t.accent : t.line, width: 1.2), + ), + child: Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: active ? t.accent : t.sub, fontSize: 11)), + ), + ); + } + + List _displayOptions(Tokens t, bool bar) { + final ViewState v = c.project.viewState; + final List> opts = bar + ? >[ + ['时间轴 / 相位双刻度', v.showRuler, (bool x) => c.setViewFlag(showRuler: x)], + ['依赖箭头 FS / SS', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], + ['跨循环片段标记', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], + ['相位分区标注', v.showPhaseBands, (bool x) => c.setViewFlag(showPhaseBands: x)], + ] + : >[ + ['同心圆环背景', v.showRingBg, (bool x) => c.setViewFlag(showRingBg: x)], + ['顺序箭头(FS / SS)', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], + ['层半径标注', v.showLayerLabels, (bool x) => c.setViewFlag(showLayerLabels: x)], + ['跨循环高亮', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], + ]; + return opts.map((List o) { + final bool on = o[1] as bool; + return InkWell( + onTap: () => (o[2] as void Function(bool))(!on), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: on ? t.accent.withValues(alpha: 0.22) : Colors.transparent, + borderRadius: BorderRadius.circular(4), + border: Border.all(color: on ? t.accent : t.line2), + ), + child: on ? Icon(Icons.check, size: 12, color: t.accent) : null, + ), + const SizedBox(width: 10), + Text(o[0] as String, style: TextStyle(color: t.sub, fontSize: 11)), + ], + ), + ), + ); + }).toList(); + } + + List _stationLoads(Tokens t) { + final Map load = {}; + for (final Action a in c.project.actions) { + load[a.stationId] = (load[a.stationId] ?? 0) + a.durationAngle; + } + final List out = []; + for (final Station s in c.project.stations) { + final double deg = load[s.id] ?? 0; + out.add(Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Text('${s.id} ${s.name}', + maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.sub, fontSize: 11)), + ), + Text('${deg.toStringAsFixed(0)}° · ${(deg / 3.6).toStringAsFixed(1)}%', + style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), + ], + ), + const SizedBox(height: 5), + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: (deg / 360).clamp(0, 1), + minHeight: 8, + backgroundColor: t.track, + valueColor: AlwaysStoppedAnimation(t.accent), + ), + ), + ], + ), + )); + } + return out; + } + + int _depCount() { + int n = 0; + for (final Action a in c.project.actions) { + n += a.deps.length; + } + return n; + } + + Widget _rightPanel(Tokens t, {bool floating = false}) { + final Action? a = c.selected; + final bool bar = c.project.viewState.mode == ViewMode.bar; + final bool flow = c.project.viewState.mode == ViewMode.flow; + return Container( + width: _rightPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] + : null, + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), + child: Row( + children: [ + _sectionLabel(t, '属性 · 选中动作'), + const Spacer(), + _panelControls(t, false), + ], + ), + ), + Expanded( + child: a == null + ? Center( + child: Text('未选中动作\n点击画布或左侧列表选择', + textAlign: TextAlign.center, style: TextStyle(color: t.dim, fontSize: 11, height: 1.6)), + ) + : SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _selectedHeader(t, a, bar), + const SizedBox(height: 14), + // 流程图只读提示:节点与连线自动生成,编辑请回时序视图。 + if (flow) ...[ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.lock_outline, size: 15, color: t.warn), + const SizedBox(width: 8), + Expanded( + child: Text('流程图只读:节点与连线由时序图自动生成,修改请切回条形 / 圆周视图。', + style: TextStyle(color: t.sub, fontSize: 10.5, height: 1.55)), + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ..._propertyFields(t, a, bar), + const SizedBox(height: 10), + if (!bar) ...[ + _sectionLabel(t, '角度编辑'), + const SizedBox(height: 8), + // 流程图只读:滑块仅展示数值,不可拖动。 + Opacity( + opacity: flow ? 0.45 : 1, + child: IgnorePointer( + ignoring: flow, + child: Column( + children: [ + _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), + (double v) => c.setActionStart(a.id, v * 360)), + _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), + (double v) => c.setActionDuration(a.id, v * 180)), + ], + ), + ), + ), + const SizedBox(height: 8), + ], + const SizedBox(height: 12), + // 输入依赖:允许多条(多前置)。 + _sectionLabel(t, '前置依赖 · 输入(${a.deps.length})'), + const SizedBox(height: 8), + if (a.deps.isEmpty) + Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11)) + else + for (final Dependency d in a.deps) _depRow(t, a, d, enabled: !flow), + const SizedBox(height: 6), + OutlinedButton.icon( + onPressed: flow + ? null + : () => showDialog( + context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), + icon: const Icon(Icons.add_link, size: 15), + label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)), + style: OutlinedButton.styleFrom( + foregroundColor: t.accent, + side: BorderSide(color: t.line2), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), + padding: const EdgeInsets.symmetric(vertical: 10), + minimumSize: const Size(double.infinity, 0), + ), + ), + const SizedBox(height: 12), + // 输出依赖:本动作作为前置指向的后续动作(允许多结果)。 + _sectionLabel(t, '输出依赖 · 结果(${_outgoingDeps(a).length})'), + const SizedBox(height: 8), + if (_outgoingDeps(a).isEmpty) + Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11)) + else + for (final (Action target, Dependency d) in _outgoingDeps(a)) + _outDepRow(t, a, target, d, enabled: !flow), + const SizedBox(height: 12), + _helpCard(t), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _selectedHeader(Tokens t, Action a, bool bar) { + final Station? st = c.project.stationById(a.stationId); + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Container( + width: 34, + height: 34, + decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(8)), + alignment: Alignment.center, + child: Text(a.id, style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(a.name, maxLines: 1, overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w600)), + Text('${st?.id ?? a.stationId} · ${a.driver} · 层 L${a.layer + 1}', + maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), + decoration: BoxDecoration( + color: (a.wrap ? t.warn : t.accent).withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: a.wrap ? t.warn : t.accent), + ), + child: Text(a.wrap ? '跨圈' : '选中', + style: TextStyle(color: a.wrap ? t.warn : t.accent, fontSize: 11)), + ), + ], + ), + ); + } + + List _propertyFields(Tokens t, Action a, bool bar) { + final UnitSettings u = c.project.units; + final double cycle = c.project.cycle.durationMs; + final List> fields; + if (bar) { + fields = >[ + ['开始时刻', tfmt(a.startAngle / 360 * cycle, u), pfmt(a.startAngle, u)], + ['结束时刻', tfmt(a.endAngle / 360 * cycle, u), a.wrap ? '${a.endAngle.toStringAsFixed(1)}° → ${(a.endAngle - 360).toStringAsFixed(1)}°' : pfmt(a.endAngle, u)], + ['持续时间', tfmt(a.durationAngle / 360 * cycle, u), pfmt(a.durationAngle, u)], + ['循环归属', a.wrap ? '当前圈 + 下一圈' : '当前圈', a.wrap ? '跨圈片段' : '单圈内'], + ['顺序约束', _depSummary(a), '前序动作关系'], + ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], + ]; + } else { + fields = >[ + ['起始相位', pfmt(a.startAngle, u), '${tfmt(a.startAngle / 360 * cycle, u)} · 12 点钟起顺时针'], + ['结束相位', pfmt(a.endAngle, u), tfmt(a.endAngle / 360 * cycle, u)], + ['持续相位', pfmt(a.durationAngle, u), '${tfmt(a.durationAngle / 360 * cycle, u)} · 占循环 ${(a.durationAngle / 3.6).toStringAsFixed(2)}%'], + ['所在层', 'L${a.layer + 1}', '层内序号 ${a.layer + 1}'], + ['顺序约束', _depSummary(a), '前序动作关系'], + ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], + ]; + } + final List out = []; + for (int i = 0; i < fields.length; i++) { + out.add(Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), + decoration: BoxDecoration( + color: i.isEven ? t.panel2.withValues(alpha: 0.7) : Colors.transparent, + borderRadius: BorderRadius.circular(8), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text(fields[i][0], style: TextStyle(color: t.sub, fontSize: 11)), + const Spacer(), + Flexible( + child: Text(fields[i][1], + textAlign: TextAlign.right, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.text, fontSize: 12, fontWeight: FontWeight.w600)), + ), + ], + ), + if (fields[i][2].isNotEmpty) + Align( + alignment: Alignment.centerRight, + child: Text(fields[i][2], style: TextStyle(color: t.dim, fontSize: 10)), + ), + ], + ), + )); + } + return out; + } + + /// 收集以 [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 _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(' · ')})'; + } + + 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), + ), + ], + ), + ); + } + + /// 依赖偏移显示:内部存角度,界面以当前时间单位显示;0 偏移不显示。 + String _depOffsetText(Dependency d) { + if (d.type != DepType.ss || d.offsetAngle == 0) return ''; + return ' +${deg2msStr(d.offsetAngle, c.project.units, c.project.cycle.durationMs, dec: 2)}'; + } + + Widget _depRow(Tokens t, Action a, Dependency d, {bool enabled = true}) { + final Color col = d.type == DepType.fs ? t.fs : t.ss; + return Container( + margin: const EdgeInsets.only(bottom: 5), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), + const SizedBox(width: 8), + Expanded( + child: Text( + '${d.fromId} → ${a.id} ${d.type.name.toUpperCase()}${_depOffsetText(d)}', + style: TextStyle(color: t.sub, fontSize: 10), + ), + ), + Tooltip( + message: '编辑依赖', + child: InkWell( + onTap: enabled + ? () => showDialog( + context: context, + builder: (_) => DependencyEditorDialog( + controller: c, + action: a, + initial: d, + ), + ) + : null, + child: Icon(Icons.edit_outlined, size: 14, color: enabled ? t.accent : t.line2), + ), + ), + const SizedBox(width: 8), + Tooltip( + message: '删除依赖', + child: InkWell( + onTap: enabled ? () => c.removeDependency(d.fromId, a.id) : null, + child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), + ), + ), + ], + ), + ); + } + + Widget _outDepRow(Tokens t, Action a, Action target, Dependency d, {bool enabled = true}) { + final Color col = d.type == DepType.fs ? t.fs : t.ss; + return Container( + margin: const EdgeInsets.only(bottom: 5), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), + const SizedBox(width: 8), + Expanded( + child: Text( + '${a.id} → ${target.id} ${d.type.name.toUpperCase()}${_depOffsetText(d)}', + style: TextStyle(color: t.sub, fontSize: 10), + ), + ), + Tooltip( + message: '编辑依赖', + child: InkWell( + onTap: enabled + ? () => showDialog( + context: context, + builder: (_) => DependencyEditorDialog( + controller: c, + action: target, + initial: d, + ), + ) + : null, + child: Icon(Icons.edit_outlined, size: 14, color: enabled ? t.accent : t.line2), + ), + ), + const SizedBox(width: 8), + Tooltip( + message: '删除依赖', + child: InkWell( + onTap: enabled ? () => c.removeDependency(a.id, target.id) : null, + child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), + ), + ), + ], + ), + ); + } + + Widget _helpCard(Tokens t) { + return Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.help_outline, size: 16, color: t.accent), + const SizedBox(width: 6), + Text('帮助 · 快捷键', style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), + ], + ), + const SizedBox(height: 8), + Text('拖拽 = 平移相位 · 拖端点 = 改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('Shift+拖 = 改层 · F1 = 帮助中心', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('Ctrl+Z / Ctrl+Y = 撤销 / 重做', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ], + ), + ); + } + + Widget _statusBar(Tokens t) { + final UnitSettings u = c.project.units; + final ViewMode mode = c.project.viewState.mode; + final bool circular = mode == ViewMode.circular; + final List items = [ + '循环周期 ${tfmt(c.project.cycle.durationMs, u)}', + '相位 360° = 100%', + '动作 ${c.project.actions.length}', + '依赖 ${_depCount()}', + circular ? '轨道 L1–L${c.project.renderLaneCount}' : '工位 ${c.project.stations.length}', + mode == ViewMode.flow + ? '泳道 L1–L${c.project.renderLaneCount}(流程节点 ${c.project.actions.length})' + : (circular ? '同心圆 ${c.project.laneCount}' : '时间轴 0–${tfmt(c.project.cycle.durationMs, u)}'), + '单位 ${timeUnitLabel(u.timeUnit)} / ${phaseUnitLabel(u.phaseUnit)}', + '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}', + c.status, + ]; + return Container( + height: 32, + padding: const EdgeInsets.symmetric(horizontal: 16), + decoration: BoxDecoration( + color: t.chrome, + border: Border(top: BorderSide(color: t.line2)), + ), + child: Row( + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: items.map((String s) { + final bool last = s == items.last; + return Padding( + padding: const EdgeInsets.only(right: 22), + child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)), + ); + }).toList(), + ), + ), + ), + if (c.dirty) + Padding( + padding: const EdgeInsets.only(right: 14), + child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)), + ), + Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ); + } +} diff --git a/lib/modules/topo/topo_module.dart b/lib/modules/topo/topo_module.dart new file mode 100644 index 0000000..1fe65ed --- /dev/null +++ b/lib/modules/topo/topo_module.dart @@ -0,0 +1,28 @@ +/// 拓扑图模块(规划中)。 +/// +/// 当前仅注册元数据与占位实现;实现时在 `lib/modules/topo/` 下补齐文档模型 +/// 与 UI,并在本类中替换 `PlannedModule` 为真实 [EdcModule] 实现即可。 +library; + +import 'package:flutter/material.dart'; + +import 'package:sequence_diagram/modules/module.dart'; + +/// 拓扑图模块单例(未开放)。 +const TopoModule topoModule = TopoModule(); + +/// 拓扑图模块。 +class TopoModule extends PlannedModule { + /// 构造模块。 + const TopoModule() + : super( + id: 'topo', + name: '拓扑图', + shortName: '拓扑', + icon: Icons.hub_outlined, + accent: 0xFFF472B6, + suffix: '.topo.json', + defaultName: '未命名-拓扑图', + blurb: '网络设备 · 链路', + ); +} diff --git a/lib/persistence/storage.dart b/lib/persistence/storage.dart index f121f72..5dce5fc 100644 --- a/lib/persistence/storage.dart +++ b/lib/persistence/storage.dart @@ -15,7 +15,7 @@ library; import 'dart:convert'; import 'dart:io'; -import '../model/models.dart'; +import 'package:sequence_diagram/model/models.dart'; /// 崩溃恢复信息:描述一次可恢复的自动保存会话。 class RecoveryInfo { diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart index 5efacf5..fa9ed3b 100644 --- a/lib/state/app_controller.dart +++ b/lib/state/app_controller.dart @@ -16,18 +16,18 @@ import 'dart:typed_data'; import 'package:flutter/material.dart' hide Action; -import '../arch/arch_models.dart'; -import '../arch/arch_samples.dart'; -import '../persistence/android_docs.dart'; -import '../sketch/sketch_models.dart'; -import '../sketch/sketch_solver.dart'; -import '../version.dart'; -import '../layout/dep_routes.dart'; -import '../layout/layout.dart'; -import '../layout/flow_layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../persistence/storage.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_samples.dart'; +import 'package:sequence_diagram/persistence/android_docs.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/version.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/persistence/storage.dart'; /// 全局应用控制器(继承 [ChangeNotifier])。 class AppController extends ChangeNotifier { @@ -45,8 +45,9 @@ class AppController extends ChangeNotifier { /// 当前主题亮度(默认浅色 / 白底)。 Brightness _brightness = Brightness.light; - /// 当前顶层设计模块(时序图 / 架构图);仅运行时状态,不随文件保存。 - AppMode _appMode = AppMode.sequence; + /// 当前顶层设计模块 id;null = 首页。模块由 `lib/modules/registry.dart` + /// 注册,控制器不依赖具体模块枚举,新增模块无需修改此处。 + String? _activeModuleId = 'sequence'; /// 架构图当前工具。 ArchTool _archTool = ArchTool.select; @@ -124,7 +125,7 @@ class AppController extends ChangeNotifier { /// 当前模块对应的文件路径(标题 / 状态显示用)。 String? get currentFilePath => - _appMode == AppMode.architecture ? _archFilePath : _filePath; + _activeModuleId == 'architecture' ? _archFilePath : _filePath; /// 架构图文档文件路径。 String? get archFilePath => _archFilePath; @@ -254,7 +255,7 @@ class AppController extends ChangeNotifier { /// 安卓写入公共 Documents,桌面写文件并同步 `.bak` 备份。 Future _autoSaveDocument() async { final String? path = - _appMode == AppMode.architecture ? _archFilePath : _filePath; + _activeModuleId == 'architecture' ? _archFilePath : _filePath; if (!_project.autoSaveEnabled || !_dirty || path == null) return; final DateTime now = DateTime.now(); // 从未保存过时间戳(如刚打开文件):以“现在”为基准,等满一个间隔再自动保存。 @@ -267,7 +268,7 @@ class AppController extends ChangeNotifier { if (now.difference(_lastSavedAt!).inSeconds < minutes * 60) return; _lastSavedAt = now; try { - if (_appMode == AppMode.architecture) { + if (_activeModuleId == 'architecture') { final String json = _project.arch.encode(); if (AndroidDocs.isAvailable) { await AndroidDocs.saveFile( @@ -391,18 +392,19 @@ class AppController extends ChangeNotifier { // ============ 设计合集(模块切换)与架构图 ============ - /// 当前顶层设计模块(时序图 / 架构图)。 - AppMode get appMode => _appMode; + /// 当前顶层设计模块 id;null = 首页。 + String? get activeModuleId => _activeModuleId; + + /// 是否处于首页。 + bool get isHome => _activeModuleId == null; /// 切换顶层设计模块并刷新界面(品牌菜单 / 首页调用)。 - void setAppMode(AppMode m) { - if (_appMode == m) return; - _appMode = m; - _status = switch (m) { - AppMode.home => '首页', - AppMode.sequence => '时序图设计', - AppMode.architecture => '架构图设计 · 手绘识别', - }; + /// + /// [status] 由模块提供进入提示;不传时使用通用文案。 + void setModuleId(String? id, {String? status}) { + if (_activeModuleId == id) return; + _activeModuleId = id; + _status = status ?? (id == null ? '首页' : '已进入模块 $id'); notifyListeners(); } @@ -412,11 +414,11 @@ class AppController extends ChangeNotifier { /// (当前文档数据在进入新模块时会由新建文档替换)。 /// 外壳在离开「有未保存修改的文档」前负责弹窗确认。 void goHome() { - final bool changed = _appMode != AppMode.home || + final bool changed = _activeModuleId != null || _dirty || _filePath != null || _archFilePath != null; - _appMode = AppMode.home; + _activeModuleId = null; _dirty = false; _filePath = null; _archFilePath = null; @@ -1954,19 +1956,29 @@ class AppController extends ChangeNotifier { /// /// 参数 [keepAngle]:为 true 时保持各动作角度不变;为 false 时按 /// `旧时长 / 新时长` 缩放所有动作的起始角与持续角,从而保持其时间不变。 + /// 依赖偏移始终按时间不变换算(界面以时间为主,角度仅内部存储)。 /// 副作用:通过 [_mutate] 记录历史并重算关键路径。 void setCycleDuration(double ms, {bool keepAngle = true}) { - // 计算角度缩放比例:keepAngle 时保持 1;否则按旧/新时长比例缩放。 + // 动作角度按策略缩放;依赖偏移始终按“时间不变”换算(界面以时间为主)。 + final double oldMs = _project.cycle.durationMs; double angleScale = 1; - if (!keepAngle && _project.cycle.durationMs > 0) { - angleScale = _project.cycle.durationMs / ms; + if (!keepAngle && oldMs > 0) { + angleScale = oldMs / ms; } + final double depScale = oldMs > 0 && ms > 0 ? oldMs / ms : 1; List actions = _project.actions; - if (angleScale != 1) { + if (angleScale != 1 || depScale != 1) { actions = actions .map((Action a) => a.copyWith( - startAngle: a.startAngle * angleScale, - durationAngle: a.durationAngle * angleScale, + startAngle: angleScale == 1 ? a.startAngle : a.startAngle * angleScale, + durationAngle: + angleScale == 1 ? a.durationAngle : a.durationAngle * angleScale, + deps: depScale == 1 + ? a.deps + : a.deps + .map((Dependency d) => + d.copyWith(offsetAngle: d.offsetAngle * depScale)) + .toList(), )) .toList(); } @@ -2262,6 +2274,45 @@ class AppController extends ChangeNotifier { ); } + /// 修改一条已有依赖(保留手动拖拽的走线偏移)。 + /// + /// [oldFromId] 为原前置动作;[fromId] 为修改后的前置动作(可保持不变); + /// [type] / [offset] 为新的依赖类型与偏移角。若目标动作已存在来自 + /// [fromId] 的另一条依赖,则合并为本条,避免重复。 + void updateDependency( + String oldFromId, + String toId, { + required String fromId, + required DepType type, + required double offset, + }) { + if (fromId == toId) return; + if (_project.actionById(fromId) == null) return; + final Action? to = _project.actionById(toId); + if (to == null) return; + final int index = to.deps.indexWhere((Dependency d) => d.fromId == oldFromId); + if (index < 0) return; + final Dependency old = to.deps[index]; + final List deps = [ + for (int i = 0; i < to.deps.length; i++) + if (i != index && to.deps[i].fromId != fromId) to.deps[i], + ]; + deps.insert( + index > deps.length ? deps.length : index, + old.copyWith( + fromId: fromId, + toId: toId, + type: type, + offsetAngle: offset, + ), + ); + updateAction( + toId, + (Action x) => x.copyWith(deps: deps), + status: '已修改依赖 $fromId→$toId', + ); + } + /// 移除 [toId] 上来自 [fromId] 的依赖。 void removeDependency(String fromId, String toId) { updateAction( diff --git a/lib/theme/tokens.dart b/lib/theme/tokens.dart index d930d43..b4460c4 100644 --- a/lib/theme/tokens.dart +++ b/lib/theme/tokens.dart @@ -4,7 +4,7 @@ /// 并把它们接入 Flutter 的主题扩展机制,供界面、画布渲染与 SVG 导出共用。 /// /// 架构位置: -/// - 渲染层(`lib/render/`)与导出层(`lib/export/`)都通过 [Tokens] 读取颜色, +/// - 各模块渲染层(`lib/modules/*/render|domain`)与共享导出层(`lib/export/`)都通过 [Tokens] 读取颜色, /// 从而保证画布绘制、SVG 导出与 Material 界面三者配色完全一致。 /// - 深色与浅色两套令牌分别以 [Tokens.dark]、[Tokens.light] 常量提供, /// 由 [Tokens.of] 按 [Brightness] 选择。 diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart index 4008f29..6000866 100644 --- a/lib/ui/app_shell.dart +++ b/lib/ui/app_shell.dart @@ -1,13 +1,11 @@ -// 应用外壳:组织工具栏、左右可停靠侧栏、画布舞台与状态栏的整体布局, -// 并集中处理文件、导出、快捷键与侧栏停靠等交互。 +// 应用外壳:负责公共窗口框架、主题、文件流程、侧栏停靠与全局快捷键。 // -// 架构位置:位于 UI 层顶层(由 main.dart 的根组件加载),向下装配 -// CanvasView / CanvasOverlays / 各类对话框,并通过 AppController 读写 -// 项目状态。本文件重点包含: -// · 全局快捷键绑定(撤销/重做/保存/打开/新建/删除/帮助等); -// · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机; -// · 自适应/紧凑工具栏布局(按可用宽度切换); -// · 文件打开/保存/另存为与 SVG、PNG 导出流程。 +// 架构位置:位于 UI 顶层(main.dart 的根组件加载),**不识别具体模块**: +// - 模块清单、元数据、文档生命周期与工作区 UI 全部来自 +// `lib/modules/registry.dart` + `lib/modules/module.dart`; +// - 外壳只负责:工具栏公共项 / 侧栏停靠轨道 / 状态栏容器 / 文件打开保存 / +// 最近列表 / 全局快捷键 / 模块快捷键合并; +// - 新增模块时不要修改本文件;通过注册表与模块契约扩展。 import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; @@ -15,30 +13,14 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import 'package:flutter/services.dart'; -import '../arch/arch_dxf.dart'; -import '../arch/arch_export.dart'; -import '../arch/arch_models.dart'; -import '../modules/module_registry.dart'; -import '../persistence/recent_store.dart'; -import '../sketch/sketch_models.dart'; -import '../sketch/sketch_solver.dart'; -import '../export/drawio_writer.dart'; -import '../export/export_renderer.dart'; -import '../export/svg_writer.dart'; -import '../layout/layout.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../persistence/android_docs.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import '../update/update_service.dart'; -import '../version.dart'; -import 'ai_dialog.dart'; -import 'arch_panel.dart'; -import 'arch_view.dart'; +import 'package:sequence_diagram/modules/registry.dart'; +import 'package:sequence_diagram/persistence/recent_store.dart'; +import 'package:sequence_diagram/persistence/android_docs.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/update/update_service.dart'; +import 'package:sequence_diagram/version.dart'; import 'brand_menu.dart'; -import 'canvas_overlays.dart'; -import 'canvas_view.dart'; import 'dialogs.dart'; import 'home_view.dart'; import 'update_dialog.dart'; @@ -110,6 +92,24 @@ class _AppShellState extends State { /// 右侧栏是否收起为贴边轨道。 bool get _rightRail => !_rightDocked && !_rightFloat; + /// 当前注册模块;首页为 null。 + EdcModule? get _module => moduleById(c.activeModuleId); + + /// 构造模块 UI 上下文(外壳 -> 模块)。 + ModuleUiContext _moduleUi(Tokens t, {bool compact = false}) => ModuleUiContext( + context: context, + controller: c, + tokens: t, + compact: compact, + leftRail: _leftRail, + rightRail: _rightRail, + leftPanelWidth: _leftPanelWidth, + rightPanelWidth: _rightPanelWidth, + toolScale: _toolScale, + toolFont: _toolFont, + panelControls: (bool left) => _panelControls(t, left), + ); + /// 订阅控制器变化以便刷新界面;启动后延迟静默检查更新。 @override void initState() { @@ -183,23 +183,15 @@ class _AppShellState extends State { /// 从首页 / 品牌菜单进入某模块并**新建**该类型文档(未保存修改先确认)。 Future _startModule(EdcModule m) async { if (!m.available) return; - if (moduleOf(c.appMode)?.id == m.id) return; // 已在该模块 + if (c.activeModuleId == m.id) return; if (!await _confirmDiscardIfDirty()) return; - switch (m.id) { - case 'sequence': - c.newProject(); - c.setAppMode(AppMode.sequence); - case 'architecture': - c.newArchProject(); - c.setAppMode(AppMode.architecture); - default: - c.setStatus('${m.name}:文档类型尚未开放'); - } + m.newDocument(c); + c.setModuleId(m.id, status: m.enterStatus); } /// 返回首页(未保存修改先确认)。 Future _goHome() async { - if (c.appMode == AppMode.home) return; + if (c.isHome) return; if (!await _confirmDiscardIfDirty()) return; c.goHome(); } @@ -224,18 +216,18 @@ class _AppShellState extends State { /// 新建项目:当前模块内新建(未保存修改先确认)。 Future _newProject() async { - if (!await _confirmDiscardIfDirty()) return; - // 架构图模块:新建独立的架构图文档(空画布 + 默认图层)。 - if (c.appMode == AppMode.architecture) { - c.newArchProject(); + final EdcModule? m = _module; + if (m == null) { + await _openDocumentChooser(); return; } - c.newProject(); + if (!await _confirmDiscardIfDirty()) return; + m.newDocument(c); } /// 打开文档(工具栏 / Ctrl+O):模块内直接打开;首页时先选择文档类型。 Future _open() async { - final EdcModule? m = moduleOf(c.appMode); + final EdcModule? m = _module; if (m == null) { await _openDocumentChooser(); return; @@ -250,11 +242,10 @@ class _AppShellState extends State { await _openDocumentOfModule(m); } - /// 打开某模块的文档:时序图 → `*.seq.json`;架构图 → `*.arch.json`。 + /// 打开某模块的文档:后缀与解析由模块契约提供。 Future _openDocumentOfModule(EdcModule m) async { if (!await _confirmDiscardIfDirty()) return; if (!mounted) return; - final bool arch = m.id == 'architecture'; final String suffix = m.suffix; // 安卓版:从公共目录打开(兼容旧目录)。 if (AndroidDocs.isAvailable) { @@ -273,14 +264,8 @@ class _AppShellState extends State { if (mounted) await showMessage(context, '打开失败', '未找到文件 $name'); return; } - final String content = utf8.decode(bytes); - if (arch) { - c.setAppMode(AppMode.architecture); - c.loadArchDoc(ArchDoc.decode(content), path: null); - } else { - c.setAppMode(AppMode.sequence); - c.loadProject(Project.decode(content), path: null); - } + c.setModuleId(m.id, status: m.enterStatus); + m.loadDocument(c, utf8.decode(bytes), path: null); c.setStatus('已打开 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '打开失败', '$e'); @@ -290,7 +275,7 @@ class _AppShellState extends State { final String? path = await pickFile( context, save: false, - initialPath: c.currentFilePath, + initialPath: m.filePath(c), suffix: suffix, ); if (path == null) return; @@ -312,13 +297,8 @@ class _AppShellState extends State { } else { src = await File(path).readAsString(); } - if (m.id == 'architecture') { - c.setAppMode(AppMode.architecture); - c.loadArchDoc(ArchDoc.decode(src), path: AndroidDocs.isAvailable ? null : path); - } else { - c.setAppMode(AppMode.sequence); - c.loadProject(Project.decode(src), path: AndroidDocs.isAvailable ? null : path); - } + c.setModuleId(m.id, status: m.enterStatus); + m.loadDocument(c, src, path: AndroidDocs.isAvailable ? null : path); _rememberRecent(path, m.id); } @@ -340,55 +320,46 @@ class _AppShellState extends State { /// 时序图与架构图分别保存为 `*.seq.json` 与 `*.arch.json` 两个独立文件 /// (内容互不包含;时序图中不含架构数据)。 Future _save() async { + final EdcModule? m = _module; + if (m == null) return; + final String? path = m.filePath(c); // 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。 - if (AndroidDocs.isAvailable || c.currentFilePath == null) { + if (AndroidDocs.isAvailable || path == null) { await _saveAs(); return; } - if (c.appMode == AppMode.architecture) { - try { - await c.saveArchAs(c.archFilePath!); - _rememberRecent(c.archFilePath!, 'architecture'); - } catch (e) { - if (mounted) await showMessage(context, '保存失败', '$e'); - } - return; - } - final bool ok = await c.save(); - if (ok && c.filePath != null) { - _rememberRecent(c.filePath!, 'sequence'); + try { + await m.saveTo(c, path); + _rememberRecent(path, m.id); + } catch (e) { + if (mounted) await showMessage(context, '保存失败', '$e'); } } /// 另存为:按当前模块选择目标路径(`*.seq.json` / `*.arch.json`),写入并生成 `.bak` 备份。 Future _saveAs() async { - final bool arch = c.appMode == AppMode.architecture; - final String suffix = arch ? '.arch.json' : '.seq.json'; + final EdcModule? m = _module; + if (m == null) return; + final String suffix = m.suffix; + final String? current = m.filePath(c); // 安卓版:写入公共 Documents(MediaStore 通道)。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, - defaultName: '${c.project.name}$suffix', + defaultName: '${m.documentName(c)}$suffix', suffix: suffix, ), ); if (name == null) return; try { - if (arch) { - await AndroidDocs.saveFile( - name, Uint8List.fromList(utf8.encode(c.arch.encode())), - mime: 'application/json'); - await c.markArchSaved('${AndroidDocs.location()}/$name'); - _rememberRecent('${AndroidDocs.location()}/$name', 'architecture'); - } else { - final Uint8List data = Uint8List.fromList( - utf8.encode(c.project.encode(includeArch: false))); - await AndroidDocs.saveFile(name, data, mime: 'application/json'); - await c.markSaved('${AndroidDocs.location()}/$name'); - _rememberRecent('${AndroidDocs.location()}/$name', 'sequence'); - } + final Uint8List data = + Uint8List.fromList(utf8.encode(m.encodeDocument(c))); + await AndroidDocs.saveFile(name, data, mime: 'application/json'); + final String display = '${AndroidDocs.location()}/$name'; + await m.markSaved(c, display); + _rememberRecent(display, m.id); } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } @@ -397,322 +368,19 @@ class _AppShellState extends State { final String? path = await pickFile( context, save: true, - initialPath: c.currentFilePath, - defaultName: c.currentFilePath == null ? '${c.project.name}$suffix' : null, + initialPath: current, + defaultName: current == null ? '${m.documentName(c)}$suffix' : null, suffix: suffix, ); if (path == null) return; try { - if (arch) { - await c.saveArchAs(path); - _rememberRecent(path, 'architecture'); - } else { - await c.saveAs(path); - _rememberRecent(path, 'sequence'); - if (mounted) { - c.setStatus('已保存 ${path.split(RegExp(r'[\\/]')).last}(含 .bak 备份)'); - } - } + await m.saveTo(c, path); + _rememberRecent(path, m.id); } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } } - /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 - /// - /// 三种视图均支持(流程图由 [FlowLayout] 几何直接生成)。 - Future _exportSvg() async { - if (!c.licensed) { - if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); - return; - } - // 安卓版:写入公共 Documents/EDC。 - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}.svg', - suffix: '.svg', - ), - ); - if (name == null) return; - try { - final String svg = SvgWriter( - project: c.project, - tokens: Tokens.of(c.brightness), - mode: c.project.viewState.mode, - ).build(); - await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}.svg', - suffix: '.svg', - ); - if (path == null) return; - try { - final String svg = SvgWriter( - project: c.project, - tokens: Tokens.of(c.brightness), - mode: c.project.viewState.mode, - ).build(); - await File(path).writeAsString(svg, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - - /// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。 - /// - /// 三种视图均支持(流程图走 [FlowchartPainter] 离屏渲染)。 - Future _exportPng() async { - if (!c.licensed) { - if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); - return; - } - final Uint8List bytes; - try { - bytes = await renderExportPng( - project: c.project, - tokens: Tokens.of(c.brightness), - criticalActions: c.criticalActions, - criticalDeps: c.criticalDeps, - ); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - return; - } - if (!mounted) return; - // 安卓版:写入配置的公共目录。 - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}.png', - suffix: '.png', - ), - ); - if (name == null) return; - try { - await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}.png', - suffix: '.png', - ); - if (path == null) return; - try { - await File(path).writeAsBytes(bytes, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - - /// 导出架构图 SVG(矢量,纯白背景)。 - Future _exportArchSvg() async { - if (!c.licensed) { - if (mounted) { - await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); - } - return; - } - final String svg = buildArchSvg(doc: c.arch, baseTokens: Tokens.of(c.brightness)); - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}-架构图.svg', - suffix: '.svg', - ), - ); - if (name == null) return; - try { - await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), - mime: 'image/svg+xml'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}-架构图.svg', - suffix: '.svg', - ); - if (path == null) return; - try { - await File(path).writeAsString(svg, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - - /// 导出架构图 PNG(固定 1920×1080 逻辑画布 × 2 倍像素,纯白背景)。 - Future _exportArchPng() async { - if (!c.licensed) { - if (mounted) { - await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); - } - return; - } - final Uint8List bytes; - try { - bytes = await renderArchPng( - doc: c.arch, - baseTokens: Tokens.of(c.brightness), - projectName: c.project.name, - ); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - return; - } - if (!mounted) return; - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}-架构图.png', - suffix: '.png', - ), - ); - if (name == null) return; - try { - await AndroidDocs.saveFile(name, bytes, mime: 'image/png'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}-架构图.png', - suffix: '.png', - ); - if (path == null) return; - try { - await File(path).writeAsBytes(bytes, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - - /// 导出架构图 DXF(AutoCAD R12 ASCII):图层 / 图形 / 连线 / 文字均保留。 - Future _exportArchDxf() async { - if (!c.licensed) { - if (mounted) { - await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 DXF。'); - } - return; - } - final String dxf = buildArchDxf(doc: c.arch); - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}-架构图.dxf', - suffix: '.dxf', - ), - ); - if (name == null) return; - try { - await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(dxf)), - mime: 'application/dxf'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}-架构图.dxf', - suffix: '.dxf', - ); - if (path == null) return; - try { - await File(path).writeAsString(dxf, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - - /// 导出 drawio:仅流程图视图提供,输出 diagrams.net 可直接打开并继续编辑的 XML。 - /// - /// 条形 / 圆周视图调用时给出明确提示(不做静默失败)。 - Future _exportDrawio() async { - if (c.project.viewState.mode != ViewMode.flow) { - if (mounted) { - await showMessage(context, '导出 drawio', '仅流程图视图支持导出 drawio;条形 / 圆周视图请导出 SVG 或 PNG。'); - } - return; - } - if (!c.licensed) { - if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 drawio。'); - return; - } - final String xml = DrawioWriter(project: c.project, tokens: Tokens.of(c.brightness)).build(); - // 安卓版:写入公共 Documents 目录。 - if (AndroidDocs.isAvailable) { - final String? name = await showDialog( - context: context, - builder: (_) => AndroidFileDialog( - saveMode: true, - defaultName: '${c.project.name}.drawio', - suffix: '.drawio', - ), - ); - if (name == null) return; - try { - await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(xml)), mime: 'application/xml'); - if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - return; - } - final String? path = await pickFile( - context, - save: true, - defaultName: '${c.project.name}.drawio', - suffix: '.drawio', - ); - if (path == null) return; - try { - await File(path).writeAsString(xml, flush: true); - if (mounted) c.setStatus('已导出 $path'); - } catch (e) { - if (mounted) await showMessage(context, '导出失败', '$e'); - } - } - // ===================== 主界面构建 ===================== /// 首页(空白启动工作台):新建文档网格 / 打开 / 最近打开。 @@ -738,58 +406,30 @@ class _AppShellState extends State { Widget build(BuildContext context) { final Tokens t = context.tok; // 首页(空白启动工作台):不渲染工作区工具栏 / 画布 / 状态栏。 - if (c.appMode == AppMode.home) { - return _buildHome(t); - } - // 顶层模块:架构图模式下画布、工具栏与侧栏切换为架构图工具。 - final bool arch = c.appMode == AppMode.architecture; - // 流程图视图只读:撤销 / 重做 / 删除等编辑操作统一停用(与置灰按钮一致)。 - final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; + if (c.isHome) return _buildHome(t); + final EdcModule? module = _module; + if (module == null) return _buildHome(t); + final ModuleUiContext ui = _moduleUi(t); + // 只读视图(如时序图流程图):撤销 / 重做等编辑操作统一停用。 + final bool readOnly = module.isReadOnly(c); // 全局快捷键绑定:编辑、文件、帮助、主题等。 return CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.keyZ, control: true): () { - if (!flow) c.undo(); + if (!readOnly) c.undo(); }, const SingleActivator(LogicalKeyboardKey.keyY, control: true): () { - if (!flow) c.redo(); + if (!readOnly) c.redo(); }, const SingleActivator(LogicalKeyboardKey.keyS, control: true): _save, const SingleActivator(LogicalKeyboardKey.keyO, control: true): _open, const SingleActivator(LogicalKeyboardKey.keyN, control: true): _newProject, - const SingleActivator(LogicalKeyboardKey.keyA, control: true): () { - if (c.appMode == AppMode.architecture) { - if (c.sketchMode) { - c.selectAllSketch(); - } else { - c.selectAllArch(); - } - } - }, - const SingleActivator(LogicalKeyboardKey.delete): () { - if (c.appMode == AppMode.architecture) { - if (c.sketchMode) { - c.deleteSketchSelection(); - } else { - c.removeArchSelection(); - } - } else if (!flow && c.selectedId != null) { - c.deleteAction(c.selectedId!); - } - }, const SingleActivator(LogicalKeyboardKey.f1): () => showDialog(context: context, builder: (_) => const HelpDialog()), const SingleActivator(LogicalKeyboardKey.f2): () => showDialog(context: context, builder: (_) => SettingsDialog(controller: c)), const SingleActivator(LogicalKeyboardKey.f3): c.toggleTheme, - const SingleActivator(LogicalKeyboardKey.escape): () { - // 草图命令进行中:Esc 取消命令(其余场景 Esc 不拦截)。 - if (c.appMode == AppMode.architecture && - c.sketchMode && - (c.sketchPendingCons != null || c.sketchPendingDim != null)) { - c.cancelSketchCommand(); - } - }, + ...module.buildShortcuts(ui), }, child: Focus( autofocus: true, @@ -810,48 +450,27 @@ class _AppShellState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // 左侧栏:仅在停靠状态占用布局宽度。 - if (_leftDocked) _leftPanel(t), + if (_leftDocked && module.hasLeftPanel) _moduleLeftPanel(t), Expanded( - // 画布舞台:可绘制区域,叠加画布视图与浮层。 + // 画布舞台:模块提供工作区,外壳只叠加侧栏轨道 / 浮动面板。 child: Stack( children: [ - if (arch) - // 架构图:独立画布(手绘识别 / 连线 / 属性编辑)。 - Positioned.fill( - child: Container( - color: t.canvas2, - child: ArchView(controller: c), - ), - ) - else ...[ - // 底层:可交互的画布。 - Positioned.fill( - child: Container(color: t.canvas2, child: CanvasView(controller: c)), - ), - // 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。 - Positioned.fill( - child: CanvasOverlays( - controller: c, - leftInset: _leftRail ? 22 : 0, - rightInset: _rightRail ? 22 : 0, - ), - ), - ], + Positioned.fill(child: module.buildWorkspace(ui)), // 收起状态:贴边轨道(悬停可展开为悬浮面板)。 - if (_leftRail) + if (module.hasLeftPanel && _leftRail) Positioned(left: 0, top: 0, bottom: 0, child: _rail(t, true)), - if (_rightRail) + if (module.hasRightPanel && _rightRail) Positioned(right: 0, top: 0, bottom: 0, child: _rail(t, false)), // 悬浮状态:覆盖在画布上的可浮动侧栏。 - if (_leftFloat) + if (module.hasLeftPanel && _leftFloat) Positioned(left: 0, top: 0, bottom: 0, child: _floating(t, true)), - if (_rightFloat) + if (module.hasRightPanel && _rightFloat) Positioned(right: 0, top: 0, bottom: 0, child: _floating(t, false)), ], ), ), // 右侧栏:仅在停靠状态占用布局宽度。 - if (_rightDocked) _rightPanel(t), + if (_rightDocked && module.hasRightPanel) _moduleRightPanel(t), ], ), ), @@ -859,7 +478,7 @@ class _AppShellState extends State { Container( color: t.chrome, padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom), - child: _statusBar(t), + child: _moduleStatusBar(t), ), ], ), @@ -942,8 +561,9 @@ class _AppShellState extends State { /// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。 Widget _toolbar(Tokens t) { final double s = _toolScale; - final bool arch = c.appMode == AppMode.architecture; - final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; + final EdcModule? module = _module; + if (module == null) return const SizedBox.shrink(); + final bool readOnly = module.isReadOnly(c); return Container( height: 54 * s, padding: EdgeInsets.symmetric(horizontal: 6 * s), @@ -953,10 +573,10 @@ class _AppShellState extends State { ), child: LayoutBuilder( builder: (BuildContext ctx, BoxConstraints cons) { - // 响应式断点:宽于 1760 用完整布局;否则用紧凑布局, - // 保证在 1920×1080(含 150% 缩放下的 1280 逻辑宽度)也能全部显示。 + // 响应式断点:宽于 1760 用完整布局;否则用紧凑布局。 final bool compact = cons.maxWidth < 1760; - // 侧栏开关(两种布局共用)。 + final ModuleUiContext ui = _moduleUi(t, compact: compact); + // 侧栏开关(模块提供侧栏时才显示)。 final Widget sideToggleLeft = _iconBtn(t, Icons.view_sidebar_outlined, () => setState(() { if (_leftVisible) { _leftVisible = false; @@ -979,80 +599,36 @@ class _AppShellState extends State { } }), tooltip: '显示 / 隐藏右侧栏'), ); - - final List left; - final List right; - if (!compact) { - // 完整布局:文件 / 编辑操作图标化 + 分段视图切换。 - left = [ - BrandMenuButton(controller: c, scale: s, onCommand: _handleBrandCommand), - SizedBox(width: 14 * s), - _iconBtn(t, Icons.note_add_outlined, _newProject, tooltip: '新建 Ctrl+N'), - _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), - _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), - SizedBox(width: 6 * s), - // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 - _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, - tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), - _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, - tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), - SizedBox(width: 6 * s), - if (!arch) _aiBtn(t), - if (!arch) SizedBox(width: 12 * s), - if (arch) _archTools(t, false) else _segmented(t), - ]; - right = [ - // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 - _exportMenu(t), - SizedBox(width: 6 * s), - _zoomBox(t), - SizedBox(width: 6 * s), - _iconBtn(t, Icons.crop_free, arch ? c.archFit : c.fitView, tooltip: '适应视图'), - if (!arch) SizedBox(width: 8 * s), - if (!arch) _unitDropdown(t), - if (!arch) SizedBox(width: 8 * s), - sideToggleLeft, - sideToggleRight, - _iconBtn(t, Icons.help_outline, () => - showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), - _updateBtn(t), - _themeToggle(t), - ]; - } else { - // 紧凑布局:图标化 + 导出合并为菜单,尽量压缩宽度。 - left = [ - BrandMenuButton(controller: c, scale: s, compact: true, onCommand: _handleBrandCommand), - SizedBox(width: 10 * s), - _iconBtn(t, Icons.note_add_outlined, _newProject, tooltip: '新建 Ctrl+N'), - _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), - _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), - SizedBox(width: 4 * s), - // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 - _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, - tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), - _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, - tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), - SizedBox(width: 4 * s), - // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 - if (!arch) _aiBtn(t), - if (!arch) SizedBox(width: 8 * s), - if (arch) _archTools(t, true) else _segmented(t, compact: true), - ]; - right = [ - // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 - _exportMenu(t), - SizedBox(width: 4 * s), - _zoomBox(t), - _iconBtn(t, Icons.crop_free, arch ? c.archFit : c.fitView, tooltip: '适应视图'), - if (!arch) _unitDropdown(t), - sideToggleLeft, - sideToggleRight, - _iconBtn(t, Icons.help_outline, () => - showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), - _updateBtn(t), - _themeToggle(t), - ]; - } + final double gap = compact ? 4 * s : 6 * s; + final List left = [ + BrandMenuButton( + controller: c, + scale: s, + compact: compact, + onCommand: _handleBrandCommand, + ), + SizedBox(width: compact ? 10 * s : 14 * s), + _iconBtn(t, Icons.note_add_outlined, _newProject, tooltip: '新建 Ctrl+N'), + _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), + _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), + SizedBox(width: gap), + _iconBtn(t, Icons.undo, !readOnly && c.canUndo ? c.undo : null, + tooltip: readOnly ? '撤销(当前视图只读)' : '撤销 Ctrl+Z'), + _iconBtn(t, Icons.redo, !readOnly && c.canRedo ? c.redo : null, + tooltip: readOnly ? '重做(当前视图只读)' : '重做 Ctrl+Y'), + SizedBox(width: gap), + ...module.buildToolbarCenter(ui, compact: compact), + ]; + final List right = [ + ...module.buildToolbarRight(ui), + if (module.hasLeftPanel || module.hasRightPanel) SizedBox(width: gap), + if (module.hasLeftPanel) sideToggleLeft, + if (module.hasRightPanel) sideToggleRight, + _iconBtn(t, Icons.help_outline, () => + showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), + _updateBtn(t), + _themeToggle(t), + ]; // 用「最小宽度 = 视口宽度」约束让内容铺满整条工具栏: // 空间足够时 Spacer 把右侧工具组顶到最右(不再留空白); // 空间不足时横向滚动,避免溢出。 @@ -1070,262 +646,6 @@ class _AppShellState extends State { ); } - /// 视图模式分段控件:条形节拍 / 圆周节拍 / 流程图 一键切换。 - /// - /// [compact] 为真时使用更窄的宽度,适配 1920×1080 等较小窗口。 - Widget _segmented(Tokens t, {bool compact = false}) { - final ViewMode mode = c.project.viewState.mode; - Widget seg(String label, bool active, VoidCallback onTap) { - return InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(10), - child: Container( - width: (compact ? 84 : 118) * _toolScale, - height: 34 * _toolScale, - alignment: Alignment.center, - decoration: BoxDecoration( - color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent, - borderRadius: BorderRadius.circular(10), - border: active ? Border.all(color: t.accent, width: 1.4) : null, - ), - child: Text(label, - style: TextStyle( - color: active ? t.accent : t.sub, - fontWeight: active ? FontWeight.w600 : FontWeight.normal, - fontSize: _toolFont(12), - )), - ), - ); - } - - return Container( - padding: EdgeInsets.all(3 * _toolScale), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: t.line2), - ), - child: Row( - children: [ - seg('条形节拍', mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar)), - seg('圆周节拍', mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular)), - seg('流程图', mode == ViewMode.flow, () => c.setViewMode(ViewMode.flow)), - ], - ), - ); - } - - /// 架构图工具分段控件:选择 / 手绘 / 连线(草图模式显示草图状态条)。 - Widget _archTools(Tokens t, bool compact) { - // 草图模式:工具在左侧栏,这里显示状态与快捷退出。 - if (c.sketchMode) { - return Container( - padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), - height: 34 * _toolScale, - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: t.accent), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.edit_note, size: 15 * _toolScale, color: t.accent), - SizedBox(width: 6 * _toolScale), - Text( - '参数化草图 · ${sketchToolLabel(c.sketchTool)}', - style: TextStyle( - color: t.accent, - fontSize: _toolFont(11), - fontWeight: FontWeight.w600, - ), - ), - SizedBox(width: 10 * _toolScale), - InkWell( - onTap: () => c.setSketchMode(false), - borderRadius: BorderRadius.circular(7), - child: Container( - padding: EdgeInsets.symmetric( - horizontal: 8 * _toolScale, vertical: 3 * _toolScale), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.line), - ), - child: Text('退出草图', - style: - TextStyle(color: t.sub, fontSize: _toolFont(10.5))), - ), - ), - ], - ), - ); - } - final ArchTool tool = c.archTool; - Widget seg(String label, IconData icon, ArchTool value, String tip) { - final bool active = tool == value; - return Tooltip( - message: tip, - child: InkWell( - onTap: () => c.setArchTool(value), - borderRadius: BorderRadius.circular(10), - child: Container( - width: (compact ? 74 : 90) * _toolScale, - height: 34 * _toolScale, - alignment: Alignment.center, - decoration: BoxDecoration( - color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent, - borderRadius: BorderRadius.circular(10), - border: active ? Border.all(color: t.accent, width: 1.4) : null, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icon, size: 15 * _toolScale, color: active ? t.accent : t.sub), - SizedBox(width: 4 * _toolScale), - Text(label, - style: TextStyle( - color: active ? t.accent : t.sub, - fontWeight: active ? FontWeight.w600 : FontWeight.normal, - fontSize: _toolFont(12), - )), - ], - ), - ), - ), - ); - } - - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - padding: EdgeInsets.all(3 * _toolScale), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: t.line2), - ), - child: Row( - children: [ - seg('选择', Icons.near_me_outlined, ArchTool.select, '选择 / 移动 / 缩放'), - seg('手绘', Icons.gesture, ArchTool.pen, - c.archAutoRecognize ? '按住拖动绘制,松手自动识别' : '按住拖动绘制;画完点「识别」确认识别'), - seg('连线', Icons.arrow_right_alt, ArchTool.connect, - '从图形拖到另一个图形(横平竖直正交走线,角点可拖拽)'), - seg('橡皮', Icons.cleaning_services_outlined, ArchTool.eraser, - '擦除图形 / 墨迹 / 连线(拖动连擦,一次撤销可整体回退)'), - ], - ), - ), - SizedBox(width: 6 * _toolScale), - // 「识别」确认按钮:手动模式下把待识别墨迹统一识别(自动模式下也可用)。 - Container( - padding: EdgeInsets.all(3 * _toolScale), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: t.line2), - ), - child: InkWell( - onTap: c.arch.strokes.isEmpty ? null : c.archRecognizeInk, - borderRadius: BorderRadius.circular(9), - child: Container( - height: 34 * _toolScale, - padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale), - alignment: Alignment.center, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.auto_fix_high, - size: 15 * _toolScale, - color: c.arch.strokes.isEmpty ? t.dim : t.accent), - SizedBox(width: 5 * _toolScale), - Text( - '识别(${c.arch.strokes.length})', - style: TextStyle( - color: c.arch.strokes.isEmpty ? t.dim : t.accent, - fontSize: _toolFont(11), - fontWeight: FontWeight.w600, - ), - ), - ], - ), - ), - ), - ), - ], - ); - } - - /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮(时序图 / 架构图通用)。 - Widget _zoomBox(Tokens t) { - final double s = _toolScale; - final bool arch = c.appMode == AppMode.architecture; - final double zoom = arch ? c.arch.zoom : c.project.viewState.zoom; - final String pct = '${(zoom * 100).round()}%'; - return Container( - height: 34 * s, - padding: EdgeInsets.symmetric(horizontal: 4 * s), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(9), - border: Border.all(color: t.line2), - ), - child: Row( - children: [ - _miniIcon(t, Icons.remove, () => arch ? c.archZoomBy(0.9) : c.zoomBy(0.9)), - SizedBox( - width: 52 * s, - child: Text(pct, - textAlign: TextAlign.center, style: TextStyle(color: t.text, fontSize: _toolFont(11))), - ), - _miniIcon(t, Icons.add, () => arch ? c.archZoomBy(1.1) : c.zoomBy(1.1)), - ], - ), - ); - } - - /// 缩放控件内的小图标按钮。 - Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) { - return InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(6), - child: Padding( - padding: EdgeInsets.all(6 * _toolScale), - child: Icon(icon, size: 15 * _toolScale, color: t.sub), - ), - ); - } - - /// 时间单位下拉框:切换 ms / s / min。 - Widget _unitDropdown(Tokens t) { - final double s = _toolScale; - return Container( - height: 34 * s, - padding: EdgeInsets.symmetric(horizontal: 10 * s), - decoration: BoxDecoration( - color: t.panel, - borderRadius: BorderRadius.circular(9), - border: Border.all(color: t.accent, width: 1.2), - ), - child: DropdownButton( - value: c.project.units.timeUnit, - underline: const SizedBox.shrink(), - dropdownColor: t.dialog, - borderRadius: BorderRadius.circular(9), - style: TextStyle(color: t.accent, fontSize: _toolFont(11), fontWeight: FontWeight.w600), - icon: Icon(Icons.keyboard_arrow_down, color: t.accent, size: 18 * s), - items: TimeUnit.values - .map((TimeUnit u) => DropdownMenuItem(value: u, child: Text(timeUnitLabel(u)))) - .toList(), - onChanged: (TimeUnit? u) { - if (u != null) c.setUnits(c.project.units.copyWith(timeUnit: u)); - }, - ), - ); - } - /// 主题切换控件:日间 / 夜间两段式按钮。 Widget _themeToggle(Tokens t) { final bool light = c.brightness == Brightness.light; @@ -1370,150 +690,6 @@ class _AppShellState extends State { ); } - /// 导出下拉菜单:合并原「导出 SVG / 导出 PNG」两个按钮。 - /// - /// 选项规则(1.3 产品约定): - /// - 「导出 SVG」「导出 PNG」三种视图(条形 / 圆周 / 流程图)均可用; - /// - 「导出 drawio」仅在流程图视图出现(条形 / 圆周视图不提供); - /// - 未授权时各项置灰(桌面无 license 不允许导出)。 - Widget _exportMenu(Tokens t) { - final double s = _toolScale; - final bool arch = c.appMode == AppMode.architecture; - final bool licensed = c.licensed; - final bool flow = c.project.viewState.mode == ViewMode.flow; - final Color fg = licensed ? Colors.white : t.dim; - return Padding( - padding: EdgeInsets.symmetric(horizontal: 3 * s), - child: PopupMenuButton( - tooltip: arch - ? '导出(SVG / PNG / DXF)· 架构图' - : '导出(SVG / PNG${flow ? ' / drawio' : ''})', - color: t.panel2, - position: PopupMenuPosition.under, - onSelected: (String v) { - if (v == 'svg') { - if (arch) { - _exportArchSvg(); - } else { - _exportSvg(); - } - } - if (v == 'png') { - if (arch) { - _exportArchPng(); - } else { - _exportPng(); - } - } - if (v == 'dxf' && arch) _exportArchDxf(); - if (v == 'drawio') _exportDrawio(); - }, - itemBuilder: (BuildContext ctx) => >[ - _exportItem( - t, - 'svg', - Icons.code, - '导出 SVG', - arch ? '矢量图:架构图无损缩放 / 二次编辑' : '矢量图:无损缩放 / 打印 / 二次编辑', - licensed), - _exportItem(t, 'png', Icons.image_outlined, '导出 PNG', '位图(3840×2160):分享 / 汇报', licensed), - // 架构图额外支持 DXF(AutoCAD 系软件可继续编辑)。 - if (arch) - _exportItem(t, 'dxf', Icons.architecture, '导出 DXF', - 'AutoCAD / DraftSight 等可编辑的 CAD 图纸', licensed), - // drawio 仅在流程图视图提供;其余视图不出现该项目。 - if (!arch && flow) - _exportItem(t, 'drawio', Icons.account_tree_outlined, '导出 drawio', - 'diagrams.net 可编辑工程', licensed), - ], - child: Container( - height: 34 * s, - padding: EdgeInsets.symmetric(horizontal: 12 * s), - decoration: BoxDecoration( - color: licensed ? t.accent2 : t.panel2, - borderRadius: BorderRadius.circular(9), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.ios_share, size: 15 * s, color: fg), - SizedBox(width: 6 * s), - Text('导出', - style: TextStyle(fontSize: _toolFont(11), fontWeight: FontWeight.w600, color: fg)), - Icon(Icons.arrow_drop_down, size: 18 * s, color: fg), - ], - ), - ), - ), - ); - } - - /// 导出菜单单项:图标 + 名称 + 一句说明;[enabled] 为 false 时整体置灰。 - /// - /// 菜单宽度有限(PopupMenu 默认上限约 256px),文本统一单行省略, - /// 避免窄窗口 / 紧凑布局下溢出。 - PopupMenuItem _exportItem( - Tokens t, String value, IconData icon, String label, String hint, bool enabled) { - final Color main = enabled ? t.text : t.dim; - return PopupMenuItem( - value: value, - enabled: enabled, - height: 46, - child: Row( - children: [ - Icon(icon, size: 17, color: enabled ? t.accent : t.dim), - const SizedBox(width: 10), - Expanded( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)), - Text(hint, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)), - ], - ), - ), - ], - ), - ); - } - - /// AI 生成按钮:打开「自然语言 → 时序图」对话框;尺寸随 [_toolScale] 缩放。 - /// - /// AI 只服务时序图(生成条形 / 圆周视图的底层数据),流程图页置灰禁用。 - Widget _aiBtn(Tokens t) { - final double s = _toolScale; - final bool enabled = c.project.viewState.mode != ViewMode.flow; - final Widget btn = FilledButton.icon( - onPressed: enabled - ? () => showDialog( - context: context, - builder: (_) => AiGenerateDialog(controller: c), - ) - : null, - icon: Icon(Icons.auto_awesome, size: 16 * s), - label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), - style: FilledButton.styleFrom( - backgroundColor: enabled ? t.accent2 : t.panel2, - foregroundColor: enabled ? Colors.white : t.dim, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), - minimumSize: Size(0, 34 * s), - tapTargetSize: MaterialTapTargetSize.shrinkWrap, - ), - ); - return Padding( - padding: EdgeInsets.symmetric(horizontal: 3 * s), - child: enabled ? btn : Tooltip(message: 'AI 生成仅针对时序图(条形 / 圆周视图)', child: btn), - ); - } - /// 图标按钮,可附带 tooltip 与自定义颜色;尺寸随 [_toolScale] 缩放, /// 触屏平台收紧点按区域,避免默认 48dp 目标把工具栏撑满。 Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) { @@ -1671,1269 +847,31 @@ class _AppShellState extends State { _rightHover = false; } }), - child: left ? _leftPanel(t, floating: true) : _rightPanel(t, floating: true), + child: left ? _moduleLeftPanel(t, floating: true) : _moduleRightPanel(t, floating: true), ); } - // ===================== 左侧栏内容 ===================== - - /// 架构图左侧栏容器(手绘识别 / 图形库 / 颜色 / 示例场景)。 - Widget _archLeftPanel(Tokens t, {bool floating = false}) { - return Container( - width: _leftPanelWidth, - decoration: BoxDecoration( - color: t.panel, - border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), - boxShadow: floating - ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] - : null, - ), - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - _sectionLabel(t, '架构图 · 设计工具'), - const Spacer(), - _panelControls(t, true), - ], - ), - const SizedBox(height: 10), - ArchLeftBody(controller: c), - ], - ), - ), - ); + /// 当前模块左侧栏(外壳停靠 / 轨道 / 悬浮共用)。 + Widget _moduleLeftPanel(Tokens t, {bool floating = false}) { + final EdcModule? m = _module; + if (m == null || !m.hasLeftPanel) return const SizedBox.shrink(); + return m.buildLeftPanel(_moduleUi(t), floating: floating) ?? + const SizedBox.shrink(); } - /// 架构图右侧栏容器(选中对象属性)。 - Widget _archRightPanel(Tokens t, {bool floating = false}) { - return Container( - width: _rightPanelWidth, - decoration: BoxDecoration( - color: t.panel, - border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), - boxShadow: floating - ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] - : null, - ), - child: Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), - child: Row( - children: [ - _sectionLabel(t, '属性 · 架构图'), - const Spacer(), - _panelControls(t, false), - ], - ), - ), - Expanded( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), - child: ArchRightBody(controller: c), - ), - ), - ], - ), - ); + /// 当前模块右侧栏。 + Widget _moduleRightPanel(Tokens t, {bool floating = false}) { + final EdcModule? m = _module; + if (m == null || !m.hasRightPanel) return const SizedBox.shrink(); + return m.buildRightPanel(_moduleUi(t), floating: floating) ?? + const SizedBox.shrink(); } - /// 构建左侧栏:项目概览、动作/工位列表、视图模式、显示选项、 - /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 - Widget _leftPanel(Tokens t, {bool floating = false}) { - // 架构图模块使用独立的左侧栏(图形库 / 识别开关 / 示例)。 - if (c.appMode == AppMode.architecture) { - return _archLeftPanel(t, floating: floating); - } - final bool bar = c.project.viewState.mode == ViewMode.bar; - final bool flow = c.project.viewState.mode == ViewMode.flow; - return Container( - width: _leftPanelWidth, - decoration: BoxDecoration( - color: t.panel, - border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), - boxShadow: floating - ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] - : null, - ), - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - _sectionLabel(t, '文档设置'), - const Spacer(), - _panelControls(t, true), - ], - ), - const SizedBox(height: 8), - _editEntry( - t, - icon: Icons.edit_note, - label: '文档设置', - enabled: !flow, - onTap: () => showDialog( - context: context, - builder: (_) => SettingsDialog(controller: c), - ), - ), - // 较浅的分隔横线,区分上方「文档设置」与下方「动作和执行编辑」。 - const SizedBox(height: 14), - Divider(height: 1, thickness: 1, color: t.line), - const SizedBox(height: 14), - Row( - children: [ - // 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。 - Expanded(child: _sectionLabel(t, '动作和执行编辑')), - _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, - flow ? null : () => c.addAction(startAngle: 0)), - const SizedBox(width: 6), - // 至少保留一个动作 / 泳道:只剩一个时禁用删除;流程图只读时禁用。 - _headerAction( - t, - Icons.delete_outline, - '删除', - t.danger, - Colors.white, - (flow || c.selectedId == null || c.project.actions.length <= 1) - ? null - : () => c.deleteAction(c.selectedId!), - ), - ], - ), - const SizedBox(height: 8), - // 按泳道 / 轨道分组:同一泳道内的多个动作合并显示(最多两行,/ 分隔)。 - ..._laneRows(t, bar), - const SizedBox(height: 8), - // 工位 / 相位分区管理入口,同属「动作和执行编辑」区域。 - // 工位:一个流程可包含多个工位,可增删改与排序。 - _editEntry( - t, - icon: Icons.precision_manufacturing_outlined, - label: '编辑工位', - badge: c.project.stations.length, - enabled: !flow, - onTap: () => showDialog( - context: context, - builder: (_) => StationDialog(controller: c), - ), - ), - const SizedBox(height: 8), - // 相位分区:可任意增删、改名、改起止角;流程图只读时置灰。 - _editEntry( - t, - icon: Icons.tune, - label: '编辑相位分区', - badge: c.project.phaseZones.length, - enabled: !flow, - onTap: () => showDialog( - context: context, - builder: (_) => PhaseZoneDialog(controller: c), - ), - ), - const SizedBox(height: 12), - _sectionLabel(t, '视图模式'), - const SizedBox(height: 8), - // 该栏永久只保留条形 / 圆周两个时序视图的切换; - // 流程图由时序图生成、属独立载体,入口在顶部工具栏(不在本栏混排)。 - Row( - children: [ - Expanded(child: _modeButton(t, '条形节拍(甘特)', c.project.viewState.mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar))), - const SizedBox(width: 8), - Expanded(child: _modeButton(t, '圆周节拍(同心)', c.project.viewState.mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular))), - ], - ), - const SizedBox(height: 12), - _sectionLabel(t, '显示选项'), - const SizedBox(height: 6), - ..._displayOptions(t, bar), - const SizedBox(height: 8), - _sectionLabel(t, '工位负载 / 相位占用'), - const SizedBox(height: 10), - ..._stationLoads(t), - const SizedBox(height: 12), - Container( - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - color: t.info, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: t.line), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), - const SizedBox(height: 6), - // 提示随视图模式切换:流程图是只读预览,给出交互方式说明。 - if (flow) ...[ - Text('流程图只读:点击节点可选中对应动作', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('滚轮缩放 · 拖拽平移 · Ctrl+滚轮连续缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('需要修改请切回条形 / 圆周视图', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - ] else ...[ - Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('双击空白新建动作 · F1 打开帮助', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - ], - ], - ), - ), - ], - ), - ), - ); + /// 当前模块状态栏。 + Widget _moduleStatusBar(Tokens t) { + final EdcModule? m = _module; + if (m == null) return const SizedBox.shrink(); + return m.buildStatusBar(_moduleUi(t)); } - /// 侧栏小节标题文本(单行,过长时省略)。 - Widget _sectionLabel(Tokens t, String s) => Text( - s, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.text2, fontSize: 11.5, letterSpacing: 1.2, fontWeight: FontWeight.w600), - ); - - /// 侧栏中的“单行编辑入口”卡片:图标 + 文案 + 可选计数徽标 + 右箭头。 - /// - /// 用于把复杂的设置模块收敛为一个点击即可进入的入口。 - /// [enabled] 为 false 时整体置灰(流程图只读视图下禁用编辑入口)。 - Widget _editEntry( - Tokens t, { - required IconData icon, - required String label, - required VoidCallback onTap, - int? badge, - bool enabled = true, - }) { - final Widget card = InkWell( - onTap: enabled ? onTap : null, - borderRadius: BorderRadius.circular(10), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: t.line), - ), - child: Row( - children: [ - Icon(icon, size: 16, color: enabled ? t.accent : t.dim), - const SizedBox(width: 8), - Expanded(child: Text(label, style: TextStyle(color: enabled ? t.text2 : t.dim, fontSize: 12))), - if (badge != null) ...[ - Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), - decoration: BoxDecoration( - color: enabled ? t.accent.withValues(alpha: 0.14) : t.line.withValues(alpha: 0.35), - borderRadius: BorderRadius.circular(6), - ), - child: Text('$badge', - style: TextStyle( - color: enabled ? t.accent : t.dim, fontSize: 10.5, fontWeight: FontWeight.w700)), - ), - const SizedBox(width: 4), - ], - Icon(Icons.chevron_right, size: 16, color: t.dim), - ], - ), - ), - ); - if (enabled) return card; - return Tooltip(message: '流程图只读:修改请切回条形 / 圆周视图', child: card); - } - - /// 左侧栏的泳道槽位小徽标:显示当前槽位数,点击可调整(1–5 槽)。 - /// - /// 槽位数 > 1 时高亮显示(多槽位泳道内动作按子行并列放置)。 - Widget _laneSlotChip(Tokens t, int lane) { - final int n = c.project.slotsOf(lane); - return Builder( - builder: (BuildContext ctx) => Tooltip( - message: '泳道 L${lane + 1} 槽位数:$n(点击调整,最多 5)', - child: InkWell( - borderRadius: BorderRadius.circular(6), - onTap: () async { - final RenderBox box = ctx.findRenderObject()! as RenderBox; - await showLaneSlotMenu(context, c, box.localToGlobal(Offset.zero), lane); - }, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: n > 1 ? t.accent.withValues(alpha: 0.14) : t.panel2, - borderRadius: BorderRadius.circular(6), - border: Border.all(color: n > 1 ? t.accent.withValues(alpha: 0.4) : t.line2), - ), - child: Text('$n 槽', - style: TextStyle(color: n > 1 ? t.accent : t.dim, fontSize: 10)), - ), - ), - ), - ); - } - - /// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。 - /// - /// [onTap] 为 null 时按钮呈禁用态(降低不透明度),用于「未选中动作时禁用删除」。 - Widget _headerAction(Tokens t, IconData icon, String label, Color bg, Color fg, VoidCallback? onTap) { - final bool enabled = onTap != null; - return Opacity( - opacity: enabled ? 1 : 0.4, - child: InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(8), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: bg, borderRadius: BorderRadius.circular(8)), - child: Row( - children: [ - Icon(icon, size: 14, color: fg), - const SizedBox(width: 4), - Text(label, style: TextStyle(color: fg, fontSize: 11, fontWeight: FontWeight.w700)), - ], - ), - ), - ), - ); - } - - /// 左侧栏:按泳道 / 轨道分组的行列表。 - List _laneRows(Tokens t, bool bar) { - final List lanes = c.project.renderLanes; - final List out = []; - for (int li = 0; li < lanes.length; li++) { - final int lane = lanes[li]; - final List acts = c.project.actions.where((Action a) => a.layer == lane).toList() - ..sort((Action a, Action b) => a.startAngle.compareTo(b.startAngle)); - // 空泳道(开启「保留空泳道」后动作被全部移走):显示占位行。 - if (acts.isEmpty) { - out.add(_emptyLaneRow(t, lane, li)); - continue; - } - // 单动作泳道沿用普通动作行;多动作泳道合并显示。 - out.add(acts.length == 1 - ? _actionRow(t, acts.first, li, bar) - : _laneRow(t, lane, li, acts, bar)); - } - return out; - } - - /// 左侧栏中的空泳道占位行(开启「保留空泳道」后,动作被全部移走的泳道)。 - Widget _emptyLaneRow(Tokens t, int lane, int li) { - return Padding( - padding: const EdgeInsets.only(bottom: 6), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(10), - border: Border.all(color: t.line), - ), - child: Row( - children: [ - Container( - width: 22, - height: 22, - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(6), - border: Border.all(color: t.line2), - ), - alignment: Alignment.center, - child: Text('${li + 1}', - style: TextStyle(color: t.dim, fontSize: 11, fontWeight: FontWeight.w700)), - ), - const SizedBox(width: 9), - Expanded( - child: Text('空泳道(已保留,可拖入动作)', - style: TextStyle(color: t.dim, fontSize: 11)), - ), - _laneSlotChip(t, lane), - ], - ), - ), - ); - } - - /// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。 - Widget _laneRow(Tokens t, int lane, int li, List acts, bool bar) { - if (acts.isEmpty) return const SizedBox.shrink(); - final bool flow = c.project.viewState.mode == ViewMode.flow; - final Action primary = - acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first); - final bool sel = c.isSelected(primary.id); - final Station? st = c.project.stationById(primary.stationId); - final String joined = acts.map((Action a) => '${a.id} ${a.name}').join(' / '); - double a0 = acts.first.startAngle; - double a1 = acts.first.endAngle; - for (final Action a in acts) { - a0 = math.min(a0, a.startAngle); - a1 = math.max(a1, a.endAngle); - } - return Padding( - padding: const EdgeInsets.only(bottom: 6), - child: InkWell( - onTap: () => c.select( - primary.id, - toggle: HardwareKeyboard.instance.isControlPressed || - HardwareKeyboard.instance.isShiftPressed, - ), - // 双击泳道行直接编辑该泳道的主动作(流程图只读时禁用)。 - onDoubleTap: flow - ? null - : () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), - borderRadius: BorderRadius.circular(10), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), - decoration: BoxDecoration( - color: sel ? t.sel : t.panel2, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), - ), - child: Row( - children: [ - Container( - width: 22, - height: 22, - decoration: BoxDecoration( - color: Color(primary.color).withValues(alpha: 0.9), - borderRadius: BorderRadius.circular(6), - ), - alignment: Alignment.center, - child: Text('${li + 1}', style: TextStyle(color: t.chip, fontSize: 11, fontWeight: FontWeight.w700)), - ), - const SizedBox(width: 9), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - joined, - // 多槽位泳道允许更多行(最多与槽位数一致),持续自动换行。 - maxLines: math.max(2, c.project.slotsOf(lane)), - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: sel ? t.text : t.text2, - fontSize: 12.5, - height: 1.25, - fontWeight: sel ? FontWeight.w600 : FontWeight.normal, - ), - ), - Text( - '${st?.name ?? primary.stationId} · ${primary.driver}' - '${acts.length > 1 ? ' · 共 ${acts.length} 个' : ''}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.dim, fontSize: 10), - ), - ], - ), - ), - const SizedBox(width: 6), - Flexible( - child: Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text( - bar ? '${a0.toStringAsFixed(0)}° – ${math.min(a1, 360).toStringAsFixed(0)}°' : 'L${li + 1}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.sub, fontSize: 11), - ), - Text('${acts.length} 个动作', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ), - const SizedBox(width: 6), - _laneSlotChip(t, lane), - const SizedBox(width: 4), - InkWell( - onTap: flow - ? null - : () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), - borderRadius: BorderRadius.circular(7), - child: Container( - width: 28, - height: 24, - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.line2), - ), - child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), - ), - ), - ], - ), - ), - ), - ); - } - - /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 - Widget _actionRow(Tokens t, Action a, int i, bool bar) { - final bool flow = c.project.viewState.mode == ViewMode.flow; - final bool sel = c.isSelected(a.id); - final Station? st = c.project.stationById(a.stationId); - return Padding( - padding: const EdgeInsets.only(bottom: 6), - child: InkWell( - // Ctrl / Shift 点击可多选,用于批量对齐等操作。 - onTap: () => c.select( - a.id, - toggle: HardwareKeyboard.instance.isControlPressed || - HardwareKeyboard.instance.isShiftPressed, - ), - // 双击动作行直接进入编辑(流程图只读时禁用)。 - onDoubleTap: flow - ? null - : () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), - borderRadius: BorderRadius.circular(10), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), - decoration: BoxDecoration( - color: sel ? t.sel : t.panel2, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: sel ? t.accent : t.line, width: sel ? 1.4 : 1), - ), - child: Row( - children: [ - Container( - width: 22, - height: 22, - decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(6)), - alignment: Alignment.center, - child: Text('${i + 1}', style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), - ), - const SizedBox(width: 9), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(a.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: sel ? t.text : t.text2, fontSize: 12, fontWeight: sel ? FontWeight.w600 : FontWeight.normal)), - Text( - '${a.id} · ${st?.name ?? a.stationId} · ${a.driver}' - '${c.project.slotsOf(a.layer) > 1 ? ' · 槽 ${effectiveSlot(c.project, a) + 1}' : ''}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ), - const SizedBox(width: 6), - Flexible( - child: Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text( - bar - ? '${a.startAngle.toStringAsFixed(0)}° – ${math.min(a.endAngle, 360).toStringAsFixed(0)}°' - : 'L${a.layer + 1}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.sub, fontSize: 10), - ), - Text(tfmt(a.durationAngle / 360 * c.project.cycle.durationMs, c.project.units), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ), - const SizedBox(width: 6), - _laneSlotChip(t, a.layer), - const SizedBox(width: 4), - InkWell( - onTap: flow - ? null - : () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), - borderRadius: BorderRadius.circular(7), - child: Container( - width: 28, - height: 24, - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.line2), - ), - child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), - ), - ), - // 选中该动作时才出现删除入口;至少保留一个动作 / 泳道;流程图只读时隐藏。 - if (sel && !flow && c.project.actions.length > 1) ...[ - const SizedBox(width: 4), - InkWell( - onTap: () => c.deleteAction(a.id), - borderRadius: BorderRadius.circular(7), - child: Container( - width: 28, - height: 24, - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.danger.withValues(alpha: 0.6)), - ), - child: Icon(Icons.delete_outline, size: 13, color: t.danger), - ), - ), - ], - ], - ), - ), - ), - ); - } - - /// 视图模式选择按钮(条形 / 圆周)。 - Widget _modeButton(Tokens t, String label, bool active, VoidCallback onTap) { - return InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(10), - child: Container( - height: 44, - alignment: Alignment.center, - decoration: BoxDecoration( - color: active ? t.accent.withValues(alpha: 0.16) : t.panel2, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: active ? t.accent : t.line, width: 1.2), - ), - child: Text(label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: active ? t.accent : t.sub, fontSize: 11)), - ), - ); - } - - /// 显示选项复选列表:根据视图模式返回不同的开关项。 - List _displayOptions(Tokens t, bool bar) { - final ViewState v = c.project.viewState; - final List> opts = bar - ? >[ - ['时间轴 / 相位双刻度', v.showRuler, (bool x) => c.setViewFlag(showRuler: x)], - ['依赖箭头 FS / SS', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], - ['跨循环片段标记', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], - ['相位分区标注', v.showPhaseBands, (bool x) => c.setViewFlag(showPhaseBands: x)], - ] - : >[ - ['同心圆环背景', v.showRingBg, (bool x) => c.setViewFlag(showRingBg: x)], - ['顺序箭头(FS / SS)', v.showDeps, (bool x) => c.setViewFlag(showDeps: x)], - ['层半径标注', v.showLayerLabels, (bool x) => c.setViewFlag(showLayerLabels: x)], - ['跨循环高亮', c.project.units.autoSplitWrap, (bool x) => c.setUnits(c.project.units.copyWith(autoSplitWrap: x))], - ]; - return opts.map((List o) { - final bool on = o[1] as bool; - return InkWell( - onTap: () => (o[2] as void Function(bool))(!on), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 4), - child: Row( - children: [ - Container( - width: 16, - height: 16, - decoration: BoxDecoration( - color: on ? t.accent.withValues(alpha: 0.22) : Colors.transparent, - borderRadius: BorderRadius.circular(4), - border: Border.all(color: on ? t.accent : t.line2), - ), - child: on ? Icon(Icons.check, size: 12, color: t.accent) : null, - ), - const SizedBox(width: 10), - Text(o[0] as String, style: TextStyle(color: t.sub, fontSize: 11)), - ], - ), - ), - ); - }).toList(); - } - - /// 各工位的相位占用统计:汇总持续角并渲染为进度条。 - List _stationLoads(Tokens t) { - final Map load = {}; - for (final Action a in c.project.actions) { - load[a.stationId] = (load[a.stationId] ?? 0) + a.durationAngle; - } - final List out = []; - for (final Station s in c.project.stations) { - final double deg = load[s.id] ?? 0; - out.add(Padding( - padding: const EdgeInsets.only(bottom: 10), - child: Column( - children: [ - Row( - children: [ - Expanded( - child: Text('${s.id} ${s.name}', - maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.sub, fontSize: 11)), - ), - Text('${deg.toStringAsFixed(0)}° · ${(deg / 3.6).toStringAsFixed(1)}%', - style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), - ], - ), - const SizedBox(height: 5), - ClipRRect( - borderRadius: BorderRadius.circular(4), - child: LinearProgressIndicator( - value: (deg / 360).clamp(0, 1), - minHeight: 8, - backgroundColor: t.track, - valueColor: AlwaysStoppedAnimation(t.accent), - ), - ), - ], - ), - )); - } - return out; - } - - /// 统计项目中所有动作的依赖总数。 - int _depCount() { - int n = 0; - for (final Action a in c.project.actions) { - n += a.deps.length; - } - return n; - } - - // ===================== 右侧栏内容 ===================== - - /// 构建右侧栏:选中动作的属性、角度编辑、工艺单位、编辑操作、 - /// 依赖关系与导出入口。[floating] 为 true 时以悬浮卡片样式呈现。 - Widget _rightPanel(Tokens t, {bool floating = false}) { - // 架构图模块使用独立的右侧栏(选中对象属性)。 - if (c.appMode == AppMode.architecture) { - return _archRightPanel(t, floating: floating); - } - final Action? a = c.selected; - final bool bar = c.project.viewState.mode == ViewMode.bar; - final bool flow = c.project.viewState.mode == ViewMode.flow; - return Container( - width: _rightPanelWidth, - decoration: BoxDecoration( - color: t.panel, - border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), - boxShadow: floating - ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] - : null, - ), - child: Column( - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), - child: Row( - children: [ - _sectionLabel(t, '属性 · 选中动作'), - const Spacer(), - _panelControls(t, false), - ], - ), - ), - Expanded( - child: a == null - ? Center( - child: Text('未选中动作\n点击画布或左侧列表选择', - textAlign: TextAlign.center, style: TextStyle(color: t.dim, fontSize: 11, height: 1.6)), - ) - : SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _selectedHeader(t, a, bar), - const SizedBox(height: 14), - // 流程图只读提示:节点与连线自动生成,编辑请回时序视图。 - if (flow) ...[ - Container( - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - color: t.info, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: t.line), - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Icon(Icons.lock_outline, size: 15, color: t.warn), - const SizedBox(width: 8), - Expanded( - child: Text('流程图只读:节点与连线由时序图自动生成,修改请切回条形 / 圆周视图。', - style: TextStyle(color: t.sub, fontSize: 10.5, height: 1.55)), - ), - ], - ), - ), - const SizedBox(height: 12), - ], - ..._propertyFields(t, a, bar), - const SizedBox(height: 10), - if (!bar) ...[ - _sectionLabel(t, '角度编辑'), - const SizedBox(height: 8), - // 流程图只读:滑块仅展示数值,不可拖动。 - Opacity( - opacity: flow ? 0.45 : 1, - child: IgnorePointer( - ignoring: flow, - child: Column( - children: [ - _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), - (double v) => c.setActionStart(a.id, v * 360)), - _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), - (double v) => c.setActionDuration(a.id, v * 180)), - ], - ), - ), - ), - const SizedBox(height: 8), - ], - const SizedBox(height: 12), - // 输入依赖:允许多条(多前置)。 - _sectionLabel(t, '前置依赖 · 输入(${a.deps.length})'), - const SizedBox(height: 8), - if (a.deps.isEmpty) - Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11)) - else - for (final Dependency d in a.deps) _depRow(t, a, d, enabled: !flow), - const SizedBox(height: 6), - OutlinedButton.icon( - onPressed: flow - ? null - : () => showDialog( - context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), - icon: const Icon(Icons.add_link, size: 15), - label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)), - style: OutlinedButton.styleFrom( - foregroundColor: t.accent, - side: BorderSide(color: t.line2), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: const EdgeInsets.symmetric(vertical: 10), - minimumSize: const Size(double.infinity, 0), - ), - ), - const SizedBox(height: 12), - // 输出依赖:本动作作为前置指向的后续动作(允许多结果)。 - _sectionLabel(t, '输出依赖 · 结果(${_outgoingDeps(a).length})'), - const SizedBox(height: 8), - if (_outgoingDeps(a).isEmpty) - Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11)) - else - for (final (Action target, Dependency d) in _outgoingDeps(a)) - _outDepRow(t, a, target, d, enabled: !flow), - const SizedBox(height: 12), - _helpCard(t), - ], - ), - ), - ), - ], - ), - ); - } - - /// 选中动作的头部信息卡:编号、名称、工位/驱动与跨圈标记。 - Widget _selectedHeader(Tokens t, Action a, bool bar) { - final Station? st = c.project.stationById(a.stationId); - return Container( - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(12), - border: Border.all(color: t.line), - ), - child: Row( - children: [ - Container( - width: 34, - height: 34, - decoration: BoxDecoration(color: Color(a.color).withValues(alpha: 0.9), borderRadius: BorderRadius.circular(8)), - alignment: Alignment.center, - child: Text(a.id, style: TextStyle(color: t.chip, fontSize: 10, fontWeight: FontWeight.w700)), - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(a.name, maxLines: 1, overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.text, fontSize: 14, fontWeight: FontWeight.w600)), - Text('${st?.id ?? a.stationId} · ${a.driver} · 层 L${a.layer + 1}', - maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ), - Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), - decoration: BoxDecoration( - color: (a.wrap ? t.warn : t.accent).withValues(alpha: 0.14), - borderRadius: BorderRadius.circular(8), - border: Border.all(color: a.wrap ? t.warn : t.accent), - ), - child: Text(a.wrap ? '跨圈' : '选中', - style: TextStyle(color: a.wrap ? t.warn : t.accent, fontSize: 11)), - ), - ], - ), - ); - } - - /// 构建属性键值列表:条形视图按时间维度,圆周视图按相位维度。 - List _propertyFields(Tokens t, Action a, bool bar) { - final UnitSettings u = c.project.units; - final double cycle = c.project.cycle.durationMs; - final List> fields; - if (bar) { - fields = >[ - ['开始时刻', tfmt(a.startAngle / 360 * cycle, u), pfmt(a.startAngle, u)], - ['结束时刻', tfmt(a.endAngle / 360 * cycle, u), a.wrap ? '${a.endAngle.toStringAsFixed(1)}° → ${(a.endAngle - 360).toStringAsFixed(1)}°' : pfmt(a.endAngle, u)], - ['持续时间', tfmt(a.durationAngle / 360 * cycle, u), pfmt(a.durationAngle, u)], - ['循环归属', a.wrap ? '当前圈 + 下一圈' : '当前圈', a.wrap ? '跨圈片段' : '单圈内'], - ['顺序约束', _depSummary(a), '前序动作关系'], - ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], - ]; - } else { - fields = >[ - ['起始相位', pfmt(a.startAngle, u), '${tfmt(a.startAngle / 360 * cycle, u)} · 12 点钟起顺时针'], - ['结束相位', pfmt(a.endAngle, u), tfmt(a.endAngle / 360 * cycle, u)], - ['持续相位', pfmt(a.durationAngle, u), '${tfmt(a.durationAngle / 360 * cycle, u)} · 占循环 ${(a.durationAngle / 3.6).toStringAsFixed(2)}%'], - ['所在层', 'L${a.layer + 1}', '层内序号 ${a.layer + 1}'], - ['顺序约束', _depSummary(a), '前序动作关系'], - ['相位归属', _phaseZone(a), '${a.startAngle.toStringAsFixed(0)}°–${math.min(a.endAngle, 360).toStringAsFixed(0)}°'], - ]; - } - final List out = []; - for (int i = 0; i < fields.length; i++) { - out.add(Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), - decoration: BoxDecoration( - color: i.isEven ? t.panel2.withValues(alpha: 0.7) : Colors.transparent, - borderRadius: BorderRadius.circular(8), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text(fields[i][0], style: TextStyle(color: t.sub, fontSize: 11)), - const Spacer(), - Flexible( - child: Text(fields[i][1], - textAlign: TextAlign.right, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: t.text, fontSize: 12, fontWeight: FontWeight.w600)), - ), - ], - ), - if (fields[i][2].isNotEmpty) - Align( - alignment: Alignment.centerRight, - child: Text(fields[i][2], style: TextStyle(color: t.dim, fontSize: 10)), - ), - ], - ), - )); - } - return out; - } - - /// 生成依赖摘要文本。 - /// - /// 一个动作可以有多条输入依赖(多输入)与多条输出依赖(多结果), - /// 因此这里按类型汇总条数,而不是只取一条。 - String _depSummary(Action a) { - if (a.deps.isEmpty) return '无输入'; - int fs = 0; - int ss = 0; - int other = 0; - for (final Dependency d in a.deps) { - if (d.type == DepType.fs) { - fs++; - } else if (d.type == DepType.ss) { - ss++; - } else { - other++; - } - } - final List parts = []; - if (fs > 0) parts.add('FS ×$fs'); - if (ss > 0) parts.add('SS ×$ss'); - if (other > 0) parts.add('其它 ×$other'); - return '${a.deps.length} 条(${parts.join(' · ')})'; - } - - /// 收集以 [a] 为起点的输出依赖(即 a 是前置、指向其它动作)。 - /// - /// 返回 `(目标动作, 依赖)` 列表;一个动作可以输出多个结果。 - List<(Action, Dependency)> _outgoingDeps(Action a) { - final List<(Action, Dependency)> out = <(Action, Dependency)>[]; - for (final Action target in c.project.actions) { - for (final Dependency d in target.deps) { - if (d.fromId == a.id) out.add((target, d)); - } - } - return out; - } - - /// 根据动作中点相位归类到用户定义的相位分区;未命中时返回「—」。 - String _phaseZone(Action a) { - final double mid = (a.startAngle + a.endAngle) / 2 % 360; - for (final PhaseZone z in c.project.phaseZones) { - if (z.contains(mid)) return z.name; - } - return '—'; - } - - /// 带标签与数值显示的滑块(用于起始角 / 持续角编辑)。 - Widget _slider(Tokens t, String label, double value, String display, ValueChanged onChanged) { - return Padding( - padding: const EdgeInsets.only(bottom: 6), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text(label, style: TextStyle(color: t.sub, fontSize: 11)), - const Spacer(), - Text(display, style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), - ], - ), - SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 4, - thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 7), - overlayShape: const RoundSliderOverlayShape(overlayRadius: 14), - ), - child: Slider(value: value, onChanged: onChanged), - ), - ], - ), - ); - } - - /// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。 - /// - /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 - Widget _depRow(Tokens t, Action a, Dependency d, {bool enabled = true}) { - final Color col = d.type == DepType.fs ? t.fs : t.ss; - return Container( - margin: const EdgeInsets.only(bottom: 5), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.line), - ), - child: Row( - children: [ - Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), - const SizedBox(width: 8), - Expanded( - child: Text( - '${d.fromId} → ${a.id} ${d.type.name.toUpperCase()}${d.type == DepType.ss ? ' +${d.offsetAngle.toStringAsFixed(0)}°' : ''}', - style: TextStyle(color: t.sub, fontSize: 10), - ), - ), - InkWell( - onTap: enabled ? () => c.removeDependency(d.fromId, a.id) : null, - child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), - ), - ], - ), - ); - } - - /// 输出依赖展示行:本动作 [a] 作为前置指向 [target],可删除。 - /// - /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 - Widget _outDepRow(Tokens t, Action a, Action target, Dependency d, {bool enabled = true}) { - final Color col = d.type == DepType.fs ? t.fs : t.ss; - return Container( - margin: const EdgeInsets.only(bottom: 5), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(7), - border: Border.all(color: t.line), - ), - child: Row( - children: [ - Container(width: 8, height: 8, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), - const SizedBox(width: 8), - Expanded( - child: Text( - '${a.id} → ${target.id} ${d.type.name.toUpperCase()}${d.type == DepType.ss ? ' +${d.offsetAngle.toStringAsFixed(0)}°' : ''}', - style: TextStyle(color: t.sub, fontSize: 10), - ), - ), - InkWell( - onTap: enabled ? () => c.removeDependency(a.id, target.id) : null, - child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), - ), - ], - ), - ); - } - - /// 右侧栏底部的帮助与快捷键提示卡片。 - Widget _helpCard(Tokens t) { - return Container( - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - color: t.panel2, - borderRadius: BorderRadius.circular(10), - border: Border.all(color: t.line), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon(Icons.help_outline, size: 16, color: t.accent), - const SizedBox(width: 6), - Text('帮助 · 快捷键', style: TextStyle(color: t.accent, fontSize: 11, fontWeight: FontWeight.w600)), - ], - ), - const SizedBox(height: 8), - Text('拖拽 = 平移相位 · 拖端点 = 改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('Shift+拖 = 改层 · F1 = 帮助中心', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('Ctrl+Z / Ctrl+Y = 撤销 / 重做', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - ], - ), - ); - } - - // ===================== 状态栏 ===================== - - /// 底部状态栏:横向滚动展示循环周期、动作/依赖数、单位换算与 - /// 当前状态消息,右侧提示未保存状态与常用快捷键。 - Widget _statusBar(Tokens t) { - // 架构图模式:状态栏展示架构图统计与工具。 - if (c.appMode == AppMode.architecture) return _archStatusBar(t); - final UnitSettings u = c.project.units; - final ViewMode mode = c.project.viewState.mode; - final bool circular = mode == ViewMode.circular; - final List items = [ - '循环周期 ${tfmt(c.project.cycle.durationMs, u)}', - '相位 360° = 100%', - '动作 ${c.project.actions.length}', - '依赖 ${_depCount()}', - circular ? '轨道 L1–L${c.project.renderLaneCount}' : '工位 ${c.project.stations.length}', - mode == ViewMode.flow - ? '泳道 L1–L${c.project.renderLaneCount}(流程节点 ${c.project.actions.length})' - : (circular ? '同心圆 ${c.project.laneCount}' : '时间轴 0–${tfmt(c.project.cycle.durationMs, u)}'), - '单位 ${timeUnitLabel(u.timeUnit)} / ${phaseUnitLabel(u.phaseUnit)}', - '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}', - c.status, - ]; - return Container( - height: 32, - padding: const EdgeInsets.symmetric(horizontal: 16), - decoration: BoxDecoration( - color: t.chrome, - border: Border(top: BorderSide(color: t.line2)), - ), - child: Row( - children: [ - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: items.map((String s) { - final bool last = s == items.last; - return Padding( - padding: const EdgeInsets.only(right: 22), - child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)), - ); - }).toList(), - ), - ), - ), - if (c.dirty) - Padding( - padding: const EdgeInsets.only(right: 14), - child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)), - ), - Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ); - } - - /// 架构图状态栏:元素统计 / 当前工具 / 缩放 / 状态消息。 - Widget _archStatusBar(Tokens t) { - final ArchDoc doc = c.arch; - final String toolLabel = c.sketchMode - ? '草图·${sketchToolLabel(c.sketchTool)}' - : switch (c.archTool) { - ArchTool.select => '选择', - ArchTool.pen => c.archAutoRecognize ? '手绘识别' : '手绘(待确认)', - ArchTool.connect => '连线', - ArchTool.eraser => '橡皮', - }; - final List items = [ - c.sketchMode ? '参数化草图' : '架构图模式', - if (c.sketchMode) ...[ - '实体 ${doc.sketch.entities.length}', - '约束 ${doc.sketch.constraints.where((SketchConstraint k) => !k.internal).length}', - '尺寸 ${doc.sketch.dims.length}', - '自由度 ${sketchDofCount(doc.sketch)}', - ] else ...[ - '元件 ${doc.shapes.length}', - '连线 ${doc.connectors.length}', - '墨迹 ${doc.strokes.length}', - '图层 ${doc.layerById(doc.activeLayer).name}', - ], - '工具 $toolLabel', - if (!c.sketchMode && c.archOrtho) '正交 开', - if (!c.sketchMode && c.archPolar) '极轴 ${c.archPolarDeg.round()}°', - '缩放 ${(doc.zoom * 100).round()}%', - c.status, - ]; - return Container( - height: 32, - padding: const EdgeInsets.symmetric(horizontal: 16), - decoration: BoxDecoration( - color: t.chrome, - border: Border(top: BorderSide(color: t.line2)), - ), - child: Row( - children: [ - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: items.map((String s) { - final bool last = s == items.last; - return Padding( - padding: const EdgeInsets.only(right: 22), - child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)), - ); - }).toList(), - ), - ), - ), - if (c.dirty) - Padding( - padding: const EdgeInsets.only(right: 14), - child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)), - ), - Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)), - ], - ), - ); - } } diff --git a/lib/ui/brand_menu.dart b/lib/ui/brand_menu.dart index 46dc00b..df1e197 100644 --- a/lib/ui/brand_menu.dart +++ b/lib/ui/brand_menu.dart @@ -1,4 +1,4 @@ -/// 左上角品牌按钮 +「EDC易得」设计合集菜单。 +/// 左上角品牌按钮 +「PDS流程设计套件」品牌菜单。 /// /// 点开左上角 logo:菜单从 logo **下方**下拉展开(不遮挡 logo)。 /// 菜单由模块注册表驱动:首页入口 + 已开放模块(可进入/新建)+ @@ -11,11 +11,10 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; -import '../model/models.dart'; -import '../modules/module_registry.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import '../version.dart'; +import 'package:sequence_diagram/modules/registry.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/version.dart'; import 'app_logo.dart'; /// 品牌按钮:logo + 当前模块名,点击在下方弹出合集菜单。 @@ -41,10 +40,10 @@ class BrandMenuButton extends StatelessWidget { /// 紧凑布局(隐藏副标题)。 final bool compact; - /// 当前模块名(首页显示「设计合集」)。 + /// 当前模块名(首页显示「流程设计套件」)。 String get _label { - final EdcModule? m = moduleOf(controller.appMode); - return m == null ? '设计合集' : '${m.name}设计'; + final EdcModule? m = moduleById(controller.activeModuleId); + return m == null ? '流程设计套件' : '${m.name}设计'; } /// 构建按钮。 @@ -56,7 +55,7 @@ class BrandMenuButton extends StatelessWidget { final Tokens t = context.tok; final BorderRadius radius = BorderRadius.circular(10); return Tooltip( - message: 'EDC易得:设计合集', + message: 'PDS流程设计套件', child: Material( color: t.panel, borderRadius: radius, @@ -94,7 +93,7 @@ class BrandMenuButton extends StatelessWidget { ), if (!compact) Text( - 'Easy Design Collection', + 'Process Design Suite', style: TextStyle( color: t.dim, fontSize: 9.5 * scale, @@ -211,8 +210,8 @@ class BrandMenuButton extends StatelessWidget { /// 菜单面板(品牌头部 + 首页 + 模块注册表 + 未开放模块 + 软件设置)。 Widget _panel(BuildContext context) { final Tokens t = context.tok; - final bool atHome = controller.appMode == AppMode.home; - final String? curId = moduleOf(controller.appMode)?.id; + final bool atHome = controller.isHome; + final String? curId = moduleById(controller.activeModuleId)?.id; final double maxH = math.max( 180, MediaQuery.sizeOf(context).height - 120, @@ -238,13 +237,17 @@ class BrandMenuButton extends StatelessWidget { padding: const EdgeInsets.fromLTRB(12, 6, 12, 8), child: Row( children: [ - Text('EDC易得', - style: TextStyle( - color: t.text, - fontSize: 12.5, - fontWeight: FontWeight.w700, - )), - const Spacer(), + Expanded( + child: Text('PDS流程设计套件', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: FontWeight.w700, + )), + ), + const SizedBox(width: 6), Text('v$kAppVersion', style: TextStyle(color: t.dim, fontSize: 10)), ], @@ -257,7 +260,7 @@ class BrandMenuButton extends StatelessWidget { const SizedBox(height: 6), Divider(height: 1, thickness: 1, color: t.line), const SizedBox(height: 4), - // 已开放模块(可通过「设计合集」进入并新建文档)。 + // 已开放模块(可通过「品牌菜单」进入并新建文档)。 for (final EdcModule m in kModules) if (m.available) _item(context, m, current: curId == m.id), const SizedBox(height: 6), diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index d8da54a..9b97a7c 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -11,16 +11,16 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; -import '../license/license_service.dart'; -import '../model/models.dart'; -import '../model/units.dart'; -import '../modules/module_registry.dart'; -import '../persistence/android_docs.dart'; -import '../persistence/storage.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import '../update/update_service.dart'; -import '../version.dart'; +import 'package:sequence_diagram/license/license_service.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; +import 'package:sequence_diagram/modules/registry.dart'; +import 'package:sequence_diagram/persistence/android_docs.dart'; +import 'package:sequence_diagram/persistence/storage.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/update/update_service.dart'; +import 'package:sequence_diagram/version.dart'; import 'app_logo.dart'; import 'update_dialog.dart'; @@ -970,38 +970,70 @@ class _ActionEditorDialogState extends State { // ===================== 依赖编辑对话框 ===================== -/// 依赖编辑对话框:为指定动作添加一条前置依赖。 +/// 依赖编辑对话框:为指定动作添加或修改一条前置依赖。 class DependencyEditorDialog extends StatefulWidget { - const DependencyEditorDialog({super.key, required this.controller, required this.action}); + const DependencyEditorDialog({ + super.key, + required this.controller, + required this.action, + this.initial, + }); /// 全局应用控制器。 final AppController controller; /// 目标动作(依赖的“后置”端)。 final Action action; + /// 要编辑的已有依赖;为 null 时是新增模式。 + final Dependency? initial; /// 创建依赖编辑对话框对应的状态对象。 @override State createState() => _DependencyEditorDialogState(); } -/// 依赖编辑对话框状态:维护前置动作、依赖类型与偏移角。 +/// 依赖编辑对话框状态:维护前置动作、依赖类型与偏移时间。 class _DependencyEditorDialogState extends State { /// 选择的前置动作 id。 String? _from; /// 依赖类型,默认 FS(完成-启动)。 DepType _type = DepType.fs; - /// 偏移角输入控制器。 - final TextEditingController _offset = TextEditingController(text: '0'); + /// 偏移时间输入控制器(按当前时间单位输入,内部换算为角度)。 + late final TextEditingController _offset; - /// 渲染依赖表单:前置动作、依赖类型与偏移角。 + bool get _editing => widget.initial != null; + + @override + void initState() { + super.initState(); + final Dependency? d = widget.initial; + _from = d?.fromId; + _type = d?.type ?? DepType.fs; + final UnitSettings u = widget.controller.project.units; + final double cycleMs = widget.controller.project.cycle.durationMs; + final double offsetMs = cycleMs <= 0 ? 0 : (d?.offsetAngle ?? 0) / 360 * cycleMs; + _offset = TextEditingController( + text: offsetMs == 0 ? '0' : timeValue(offsetMs, u.timeUnit).toStringAsFixed(3), + ); + } + + @override + void dispose() { + _offset.dispose(); + super.dispose(); + } + + /// 渲染依赖表单:前置动作、依赖类型与偏移时间。 @override Widget build(BuildContext context) { final Tokens t = context.tok; + final UnitSettings u = widget.controller.project.units; 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} 添加前置依赖'), + title: Text(_editing + ? '编辑依赖 ${widget.initial!.fromId} → ${widget.action.id}' + : '为 ${widget.action.id} 添加前置依赖'), content: SizedBox( width: 420, child: Column( @@ -1030,8 +1062,11 @@ class _DependencyEditorDialogState extends State { const SizedBox(height: 8), TextField( controller: _offset, - keyboardType: TextInputType.number, - decoration: const InputDecoration(labelText: '偏移角 offset (°)'), + keyboardType: TextInputType.text, + decoration: InputDecoration( + labelText: '偏移时间 offset (${timeUnitLabel(u.timeUnit)})', + helperText: '以时间为主:可直接输入 120ms / 0.5s / 1min;内部自动换算', + ), ), ], ), @@ -1042,15 +1077,32 @@ class _DependencyEditorDialogState extends State { onPressed: () { // 未选择前置动作时不提交。 if (_from == null) return; - widget.controller.addDependency( - _from!, - widget.action.id, - _type, - double.tryParse(_offset.text) ?? 0, - ); + final UnitSettings unit = widget.controller.project.units; + final double cycleMs = widget.controller.project.cycle.durationMs; + final double? offsetMs = parseDuration(_offset.text, unit); + final double offset = (offsetMs == null || cycleMs <= 0) + ? 0 + : offsetMs / cycleMs * 360; + final Dependency? old = widget.initial; + if (old == null) { + widget.controller.addDependency( + _from!, + widget.action.id, + _type, + offset, + ); + } else { + widget.controller.updateDependency( + old.fromId, + widget.action.id, + fromId: _from!, + type: _type, + offset: offset, + ); + } Navigator.pop(context); }, - child: const Text('添加'), + child: Text(_editing ? '保存' : '添加'), ), ], ); @@ -2049,7 +2101,7 @@ class _StationRowState extends State<_StationRow> { /// 双视图说明以及单位与导出等信息。 /// 软件设置:集中设置入口(外观 / 文档默认 / 架构图网格 / 更新)。 /// -/// 从左上角「EDC易得」菜单底部的「软件设置」打开;文档级的完整设置 +/// 从左上角「PDS流程设计套件」菜单底部的「软件设置」打开;文档级的完整设置 /// (单位 / 循环 / 相位等)仍在「文档设置」(F2 / 左侧栏)里。 class SoftwareSettingsDialog extends StatefulWidget { /// 构造软件设置对话框。 @@ -2621,7 +2673,7 @@ class _HelpDialogState extends State { ['我要调相位 / 时长', '拖动动作块平移相位;拖条形右端改持续角;圆周视图拖弧两端改起止角;右侧滑杆可精调。'], ['泳道加宽(并列动作)', '双击条形视图左侧泳道编号(或点左侧栏「N 槽」徽标)→ 选 1–5 槽;拖拽动作可同时换道 + 换槽位。'], ['空泳道的保留 / 移除', 'F2 文档设置 →「泳道」→ 保留空泳道(默认开):动作全部移走的泳道保留,序号不变;关闭则自动移除。'], - ['我要加前置依赖(输入)', '右侧「前置依赖 · 输入」→「添加前置依赖」;或右键动作 →「添加依赖」。FS 绿色实线=完成后启动;SS 琥珀虚线=可提前启动(带 +n°)。'], + ['我要加前置依赖(输入)', '右侧「前置依赖 · 输入」→「添加前置依赖」;或右键动作 →「添加依赖」。FS 绿色实线=完成后启动;SS 琥珀虚线=可提前启动(带偏移时间,如 +0.33s)。'], ['连线重叠怎么办', '点选连线后拖动可沿法线方向平移整条线(圆周沿半径方向);双击连线或右键「复位走线偏移」恢复;同一组连线会自动错开。'], ['我要编辑相位分区', '左侧「文档设置」→「编辑相位分区」;增删分区、改名称与起止角;可重叠、可留空、>360° 表示跨圈。'], ]), @@ -2743,7 +2795,7 @@ class _HelpDialogState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('EDC易得 · Easy Design Collection', + Text('PDS流程设计套件 · Process Design Suite', style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), const SizedBox(height: 4), Text('V$kAppVersion(${android ? '安卓版' : 'Windows 版'})', @@ -2763,8 +2815,8 @@ class _HelpDialogState extends State { if (!android) // 注意:绝不能展示「期望授权串」——它等同于 .lic 内容,公开即可被绕过授权。 row('本机 MAC', info.mac ?? '读取失败'), - row('版权声明', 'Copyright © 2026 EDC(Easy Design Collection)呆头鹅。保留所有权利。'), - row('产品简介', '设计合集(Easy Design Collection):时序图设计面向 PLC 流程节拍 / ' + row('版权声明', 'Copyright © 2026 PDS流程设计套件(Process Design Suite)呆头鹅。保留所有权利。'), + row('产品简介', '流程设计套件(Process Design Suite):时序图设计面向 PLC 流程节拍 / ' '相位角设计(条形 / 圆周 / 流程图三视图、FS / SS 依赖与关键路径、泳道加宽);' '架构图设计支持手绘识别标准图形、正交连线与标签;支持导出 SVG / PNG / drawio。'), const SizedBox(height: 6), diff --git a/lib/ui/home_view.dart b/lib/ui/home_view.dart index 80deb1e..1df6396 100644 --- a/lib/ui/home_view.dart +++ b/lib/ui/home_view.dart @@ -6,11 +6,11 @@ library; import 'package:flutter/material.dart'; -import '../modules/module_registry.dart'; -import '../persistence/recent_store.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import '../version.dart'; +import 'package:sequence_diagram/modules/registry.dart'; +import 'package:sequence_diagram/persistence/recent_store.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/version.dart'; import 'app_logo.dart'; import 'update_icon.dart'; @@ -195,7 +195,7 @@ class _HomeViewState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - 'EDC易得', + 'PDS流程设计套件', style: TextStyle( color: t.text, fontSize: 24, @@ -204,7 +204,7 @@ class _HomeViewState extends State { ), ), Text( - '工程总体设计合集(Easy Design Collection) v$kAppVersion', + 'Process Design Suite v$kAppVersion', style: TextStyle(color: t.dim, fontSize: 11.5), ), ], diff --git a/lib/ui/update_dialog.dart b/lib/ui/update_dialog.dart index c77aef6..fcb181e 100644 --- a/lib/ui/update_dialog.dart +++ b/lib/ui/update_dialog.dart @@ -12,11 +12,11 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../state/app_controller.dart'; -import '../theme/tokens.dart'; -import '../update/keep_awake.dart'; -import '../update/update_service.dart'; -import '../version.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/update/keep_awake.dart'; +import 'package:sequence_diagram/update/update_service.dart'; +import 'package:sequence_diagram/version.dart'; import 'dialogs.dart'; import 'update_icon.dart'; @@ -124,31 +124,54 @@ class _UpdateDialogState extends State { if (r.exitCode != 0) throw Exception('解压失败:${r.stderr}'); // 兼容两种打包方式:zip 根目录即程序文件,或多包一层 dist/。 - String srcDir = extractDir; - if (!File('$extractDir\\EasyDesignCollection.exe').existsSync()) { - if (File('$extractDir\\dist\\EasyDesignCollection.exe').existsSync()) { - srcDir = '$extractDir\\dist'; - } else { - throw Exception('更新包内容不完整(未找到 EasyDesignCollection.exe)'); + // 同时识别新版 ProcessDesignSuite.exe 与旧版 EasyDesignCollection.exe。 + const List exeNames = [ + 'ProcessDesignSuite.exe', + 'EasyDesignCollection.exe', + ]; + String? srcDir; + String? exeName; + for (final String base in [extractDir, '$extractDir\\dist']) { + for (final String name in exeNames) { + if (File('$base\\$name').existsSync()) { + srcDir = base; + exeName = name; + break; + } } + if (srcDir != null) break; + } + if (srcDir == null || exeName == null) { + throw Exception('更新包内容不完整(未找到 ProcessDesignSuite.exe)'); } if (mounted) setState(() => _status = '正在准备覆盖更新…'); final String appDir = File(Platform.resolvedExecutable).parent.path; final String batPath = '${tmp.path}\\apply_update.bat'; + // 升级过渡期可能残留旧版 exe:换成新名字时顺手清理旧文件。 + final String cleanup = exeName == 'ProcessDesignSuite.exe' + ? 'if exist "%~2\\EasyDesignCollection.exe" del /q "%~2\\EasyDesignCollection.exe"\r\n' + 'if exist "%~2\\EasyDesignCollection.exe.manifest" del /q "%~2\\EasyDesignCollection.exe.manifest"\r\n' + : ''; // 生成替换脚本:等待本程序退出 → 原地覆盖 → 重新启动。 // 内容保持纯 ASCII,源/目标路径通过参数传入(cmd 以 UTF-16 接收参数, // 中文安装路径也能正确处理);脚本文件本身不包含路径,避免编码问题。 File(batPath).writeAsStringSync( '@echo off\r\n' ':wait\r\n' + 'tasklist /fi "IMAGENAME eq ProcessDesignSuite.exe" | find /i "ProcessDesignSuite.exe" >nul\r\n' + 'if not errorlevel 1 (\r\n' + ' ping -n 1 -w 600 127.0.0.1 >nul\r\n' + ' goto wait\r\n' + ')\r\n' 'tasklist /fi "IMAGENAME eq EasyDesignCollection.exe" | find /i "EasyDesignCollection.exe" >nul\r\n' 'if not errorlevel 1 (\r\n' ' ping -n 1 -w 600 127.0.0.1 >nul\r\n' ' goto wait\r\n' ')\r\n' 'xcopy /e /i /y /q "%~1\\*" "%~2\\"\r\n' - 'start "" "%~2\\EasyDesignCollection.exe"\r\n' + '$cleanup' + 'start "" "%~2\\$exeName"\r\n' 'del "%~f0"\r\n', flush: true, ); diff --git a/lib/update/update_service.dart b/lib/update/update_service.dart index adfe6c9..c934063 100644 --- a/lib/update/update_service.dart +++ b/lib/update/update_service.dart @@ -14,7 +14,7 @@ library; import 'dart:convert'; import 'dart:io'; -import '../version.dart'; +import 'package:sequence_diagram/version.dart'; /// Gitea 服务器与仓库定位。 class UpdateServer { @@ -22,8 +22,8 @@ class UpdateServer { static const String host = 'http://124.220.63.9:30000'; /// 仓库拥有者。 static const String owner = 'admin'; - /// 仓库名称(2026-10 由 Sequence-Diagram 改名; - /// 旧名在服务器保留 301 重定向,老客户端查更新不受影响)。 + /// 仓库名称(服务器仓库名保持不变;客户端更新地址依赖它, + /// 软件品牌更名不影响该常量)。 static const String repo = 'EasyDesignCollection'; /// 版本检查接口(最新正式发布)。 @@ -48,7 +48,7 @@ class UpdateInfo { /// 更新说明(Markdown 文本)。 final String notes; - /// 安装包文件名(如 `EasyDesignCollection_android_v1.3.10_release.apk`)。 + /// 安装包文件名(如 `ProcessDesignSuite_android_v1.3.13_release.apk`)。 final String assetName; /// 安装包下载地址。 diff --git a/lib/version.dart b/lib/version.dart index 8e95e22..8c7c36c 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -2,7 +2,7 @@ /// /// 应用内更新检查用它判断服务器发布的版本是否更新; /// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。 -const String kAppVersion = '1.3.12'; +const String kAppVersion = '1.3.13'; /// 是否要求授权(License)才能导出。 /// diff --git a/pubspec.yaml b/pubspec.yaml index 60cba66..fa1bb47 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: sequence_diagram -description: "EDC易得 · Easy Design Collection:面向 PLC 流程节拍 / 相位角、系统架构与电气设计的桌面软件。" +description: "PDS流程设计套件 · Process Design Suite:面向 PLC 流程节拍 / 相位角、系统架构与电气设计的桌面软件。" # 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 @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # 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.3.12+34 +version: 1.3.13+35 environment: sdk: ^3.13.3 @@ -57,6 +57,15 @@ flutter: # the material Icons class. uses-material-design: true + assets: + - assets/modules/registry.json + - assets/modules/architecture/module.json + - assets/modules/sequence/module.json + - assets/modules/elec/module.json + - assets/modules/io/module.json + - assets/modules/topo/module.json + - assets/modules/pid/module.json + # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg diff --git a/scripts/build.bat b/scripts/build.bat index 14192bc..3f4d29f 100644 --- a/scripts/build.bat +++ b/scripts/build.bat @@ -1,5 +1,6 @@ @echo off -rem Build the Windows release and copy the runnable bundle to .\dist\ +rem Build the Windows release and copy the runnable bundle to the shared release +rem root next to the source tree: ..\..\release\windows\ProcessDesignSuite rem (ASCII only: .bat files are read with the OEM codepage.) setlocal @@ -10,11 +11,13 @@ rem NOTE: avoid `if (...)` blocks here -- %PATH% contains parentheses rem (e.g. "Program Files (x86)") which break cmd block parsing. set FLUTTER_BIN=D:\flutter\bin if not exist D:\flutter\bin\flutter.bat set FLUTTER_BIN=E:\flutter\bin +if not exist E:\flutter\bin\flutter.bat set FLUTTER_BIN=E:\AiCodeGitea\ven\flutter\bin set PATH=%FLUTTER_BIN%;%PATH% set FLUTTER_CMAKE_PATH= if exist D:\cmake-lv\bin\cmk2.exe set FLUTTER_CMAKE_PATH=D:\cmake-lv\bin\cmk2.exe if exist E:\cmake-lv\bin\cmk2.exe set FLUTTER_CMAKE_PATH=E:\cmake-lv\bin\cmk2.exe +if exist E:\AiCodeGitea\ven\cmake-lv\bin\cmk2.exe set FLUTTER_CMAKE_PATH=E:\AiCodeGitea\ven\cmake-lv\bin\cmk2.exe if "%FLUTTER_CMAKE_PATH%"=="" echo [warn] renamed CMake not found: D:\cmake-lv\bin\cmk2.exe if "%FLUTTER_CMAKE_PATH%"=="" echo [warn] if a transparent-encryption DLP is installed, run scripts\setup-cmake.bat first. @@ -27,15 +30,21 @@ if errorlevel 1 ( exit /b 1 ) -if exist dist rmdir /s /q dist -mkdir dist -xcopy /e /i /y /q "build\windows\x64\runner\Release\*" "dist\" >nul +set "RELEASE_WINDOWS=%~dp0..\..\release\windows" +set "OUT=%RELEASE_WINDOWS%\ProcessDesignSuite" +if not exist "%RELEASE_WINDOWS%" mkdir "%RELEASE_WINDOWS%" +if exist "%OUT%" rmdir /s /q "%OUT%" +mkdir "%OUT%" +xcopy /e /i /y /q "build\windows\x64\runner\Release\*" "%OUT%\" >nul + +rem Release-level module registry: visible modules//module.json next to exe. +if exist "assets\modules" xcopy /e /i /y /q "assets\modules\*" "%OUT%\modules\" >nul rem Create an empty license folder next to the exe and copy ONLY *.lic files. rem IMPORTANT: never ship any documentation (the algorithm must stay private). -if not exist "dist\license" mkdir "dist\license" -if exist "license\*.lic" xcopy /y /q "license\*.lic" "dist\license\" >nul +if not exist "%OUT%\license" mkdir "%OUT%\license" +if exist "license\*.lic" xcopy /y /q "license\*.lic" "%OUT%\license\" >nul echo. -echo Build OK: dist\sequence_diagram.exe +echo Build OK: %OUT%\ProcessDesignSuite.exe endlocal diff --git a/scripts/publish_release.ps1 b/scripts/publish_release.ps1 index 19d7ec8..adceefe 100644 --- a/scripts/publish_release.ps1 +++ b/scripts/publish_release.ps1 @@ -3,13 +3,14 @@ # # 用法(在仓库根目录或任意位置): # powershell -File scripts\publish_release.ps1 -Version 1.2.1 ` -# -NotesFile release\notes\RELEASE_NOTES_v1.2.1.md +# -NotesFile docs\release-notes\RELEASE_NOTES_v1.2.1.md # # 说明: # - 更新说明写入 Release 正文(Markdown),客户端「检查更新」时读取展示; -# - 安卓 APK:默认取 release\android\EasyDesignCollection_android_v<版本>_release.apk; -# - Windows 绿色版:默认把 release\windows\EasyDesignCollection\ 打包为 zip -# (客户端下载后原地解压覆盖;zip 内部必须平铺,脚本自动生成于 release\windows\); +# - 发布根目录:默认在源码仓库同级的 release\(可 -ReleaseRoot 覆盖); +# - 安卓 APK:默认取 \android\ProcessDesignSuite_android_v<版本>_release.apk; +# - Windows 绿色版:默认把 \windows\ProcessDesignSuite\ 打包为 zip +# (客户端下载后原地解压覆盖;zip 内部必须平铺); # - 安装包作为 Release 附件保存,不进入 git 历史,仓库保持精简; # - 发布幂等:v<版本> 已存在(如上次上传中断)时复用它并更新说明; # - 发布完成后自动清理历史附件:只保留「最新 1 个版本」的安装包 @@ -20,9 +21,10 @@ param( [Parameter(Mandatory = $true)][string]$NotesFile, [string]$ApkPath = "", [string]$WindowsZipPath = "", + [string]$ReleaseRoot = "", [string]$Server = "http://124.220.63.9:30000", [string]$Owner = "admin", - [string]$Repo = "EasyDesignCollection", # 2026-10 由 Sequence-Diagram 改名(旧名保留 301 重定向) + [string]$Repo = "EasyDesignCollection", # 服务器仓库名保持不变(客户端更新地址依赖它) [string]$Auth = "liuyu65@126.com:ds3317210", # 上传限速(curl --limit-rate):服务器带宽很小(5Mbps), # 限速上传避免打满带宽把服务器压垮(默认 320KB/s ≈ 2.6Mbps)。 @@ -31,22 +33,26 @@ param( $ErrorActionPreference = "Stop" $root = Split-Path -Parent $PSScriptRoot # 仓库根目录(scripts 的上一级) +if ($ReleaseRoot -eq "") { + $ReleaseRoot = Join-Path (Split-Path -Parent $root) "release" +} +$ReleaseRoot = [System.IO.Path]::GetFullPath($ReleaseRoot) # ---- 1) 定位安装包 ---- if ($ApkPath -eq "") { - $ApkPath = Join-Path $root "release\android\EasyDesignCollection_android_v${Version}_release.apk" + $ApkPath = Join-Path $ReleaseRoot "android\ProcessDesignSuite_android_v${Version}_release.apk" } if (!(Test-Path $ApkPath)) { throw "找不到 APK:$ApkPath(先执行 flutter build apk --release 并归档到 release\)" } if ($WindowsZipPath -eq "") { - $WindowsZipPath = Join-Path $root "release\windows\EasyDesignCollection_windows_v${Version}.zip" + $WindowsZipPath = Join-Path $ReleaseRoot "windows\ProcessDesignSuite_windows_v${Version}.zip" } if (!(Test-Path $WindowsZipPath) -or (Get-Item $WindowsZipPath).Length -lt 1048576) { - $winDir = Join-Path $root "release\windows\EasyDesignCollection" - if (!(Test-Path (Join-Path $winDir "EasyDesignCollection.exe"))) { - throw "找不到 release\windows\EasyDesignCollection\EasyDesignCollection.exe(先执行 flutter build windows --release 并同步到该目录)" + $winDir = Join-Path $ReleaseRoot "windows\ProcessDesignSuite" + if (!(Test-Path (Join-Path $winDir "ProcessDesignSuite.exe"))) { + throw "找不到 $winDir\ProcessDesignSuite.exe(先执行 scripts\build.bat 或 flutter build windows --release)" } Write-Host "打包 Windows 绿色版:$WindowsZipPath" if (Test-Path $WindowsZipPath) { Remove-Item $WindowsZipPath -Force } diff --git a/test/arch_export_test.dart b/test/arch_export_test.dart index 9345601..27ec3be 100644 --- a/test/arch_export_test.dart +++ b/test/arch_export_test.dart @@ -2,9 +2,9 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_dxf.dart'; -import 'package:sequence_diagram/arch/arch_export.dart'; -import 'package:sequence_diagram/arch/arch_samples.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_dxf.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_export.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_samples.dart'; import 'package:sequence_diagram/theme/tokens.dart'; void main() { diff --git a/test/arch_panel_test.dart b/test/arch_panel_test.dart index ea14fbd..e5d9727 100644 --- a/test/arch_panel_test.dart +++ b/test/arch_panel_test.dart @@ -1,11 +1,11 @@ // 架构图属性面板回归:选中图元后显示基本信息;已移除的「尺寸标注」不再出现。 import 'package:flutter/material.dart' hide Action; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.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/arch_panel.dart'; +import 'package:sequence_diagram/modules/architecture/ui/arch_panel.dart'; void main() { testWidgets('选中图元:属性卡正常显示,且不再有「尺寸 · mm」区', diff --git a/test/arch_screenshots_test.dart b/test/arch_screenshots_test.dart index 544beb4..82e59e1 100644 --- a/test/arch_screenshots_test.dart +++ b/test/arch_screenshots_test.dart @@ -5,13 +5,12 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_models.dart'; -import 'package:sequence_diagram/arch/arch_painter.dart'; -import 'package:sequence_diagram/arch/arch_recognizer.dart'; -import 'package:sequence_diagram/arch/arch_samples.dart'; -import 'package:sequence_diagram/model/models.dart'; -import 'package:sequence_diagram/sketch/sketch_models.dart'; -import 'package:sequence_diagram/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_painter.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_recognizer.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_samples.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; import 'package:sequence_diagram/state/app_controller.dart'; import 'package:sequence_diagram/theme/tokens.dart'; import 'package:sequence_diagram/ui/app_shell.dart'; @@ -58,7 +57,7 @@ void main() { await shot('../demo/home-light.png'); // 切换到架构图模块(左上角「设计合集」菜单的动作)。 - c.setAppMode(AppMode.architecture); + c.setModuleId('architecture', status: '架构图设计 · 手绘识别'); await tester.pump(); // 展开左右侧栏(浮层)并钉住,展示停靠布局(与 tablet 截图一致的操作)。 diff --git a/test/arch_symbol_recognizer_test.dart b/test/arch_symbol_recognizer_test.dart index 493df1e..a54392b 100644 --- a/test/arch_symbol_recognizer_test.dart +++ b/test/arch_symbol_recognizer_test.dart @@ -2,8 +2,8 @@ import 'dart:math' as math; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_symbol_recognizer.dart'; -import 'package:sequence_diagram/library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_symbol_recognizer.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; /// 线段采样。 List seg(Offset a, Offset b, {int n = 10}) => [ diff --git a/test/arch_test.dart b/test/arch_test.dart index c89b9cf..7cacb48 100644 --- a/test/arch_test.dart +++ b/test/arch_test.dart @@ -5,10 +5,10 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_models.dart'; -import 'package:sequence_diagram/arch/arch_painter.dart'; -import 'package:sequence_diagram/arch/arch_recognizer.dart'; -import 'package:sequence_diagram/arch/arch_samples.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_painter.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_recognizer.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_samples.dart'; import 'package:sequence_diagram/model/models.dart'; import 'package:sequence_diagram/state/app_controller.dart'; diff --git a/test/dep_routes_test.dart b/test/dep_routes_test.dart index 0c5314d..16a24fb 100644 --- a/test/dep_routes_test.dart +++ b/test/dep_routes_test.dart @@ -1,9 +1,9 @@ // 依赖走线测试:自动错开、手动偏移、命中测试与 JSON 往返。 -import 'dart:ui' show Size, Offset; +import 'dart:ui' show Size, Offset, Rect; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/layout/dep_routes.dart'; -import 'package:sequence_diagram/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; import 'package:sequence_diagram/model/models.dart'; /// 构造测试工程:A1/A2/A3 同属一条泳道(L0),A3 依赖 A1 与 A2, @@ -25,7 +25,7 @@ Project _project({double offset = 0}) { durationAngle: 30, layer: 0, color: 0xFF4CC9F0), - const Action( + Action( id: 'A2', name: 'A2', stationId: 'ST1', @@ -96,4 +96,213 @@ void main() { }); expect(legacy.routeOffset, 0); }); + + test('条形:默认从端点中心引出;端部被遮挡时退到上下角', () { + Project make({required bool blocker}) => Project( + name: 'anchor', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: [ + const Action( + id: 'A1', + name: 'A1', + stationId: 'ST1', + driver: '', + startAngle: 0, + durationAngle: 30, + layer: 0, + color: 0xFF4CC9F0), + if (blocker) + const Action( + id: 'A2', + name: 'A2', + stationId: 'ST1', + driver: '', + startAngle: 33, + durationAngle: 30, + layer: 0, + color: 0xFF7BD88F), + const Action( + id: 'A3', + name: 'A3', + stationId: 'ST1', + driver: '', + startAngle: 80, + durationAngle: 30, + layer: 0, + color: 0xFFFFD166, + deps: [Dependency(fromId: 'A1', toId: 'A3')]), + ], + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar), + ); + + Project p = make(blocker: false); + BarLayout layout = BarLayout(p, size); + BarDepRoute r = buildBarDepRoutes(p, layout).single; + final Rect ra = layout.rectFor(p.actionById('A1')!); + final Rect rb = layout.rectFor(p.actionById('A3')!); + expect(r.points.first.dx, closeTo(ra.right + 2, 0.001)); + expect(r.points.first.dy, closeTo(ra.center.dy, 0.001)); + expect(r.points.last.dx, closeTo(rb.left - 2, 0.001)); + expect(r.points.last.dy, closeTo(rb.center.dy, 0.001)); + + // A2 紧贴 A1 右端:源端应退到下角,目标端仍从中心进入。 + p = make(blocker: true); + layout = BarLayout(p, size); + r = buildBarDepRoutes(p, layout).single; + final Rect ra2 = layout.rectFor(p.actionById('A1')!); + final Rect rb2 = layout.rectFor(p.actionById('A3')!); + expect(r.points.first.dy, closeTo(ra2.bottom - 2, 0.001)); + expect(r.points.length, greaterThan(2)); + expect(r.points.last.dy, closeTo(rb2.center.dy, 0.001)); + expect(r.points.last.dx, closeTo(rb2.left - 2, 0.001)); + }); + + test('条形:前后贴紧时隐藏连线,标签位于接缝处', () { + final Project q = Project( + name: 'tight', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: const [ + Action( + id: 'A1', + name: 'A1', + stationId: 'ST1', + driver: '', + startAngle: 0, + durationAngle: 70, + layer: 0, + color: 0xFF4CC9F0), + Action( + id: 'A2', + name: 'A2', + stationId: 'ST1', + driver: '', + startAngle: 70, + durationAngle: 60, + layer: 0, + color: 0xFF7BD88F, + deps: [Dependency(fromId: 'A1', toId: 'A2')]), + ], + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar), + ); + final BarLayout layout = BarLayout(q, size); + final BarDepRoute r = buildBarDepRoutes(q, layout).single; + final Rect ra = layout.rectFor(q.actionById('A1')!); + final Rect rb = layout.rectFor(q.actionById('A2')!); + expect(r.junctionOnly, isTrue); + expect(r.points, isEmpty); + expect(r.chipCenter.dx, closeTo((ra.right + rb.left) / 2, 0.001)); + expect(r.chipCenter.dy, lessThan(ra.top)); + }); + + test('圆周:同环依赖的绕行与标签位于环外空隙', () { + final Project p = Project( + name: 'circ', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: const [ + Action( + id: 'A1', + name: 'A1', + stationId: 'ST1', + driver: '', + startAngle: 0, + durationAngle: 70, + layer: 0, + color: 0xFF4CC9F0), + Action( + id: 'A2', + name: 'A2', + stationId: 'ST1', + driver: '', + startAngle: 70, + durationAngle: 60, + layer: 0, + color: 0xFF7BD88F, + deps: [Dependency(fromId: 'A1', toId: 'A2')]), + ], + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.circular), + ); + final CircularLayout layout = CircularLayout(p, size); + final ArcDepRoute r = buildArcDepRoutes(p, layout).single; + expect(r.junctionOnly, isTrue); + expect(r.rC, greaterThan(r.rB)); + expect(r.chipR, greaterThan(r.rB)); + }); + + test('条形:FS / FF 取后端,SS / SF 取前端', () { + final Project p = Project( + name: 'semantics', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: [ + const Action( + id: 'A1', + name: 'A1', + stationId: 'ST1', + driver: '', + startAngle: 0, + durationAngle: 30, + layer: 0, + color: 0xFF4CC9F0), + const Action( + id: 'A2', + name: 'A2', + stationId: 'ST1', + driver: '', + startAngle: 60, + durationAngle: 30, + layer: 1, + color: 0xFF7BD88F, + deps: [ + Dependency(fromId: 'A1', toId: 'A2', type: DepType.ff) + ]), + const Action( + id: 'A3', + name: 'A3', + stationId: 'ST1', + driver: '', + startAngle: 100, + durationAngle: 30, + layer: 2, + color: 0xFFFFD166, + deps: [ + Dependency(fromId: 'A2', toId: 'A3', type: DepType.ss) + ]), + ], + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar), + ); + final BarLayout layout = BarLayout(p, size); + final List routes = buildBarDepRoutes(p, layout); + final Rect r1 = layout.rectFor(p.actionById('A1')!); + final Rect r2 = layout.rectFor(p.actionById('A2')!); + final Rect r3 = layout.rectFor(p.actionById('A3')!); + + // FF:源后端(右端)→ 目标后端(右端)。 + final BarDepRoute ff = + routes.firstWhere((BarDepRoute r) => r.key == 'A1->A2'); + expect(ff.points.first.dx, greaterThan(r1.right)); + expect(ff.points.last.dx, greaterThan(r2.right)); + expect(ff.arrowDir.dx, lessThan(0)); + + // SS:源前端(左端)→ 目标前端(左端)。 + final BarDepRoute ss = + routes.firstWhere((BarDepRoute r) => r.key == 'A2->A3'); + expect(ss.points.first.dx, lessThan(r2.left)); + expect(ss.points.last.dx, lessThan(r3.left)); + expect(ss.arrowDir.dx, greaterThan(0)); + }); } diff --git a/test/dependency_edit_test.dart b/test/dependency_edit_test.dart new file mode 100644 index 0000000..7c97881 --- /dev/null +++ b/test/dependency_edit_test.dart @@ -0,0 +1,83 @@ +// 依赖编辑:修改已有依赖的类型 / 偏移 / 前置动作,并保留手动走线偏移。 +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +Project _project() { + Action a(String id, double start) => Action( + id: id, + name: id, + stationId: 'ST1', + driver: '', + startAngle: start, + durationAngle: 30, + layer: 0, + color: 0xFF4CC9F0, + ); + return Project( + name: 'dep-edit', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: [a('A1', 0), a('A2', 60), a('A3', 120)], + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar), + ); +} + +void main() { + test('updateDependency:修改类型与偏移,保留走线偏移', () { + final AppController c = AppController(project: _project()); + addTearDown(c.dispose); + c.addDependency('A1', 'A2', DepType.fs, 0); + c.setDependencyOffset('A1', 'A2', 30); + c.updateDependency( + 'A1', + 'A2', + fromId: 'A1', + type: DepType.ss, + offset: 12, + ); + final Dependency d = + c.project.actionById('A2')!.deps.firstWhere((Dependency d) => d.fromId == 'A1'); + expect(d.type, DepType.ss); + expect(d.offsetAngle, 12); + expect(d.routeOffset, 30); + }); + + test('修改循环时长:依赖偏移的时间保持不变', () { + final AppController c = AppController(project: _project()); + addTearDown(c.dispose); + c.addDependency('A1', 'A2', DepType.ss, 50); + c.setCycleDuration(4800); + Dependency d = + c.project.actionById('A2')!.deps.firstWhere((Dependency d) => d.fromId == 'A1'); + // 2400ms 下 50° = 0.333s;换成 4800ms 后角度应减半,时间不变。 + expect(d.offsetAngle, closeTo(25, 0.001)); + c.setCycleDuration(2400); + d = c.project.actionById('A2')!.deps.firstWhere((Dependency d) => d.fromId == 'A1'); + expect(d.offsetAngle, closeTo(50, 0.001)); + }); + + test('updateDependency:更换前置动作时去重并合并', () { + final AppController c = AppController(project: _project()); + addTearDown(c.dispose); + c.addDependency('A1', 'A2', DepType.fs, 0); + c.addDependency('A3', 'A2', DepType.ss, 5); + c.updateDependency( + 'A1', + 'A2', + fromId: 'A3', + type: DepType.ff, + offset: 7, + ); + final List deps = c.project.actionById('A2')!.deps; + expect(deps.where((Dependency d) => d.fromId == 'A1'), isEmpty); + final List from3 = + deps.where((Dependency d) => d.fromId == 'A3').toList(); + expect(from3.length, 1); + expect(from3.single.type, DepType.ff); + expect(from3.single.offsetAngle, 7); + }); +} diff --git a/test/export_test.dart b/test/export_test.dart index 8bd94a1..463a139 100644 --- a/test/export_test.dart +++ b/test/export_test.dart @@ -4,11 +4,12 @@ import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/export/drawio_writer.dart'; -import 'package:sequence_diagram/export/export_renderer.dart'; -import 'package:sequence_diagram/export/svg_writer.dart'; -import 'package:sequence_diagram/layout/flow_layout.dart'; +import 'package:sequence_diagram/modules/sequence/export/drawio_writer.dart'; +import 'package:sequence_diagram/modules/sequence/export/export_renderer.dart'; +import 'package:sequence_diagram/modules/sequence/export/svg_writer.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/model/units.dart'; import 'package:sequence_diagram/theme/tokens.dart'; import 'helpers.dart'; @@ -66,7 +67,9 @@ void main() { expect(svg, contains('marker-end="url(#arrow-fs)"')); expect(svg, contains('marker-end="url(#arrow-ss)"')); expect(svg, contains('stroke-dasharray="6 4"')); - expect(svg, contains('>SS+10°')); + final String ssLabel = + 'SS+${deg2msStr(10, p.units, p.cycle.durationMs, dec: 2)}'; + expect(svg, contains('>$ssLabel')); expect(svg, contains('')); expect(svg, contains('data-action="A1"')); // 每个节点都在(标题 / 副标题取自布局,避免硬编码格式)。 @@ -103,6 +106,8 @@ void main() { test('drawio export: mxfile with lanes / phases / nodes / edges', () { final Project p = demoTiming(); final String xml = DrawioWriter(project: p, tokens: Tokens.light).build(); + final String ssLabel = + 'SS+${deg2msStr(10, p.units, p.cycle.durationMs, dec: 2)}'; expect(xml, startsWith('')); expect(xml, contains(' Project( diff --git a/test/sketch_test.dart b/test/sketch_test.dart index 423bc53..40d9405 100644 --- a/test/sketch_test.dart +++ b/test/sketch_test.dart @@ -3,10 +3,10 @@ // 控制器集成与画布交互(两次点击画直线)。 import 'package:flutter/material.dart' hide Action; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/arch/arch_models.dart'; +import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart'; import 'package:sequence_diagram/model/models.dart'; -import 'package:sequence_diagram/sketch/sketch_models.dart'; -import 'package:sequence_diagram/sketch/sketch_solver.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart'; +import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart'; import 'package:sequence_diagram/state/app_controller.dart'; import 'package:sequence_diagram/theme/tokens.dart'; import 'package:sequence_diagram/ui/app_shell.dart'; @@ -512,7 +512,7 @@ void main() { home: AppShell(controller: c), )); await tester.pump(); - c.setAppMode(AppMode.architecture); + c.setModuleId('architecture', status: '架构图设计 · 手绘识别'); await tester.pump(); c.setSketchMode(true); c.setSketchTool(SketchTool.line); diff --git a/test/snap_test.dart b/test/snap_test.dart new file mode 100644 index 0000000..80fe423 --- /dev/null +++ b/test/snap_test.dart @@ -0,0 +1,72 @@ +// 动作条整体拖拽吸附:起点/终点同时匹配最近端点、整 5° 与分区边界。 +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/modules/sequence/layout/snap.dart'; +import 'package:sequence_diagram/model/models.dart'; + +Project _project(List actions) { + return Project( + name: 'snap', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: 'S', order: 0, color: 0xFF4CC9F0), + ], + actions: actions, + units: const UnitSettings(), + viewState: const ViewState(mode: ViewMode.bar), + ); +} + +Action _a(String id, double start, double duration) { + return Action( + id: id, + name: id, + stationId: 'ST1', + driver: '', + startAngle: start, + durationAngle: duration, + layer: 0, + color: 0xFF4CC9F0, + ); +} + +void main() { + test('整体拖动:起点吸附到上游动作结束角', () { + final Project p = _project([_a('A1', 0, 40), _a('A2', 80, 40)]); + final (double start, double? guide) = snapActionStart( + project: p, + excludeId: 'A2', + rawStart: 41.5, + duration: 40, + toleranceDeg: 3.5, + ); + expect(start, closeTo(40, 0.001)); + expect(guide, closeTo(40, 0.001)); + }); + + test('整体拖动:终点吸附到下游动作起始角', () { + final Project p = _project([_a('A1', 100, 40), _a('A2', 63, 38)]); + final (double start, double? guide) = snapActionStart( + project: p, + excludeId: 'A2', + rawStart: 63, + duration: 38, + toleranceDeg: 2.5, + ); + // 末端 101 距 A1 起点 100 仅 1°,优先于起点附近的 5° 网格。 + expect(start, closeTo(62, 0.001)); + expect(guide, closeTo(100, 0.001)); + }); + + test('整体拖动:容差外不吸附', () { + final Project p = _project([_a('A1', 0, 40), _a('A2', 123.4, 40)]); + final (double start, double? guide) = snapActionStart( + project: p, + excludeId: 'A2', + rawStart: 123.4, + duration: 40, + toleranceDeg: 1.0, + ); + expect(start, closeTo(123.4, 0.001)); + expect(guide, isNull); + }); +} diff --git a/test/station_test.dart b/test/station_test.dart index 41faa46..dc2dbf0 100644 --- a/test/station_test.dart +++ b/test/station_test.dart @@ -1,8 +1,8 @@ import 'dart:ui' show Rect, Size; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/layout/flow_layout.dart'; -import 'package:sequence_diagram/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/flow_layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.dart'; import 'package:sequence_diagram/model/models.dart'; import 'package:sequence_diagram/state/app_controller.dart'; diff --git a/test/symbol_library_test.dart b/test/symbol_library_test.dart index 382833b..60ea115 100644 --- a/test/symbol_library_test.dart +++ b/test/symbol_library_test.dart @@ -2,7 +2,7 @@ import 'dart:ui' show Path, Rect; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/library/symbol_library.dart'; +import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; void main() { group('内置符号', () { diff --git a/test/widget_test.dart b/test/widget_test.dart index 9e5e4ae..f7113c5 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,12 +1,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:sequence_diagram/layout/dep_routes.dart'; -import 'package:sequence_diagram/layout/layout.dart'; +import 'package:sequence_diagram/modules/sequence/layout/dep_routes.dart'; +import 'package:sequence_diagram/modules/sequence/layout/layout.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'; -import 'package:sequence_diagram/ui/canvas_view.dart'; +import 'package:sequence_diagram/modules/sequence/ui/canvas_view.dart'; void main() { testWidgets('renders bar and circular views without errors', (WidgetTester tester) async { diff --git a/tool/check_update.dart b/tools/check_update.dart similarity index 86% rename from tool/check_update.dart rename to tools/check_update.dart index 11627c4..9e9957a 100644 --- a/tool/check_update.dart +++ b/tools/check_update.dart @@ -2,8 +2,8 @@ // // 用途:验证更新链路(网络可达 / 接口解析 / 版本判定 / 附件匹配)。 // 运行: -// dart run tool\check_update.dart # 用当前版本检查 -// dart run tool\check_update.dart 1.2.1 # 模拟旧版本,验证「发现更新」路径 +// dart run tools\check_update.dart # 用当前版本检查 +// dart run tools\check_update.dart 1.2.1 # 模拟旧版本,验证「发现更新」路径 // // 说明:使用的是与客户端完全相同的 lib/update/update_service.dart; // 本文件是命令行工具,直接向控制台打印结果属预期用法。 @@ -13,7 +13,7 @@ import 'package:sequence_diagram/update/update_service.dart'; import 'package:sequence_diagram/version.dart'; Future main(List args) async { - // 可传入一个版本号模拟旧安装(如 `dart run tool\check_update.dart 1.2.1`)。 + // 可传入一个版本号模拟旧安装(如 `dart run tools\check_update.dart 1.2.1`)。 final String current = args.isNotEmpty ? args.first : kAppVersion; print('当前版本(模拟): $current'); try { diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index fc460f2..fb5e7fd 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,10 +1,10 @@ # Project-level configuration. cmake_minimum_required(VERSION 3.14) -project(EasyDesignCollection LANGUAGES CXX) +project(ProcessDesignSuite 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 "EasyDesignCollection") +set(BINARY_NAME "ProcessDesignSuite") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc index bc01904..7ae86c8 100644 --- a/windows/runner/Runner.rc +++ b/windows/runner/Runner.rc @@ -90,12 +90,12 @@ BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "呆头鹅" "\0" - VALUE "FileDescription", "EDC易得 Easy Design Collection" "\0" + VALUE "FileDescription", "PDS流程设计套件 Process Design Suite" "\0" VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "EasyDesignCollection" "\0" + VALUE "InternalName", "ProcessDesignSuite" "\0" VALUE "LegalCopyright", "Copyright (C) 2026 呆头鹅. All rights reserved." "\0" - VALUE "OriginalFilename", "EasyDesignCollection.exe" "\0" - VALUE "ProductName", "Easy Design Collection" "\0" + VALUE "OriginalFilename", "ProcessDesignSuite.exe" "\0" + VALUE "ProductName", "Process Design Suite" "\0" VALUE "ProductVersion", VERSION_AS_STRING "\0" END END diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp index c1938b5..70fa6bd 100644 --- a/windows/runner/main.cpp +++ b/windows/runner/main.cpp @@ -38,7 +38,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, Win32Window::Size size( static_cast(screen_width / scale * 0.94), static_cast(screen_height / scale * 0.94)); - if (!window.Create(L"EDC\u6613\u5F97", origin, size)) { + if (!window.Create(L"PDS\u6D41\u7A0B\u8BBE\u8BA1\u5957\u4EF6", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true);