diff --git a/.gitignore b/.gitignore index 90e8ebe..e54a5fb 100644 --- a/.gitignore +++ b/.gitignore @@ -31,11 +31,13 @@ desktop.ini /license/*.lic /dist/license/ -# 构建产物:本地保留,不入库、不推送(Windows exe 目录 dist/ 与安卓 APK) +# 构建产物:本地保留,不入库、不推送 +# (Windows 绿色目录 / zip 与安卓 APK 位于 release/ 下,仅 notes 入库) /dist*/ /release/*.apk -/sequence_diagram/ +/release/android/ +/release/windows/ /*.7z -# ½Øͼ±ȶÔʧ°ܲúÎflutter test ×Զ¯Éú³ɣ© +# golden 对比失败产物(flutter test 自动生成) test/failures/ diff --git a/BUILD-NOTES.md b/BUILD-NOTES.md index e850296..f3036c0 100644 --- a/BUILD-NOTES.md +++ b/BUILD-NOTES.md @@ -191,7 +191,7 @@ flutter test --update-goldens test\tablet_screenshots_test.dart # 重新生成 **客户端逻辑**(`lib/update/update_service.dart`、`lib/ui/update_dialog.dart`): - 启动后静默检查 + 工具栏「检查更新」按钮(有新版本时显示红色角标); -- 更新源 = Gitea 仓库的「发布(Releases)」:`GET /api/v1/repos/admin/Sequence-Diagram/releases/latest`(公开只读); +- 更新源 = Gitea 仓库的「发布(Releases)」:`GET /api/v1/repos/admin/EasyDesignCollection/releases/latest`(公开只读;旧名 Sequence-Diagram 保留 301 重定向); - 更新说明 = Release 正文(Markdown);安装包 = Release 附件(安卓 `.apk`,Windows `.zip` 绿色版整包); - 安卓:下载 APK → FileProvider + 系统安装器安装(签名一致可直接覆盖安装); - Windows:下载 zip → 解压 → 生成替换脚本,等主程序退出后原地覆盖并自动重启(无需安装); diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 78a59c7..0e4ae87 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,7 +9,7 @@ 状态:P0 已实施(空白启动首页 + 模块注册表 + 文件路由 + 测试适配,全量 106 项通过); +> P1 部分完成(release/ 目录已按方案 B 重组并验证,运行时路径迁移与素材库目录待做)。 +> 目标:把当前「两模块应用」升级为 +> 「多专业模块的设计合集」:空白启动 → 选择文档类型 → 进入对应模块; +> 文档之间可显式交换数据;构建产物与素材库路径一并规范化。 + +## 0. 目标一句话 + +像 Creo / COMSOL 一样:**打开软件是空白首页**,新建时选择文档类型 +(时序图 / 架构图 / 电器原理图 / IO 表 / 拓扑图 / PID 图),各模块独立文档 +(JSON),模块之间通过「引用导入」交换数据;导出能力按模块注册 +(时序:SVG/PNG + drawio;架构:SVG/PNG/DXF;电器:SVG/DXF;IO:CSV/XLSX…)。 + +## 1. 现状盘点 + +| 维度 | 现状 | 痛点 | +| --- | --- | --- | +| 启动 | `AppController()` 默认装载 `Project.demo()`,`AppMode.sequence` | 打开软件直接进时序图演示工程,不像专业软件 | +| 模块 | `enum AppMode { sequence, architecture }`,外壳内大量 `if (architecture)` 硬编码 | 新增 4 个模块会指数级污染 shell | +| 文档 | `*.seq.json` / `*.arch.json` 独立文件,互不相通 | 未来需要跨模块交换数据,需要统一「信封」与引用机制 | +| 导出 | 导出菜单/方法全部写死在 `app_shell.dart` | 每模块导出不同,继续硬编码不可维护 | +| 运行时路径 | 桌面 `%APPDATA%/SequenceDiagramStudio/autosave/`;安卓 `Documents/SequenceDiagram` | 品牌改名后路径还是旧名;没有素材/图元库位置 | +| 构建产物 | `dist/`(Windows 绿色目录)+ `release/*.apk` | 路径与命名随意,和多模块时代不匹配 | + +改名相关(已完成、不影响本评估):Gitea 仓库已更名 `EasyDesignCollection`, +旧名保留 301 重定向,1.3.4 客户端查更新不受影响(已端到端实测)。 + +## 2. 启动器(首页)设计 —— 空白启动 + +- `AppMode` 增加 `home`:**启动即进入首页**(无文档、无画布、无侧栏)。 +- 首页内容(COMSOL Home 风格,单页即可): + 1. 顶部:品牌 EDC|易得设计 + 版本号; + 2. 中央「新建文档」网格:6 个模块卡片(图标 + 名称 + 一句话); + 未开放的模块灰显标注「未开放」(符合既定规则,无"规划中"字样); + 3. 「打开文档…」按钮(按类型路由到对应模块的打开流程); + 4. 「最近打开」列表(记录:路径、模块、时间;存 `recent.json`); + 5. 右下角:软件设置 / 帮助 / 关于 / 检查更新。 +- 新建/打开成功后切到对应模块工作区;工作区「关闭文档」回到首页。 +- 单文档单窗口(不做多标签);多文档 = 多开(与 COMSOL 一致)。 +- 关闭最后一个文档不退出软件,回首页。 + +## 3. 模块注册表(唯一事实来源) + +新增 `lib/modules/module_registry.dart`,每个模块一条记录: + +```dart +class EdcModule { + final String id; // sequence / architecture / elec / io / topo / pid + final String name; // 时序图 / 架构图 / 电器原理图 / IO 表 / 拓扑图 / PID 图 + final String shortName; // 状态栏/标题用短名 + final IconData icon; + final int accent; // 品牌色 + final String suffix; // .seq.json / .arch.json / .elec.json / .io.json / .topo.json / .pid.json + final bool available; // 未完成模块 false(菜单与首页灰显) + final String defaultDocName; // 新建默认文件名(未命名-时序图 等) + final List exports; // svg / png / dxf / drawio / csv ... +} +const List kModules = [...]; +``` + +- 品牌菜单「设计合集」、首页网格、窗口标题、状态栏、保存/打开后缀、 + 导出菜单 **全部由注册表驱动**;shell 内不再出现模块名字符串。 +- 模块工作区组件选择用 `switch (module.id)`(务实方案),接口约定: + `Widget buildWorkspace()`、`Future save()/open()`、`List exports`; + 后续新模块只需新增 workspace 组件 + 注册一条记录。 + +## 4. 文档模型 v2 与数据交换 + +### 4.1 统一信封(向后兼容) + +```jsonc +{ + "schema": "edc/2", + "meta": { + "docType": "sequence", // 模块 id(旧文件缺失时按内容嗅探) + "name": "装配线节拍", + "created": "...", "modified": "...", + "appVersion": "1.3.5" + }, + "tags": [ { "id": "T1", "name": "PLC 主站", "kind": "plc" } ], // 位号/设备注册表(交换锚点) + "payload": { /* 模块私有数据:现有 Project / ArchDoc 等 */ } +} +``` + +- 旧文件兼容:`edc/1.3` 与裸 ArchDoc JSON 均按现有逻辑读入(嗅探 `schema/project/shapes` 键)。 +- 文件后缀沿用:`*.seq.json` / `*.arch.json`(新增 `*.elec.json` / `*.io.json` / `*.topo.json` / `*.pid.json`)。 + +### 4.2 数据交换(显式引用导入,拒绝隐式耦合) + +机制:模块提供「从其它文档导入」动作 → 选择源文件 → 读取对方 `tags/payload` +→ 映射导入 → 记录来源元数据: + +```jsonc +{ "importedFrom": { "path": "…/line.elec.json", "exported": "2026-10-11T10:00:00Z" } } +``` + +按需「重新同步」。首批规划的两条链路: +1. 电器原理图 → IO 表(PLC 点位:地址 / 符号 / 注释 / 类型); +2. 架构图 → IO 表 / PID(设备清单:名称 / 位号 / 通讯)。 +远期可选「工程清单」(`*.edcproj`,记录一组文档路径),但**不引入**共享大文件, +保持"一份文档一个文件"的现状。 + +## 5. 导出体系 + +新增 `lib/export/export_registry.dart`:`ExportItem { id, label, icon, tip, handler }`, +每模块注册自己的导出项,shell 只负责渲染菜单与文件对话框。 + +| 模块 | 现有 | 计划 | +| --- | --- | --- | +| 时序图 | SVG / PNG;流程图 + drawio | 保持 | +| 架构图 | SVG / PNG / DXF | 保持 | +| 电器原理图 | — | SVG / PNG / DXF | +| IO 表 | — | CSV(Excel 可直接开)/ XLSX(P4 视依赖) | +| 拓扑图 | — | SVG / PNG | +| PID 图 | — | SVG / PNG / PDF(打印) | + +## 6. 路径与打包评估(重点) + +### 6.1 运行时数据路径(桌面) + +``` +%APPDATA%/EDC/ ← 由 SequenceDiagramStudio 更名 + autosave/ + current.seq.json ← 任务快照改为按模块分槽:current..json + session.json + recent.json ← 最近打开列表(新增) + library/ ← 用户级素材库(新增) + symbols/ ← 自定义图元(*.symbol.json / 导入 SVG) + images/ ← 导入的图片 + templates/ ← 文档模板(新建时的可选模板) + settings.json ← 远期:主题/自动保存等(现在在工程文件里) +``` + +迁移策略:启动时若旧目录存在且新目录不存在 → **复制**(不改写旧目录), +状态栏提示「已迁移旧版本数据」。旧目录保留一个版本周期后再考虑清理。 + +### 6.2 内置素材(随包发布,只读) + +内置图元/素材不新增外层文件夹,直接走 Flutter assets +(`assets/symbols/…`,打进 `data/flutter_assets`):安装目录保持最小, +也天然防误删。用户新增素材一律进 `%APPDATA%/EDC/library/`。 + +### 6.3 Android 端 + +- 公开目录:`Documents/EDC/`(由 `Documents/SequenceDiagram` 更名; + 打开对话框同时列出旧目录文件,兼容一个版本)。 +- 素材库:`Documents/EDC/library/{symbols,images,templates}`。 +- 更新包与文档保存流程不变。 + +### 6.4 构建产物路径(本地 + 发布) + +现状:`dist/`(exe 平铺)+ `release/*.apk`(命名混杂旧新两套)。 + +建议(方案 B,一次到位): + +``` +release/ + windows/ + EasyDesignCollection/ ← 绿色目录(= 现在 dist 的内容) + EasyDesignCollection_windows_v1.3.5.zip ← 打包发布用 + android/ + EasyDesignCollection_android_v1.3.5_release.apk + notes/ + RELEASE_NOTES_v1.3.5.md +``` + +- **硬约束**:Windows 更新包 zip 内部必须保持**平铺** + (exe + dll + data/ + license/ 在 zip 根),客户端是"解压覆盖安装目录"式更新; + 外层不包一层目录、目录名可随意。 +- `scripts/publish_release.ps1`、`scripts/build.bat` 默认路径同步改到新目录; + `dist/` 制作一次后退役(保留一个版本周期)。 +- 方案 A(保守):维持 `dist/` 名字,只规范 `release/android|notes`。 + 推荐 B:既然要做多模块大版本,一次整理干净,脚本改动量很小(半屏)。 + +(已实施 2026-10-11,方案 B:`dist/` 留说明文件退役;新版发布脚本读取 +`release\windows\EasyDesignCollection\`,zip 生成于 `release\windows\`, +APK 归档 `release\android\`,更新说明归档 `release\notes\`;zip 平铺已校验。) + +## 7. 分阶段实施计划 + +| 阶段 | 内容 | 验收 | +| --- | --- | --- | +| P0 空白启动 | `AppMode.home` + 首页(新建网格/打开/最近/设置)+ 模块注册表 + 现有测试适配 | 启动进首页;新建/打开时序、架构正常往返;全量测试绿 | +| P1 路径体系 | `app_paths.dart` 统一路径 + EDC 目录迁移 + library 目录创建 + 打包脚本切 release/ 新结构 | 旧数据自动迁移;发布脚本按新路径跑通 | +| P2 新模块接入 | 电器原理图(图元库先行)→ IO 表(表格)→ 拓扑图 → PID 图;每模块:模型 + 画布/编辑器 + 导出 + 测试 | 各模块可新建/保存/打开/导出 | +| P3 数据交换 | tag 注册表 + 引用导入(电气→IO、架构→IO 优先)+ 重新同步 | 跨文档导入闭环 | +| P4 素材库 | 库管理面板(导入/分类/拖入画布)+ 模板 | 用户素材可用可管理 | + +## 8. 风险与注意事项 + +1. **测试面广**:~99 个用例假设"启动即时序图"。P0 需要一个 + `pumpApp(module: …)` 测试助手,逐组适配,避免大面积改断言。 +2. **快照恢复**:多模块后 `current.seq.json` 需按模块分槽,恢复对话框要注明模块。 +3. **数据迁移**:一律"复制不改写",任何迁移失败不得阻塞启动。 +4. **更新包布局**:zip 平铺是硬约束(见 6.4),组包脚本需有断言防呆。 +5. **仓库改名**:已完成(301 重定向已于服务器端到端验证);发布脚本与 + 客户端常量已切到 `EasyDesignCollection`,无需额外动作。 +6. **发布节奏**:1.3.5 未开发完成前不推送、不发布(本评估不改变该约定)。 diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 78d234e..e0e3141 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -10,9 +10,9 @@ | 版本 | 主题 | 状态 | | --- | --- | --- | -| **v1.3.4** | 泳道拓宽计划(空泳道策略 + 多槽位泳道,扩展到圆周图 / 流程图) | 开发中 | -| **v1.3.5** | 软件更名 + 架构图设计能力(含手写笔涂鸦识别) | 规划 | -| **v1.3.6** | 硬件组态 / IO 规划表 / 元器件表 → 网络拓扑 → P&ID 图 | 规划 | +| **v1.3.4** | 泳道拓宽计划(空泳道策略 + 多槽位泳道,扩展到圆周图 / 流程图) | 已发布 | +| **v1.3.5** | 软件更名(EDC\|设计套件)+ 架构图设计能力(手绘识别 / 全套图形与连线) | 开发中 | +| **v1.3.6** | 硬件组态 / IO 规划表 / 元器件库 / 电气柜布置 / 电路板 EDA 初步布置 / 硬件清单 BOM → 网络拓扑 → P&ID 图 | 规划 | | **v2.0.1** | 大版本:新数据类型、视图报表、协作云端、AI 大跨越 | 规划 | ## 二、v1.3.4 泳道拓宽计划(本轮) @@ -37,22 +37,37 @@ - 更新检查确认「直接升级到最新版本」(不做逐版本升级),更新对话框中明确提示 “将直接升级到 vX.Y.Z(最新版本)”。 -## 三、v1.3.5 更名与架构图 +## 三、v1.3.5 更名与架构图(开发中) -- **软件更名**:`Easy Design Collection`,中文名 **易得设计集** - (窗口标题、Logo、关于页、安装包命名、README 等全量替换)。 -- **架构图设计能力**:在现有节拍设计之外,扩展“架构图”设计; - 交互与 UI 将采用**全新的设计语言**(由需求方提供设计稿)。 -- **手写笔涂鸦识别**:支持手写笔在画布上涂鸦(画方块、圆圈、线条等), - **自动识别并转换为模块 / 元件**,体验参考 Apple 的手写识别(Freeform / 备忘录)。 +- **软件更名**:`Easy Design Collection`(缩写 **EDC**),中文名 **EDC|易得设计** + (窗口标题、Logo 菜单、关于页已替换;安装包命名与 README 随发布更新)。 +- **合集菜单**:左上角「EDC|易得设计」下拉**一次列全所有模块**(时序图 / 架构图已可用, + 其余以「规划中」列出、按序点亮);后续模块只需在菜单中逐个开放,不再调整导航结构。 + 菜单在 logo 下方展开、不遮挡 logo,内容超高时内部滚动。 +- **架构图设计(本轮已交付)**: + - 手绘识别:直线 / 箭头 / 矩形 / 圆角矩形 / 圆 / 椭圆 / 三角形 / 菱形 / 六边形 / + **折线(近轴段自动扶正)** / **曲线(样条平滑)** / **云(凹口鼓包判定)** / + **圆柱(柱体 + 顶盖双轮廓,支持两笔拼接)**;识别不了保留墨迹; + - **多笔组合识别**:两笔画出的矩形、先画顶盖再画柱体等; + - **三种笔模式**:图形识别 / 手写文字 / 纯墨迹(保证稳定性,互不干扰); + - 选择 / **框选多选(鼠标拖框、触屏长按)** / 批量移动、8 点缩放、 + **网格吸附(粒度 10/20/40/80 可调)**、双击改字、层级、换色(多选批量); + - 连线:直线 / **正交折线**两种走线(选中后可在属性栏切换)、 + **拖动中按住 Shift 极轴吸附 15°**、吸附图形后自动跟随; + - 示例场景与「识别演示」逐笔转化动画。 +- **手写文字识别(进行中)**:文字模式暂保留笔迹不误转图形;逐字识别 + (模板匹配:数字 / 字母 / 常用汉字,识别后可双击改正)在后续小版本接入。 -## 四、v1.3.6 硬件组态 → 拓扑 → P&ID +## 四、v1.3.6 硬件组态 → 元器件库 → 柜布置 / EDA → 拓扑 → P&ID 1. **硬件组态 / 硬件组合**:PLC、变频器、各类模块的选型与组态; 2. **IO 规划表**:点位表(DI / DO / AI / AO)规划、模块分配与导出; -3. **元器件表**:BOM 式元器件清单,与组态数据联动; -4. **网络与组态拓扑图**:设备间网络 / 总线连接拓扑(自动布点、连线路由); -5. **P&ID 图**:管道与仪表流程图(设备符号库、管线、仪表位号)。 +3. **元器件库**:元件符号 / 参数 / 厂商,供各模块复用(架构图 / 原理图 / 柜布置共用); +4. **电气柜布置**:柜体、导轨、线槽与元件排布(柜内布局视图 + 容量 / 间距检查); +5. **电路板 EDA 初步布置**:板框、器件摆放、预连线(初步布局,不做完整布线规则检查); +6. **硬件清单 / BOM**:元器件清单、选型,与组态 / 柜布置 / EDA 数据联动的导出; +7. **网络与组态拓扑图**:设备间网络 / 总线连接拓扑(自动布点、连线路由); +8. **P&ID 图**:管道与仪表流程图(设备符号库、管线、仪表位号)。 > 以上全部完成后,产品定位由“节拍设计”升级为“设计集”,版本号进入 **2.0.1**。 diff --git a/lib/arch/arch_dxf.dart b/lib/arch/arch_dxf.dart new file mode 100644 index 0000000..54ca27a --- /dev/null +++ b/lib/arch/arch_dxf.dart @@ -0,0 +1,268 @@ +/// 架构图 DXF 导出(AutoCAD R12 ASCII,AC1009): +/// 可直接在 AutoCAD / DraftSight / ZWCAD 等 CAD 软件中打开继续编辑。 +/// +/// 约定: +/// - 图形几何统一采样为 POLYLINE/VERTEX(圆用 CIRCLE、直线用 LINE); +/// - 文字用 TEXT(多行拆多条),连线标签同; +/// - 图层按架构图图层写入 TABLES→LAYER(颜色近似为 ACI 色号); +/// - Y 轴取反(CAD 绿轴向上,画布向下)。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import '../library/symbol_library.dart'; +import 'arch_models.dart'; +import 'arch_painter.dart'; + +/// 构造架构图 DXF 文本。 +String buildArchDxf({required ArchDoc doc}) { + final StringBuffer sb = StringBuffer(); + sb.write('0\nSECTION\n2\nHEADER\n9\n\$ACADVER\n1\nAC1009\n0\nENDSEC\n'); + + // TABLES → LAYER + sb.write('0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n' + '${doc.layers.length}\n'); + for (final ArchLayer l in doc.layers) { + sb.write('0\nLAYER\n2\n${_name(l.name)}\n70\n0\n62\n${_aci(l.color)}\n' + '6\nCONTINUOUS\n'); + } + sb.write('0\nENDTAB\n0\nENDSEC\n'); + + // ENTITIES + sb.write('0\nSECTION\n2\nENTITIES\n'); + for (final ArchConnector c in doc.connectors) { + if (!doc.isLayerVisible(c.layerId)) continue; + _connector(sb, doc, c); + } + for (final ArchShape s in doc.shapes) { + if (!doc.isLayerVisible(s.layerId)) continue; + _shape(sb, doc, s); + } + for (final ArchStroke s in doc.strokes) { + if (!doc.isLayerVisible(s.layerId)) continue; + _polyline(sb, _layerName(doc, s.layerId), s.pts, false); + } + sb.write('0\nENDSEC\n0\nEOF\n'); + return sb.toString(); +} + +// ===================== 图形 ===================== + +void _shape(StringBuffer sb, ArchDoc doc, ArchShape s) { + final String layer = _layerName(doc, s.layerId); + switch (s.type) { + case ArchShapeType.line: + final Offset a = s.a ?? s.rect.topLeft; + final Offset b = s.b ?? s.rect.bottomRight; + _line(sb, layer, a, b); + if (s.arrow) _solidArrow(sb, layer, a, b); + break; + case ArchShapeType.circle: + _circle(sb, layer, s.rect.center, s.rect.width / 2); + break; + case ArchShapeType.text: + break; + case ArchShapeType.rect: + _polyline( + sb, + layer, + [ + s.rect.topLeft, + s.rect.topRight, + s.rect.bottomRight, + s.rect.bottomLeft, + ], + true, + ); + break; + case ArchShapeType.polyline: + _polyline(sb, layer, s.pts, false); + break; + case ArchShapeType.curve: + _samplePath(sb, layer, archSplinePath(s.pts), closed: false); + break; + case ArchShapeType.roundRect: + case ArchShapeType.ellipse: + case ArchShapeType.triangle: + case ArchShapeType.diamond: + case ArchShapeType.cylinder: + case ArchShapeType.cloud: + case ArchShapeType.hexagon: + case ArchShapeType.server: + case ArchShapeType.client: + case ArchShapeType.mobile: + case ArchShapeType.firewall: + case ArchShapeType.netSwitch: + case ArchShapeType.queue: + _samplePath(sb, layer, archShapePath(s), closed: true); + break; + case ArchShapeType.symbol: + final LibSymbol? sym = SymbolCache.byId(s.symbolId); + final Path symPath = (sym == null || s.symbolId.isEmpty) + ? archShapePath(s) + : buildSymbolPath(sym, s.rect); + _samplePathEach(sb, layer, symPath); + break; + } + if (s.text.isNotEmpty) { + final double size = s.type == ArchShapeType.text + ? (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble() + : 12.5; + Offset center = s.rect.center; + if (s.type == ArchShapeType.cloud) { + center = center.translate(0, s.rect.height * 0.12); + } + _text(sb, layer, s.text, center, size); + } +} + +void _connector(StringBuffer sb, ArchDoc doc, ArchConnector c) { + final String layer = _layerName(doc, c.layerId); + final ArchConnGeometry g = archConnectorGeometry(doc, c); + _polyline(sb, layer, g.pts, false); + if (g.pts.length >= 2) { + _solidArrow(sb, layer, g.pts[g.pts.length - 2], g.end); + } + if (c.label.isNotEmpty) { + _text(sb, layer, c.label, g.label, 10.5); + } +} + +// ===================== 实体 ===================== + +void _polyline(StringBuffer sb, String layer, List pts, bool closed) { + if (pts.length < 2) return; + sb.write('0\nPOLYLINE\n8\n$layer\n66\n1\n70\n${closed ? 1 : 0}\n'); + for (final Offset p in pts) { + sb.write('0\nVERTEX\n8\n$layer\n10\n${_n(p.dx)}\n20\n${_n(-p.dy)}\n' + '30\n0\n'); + } + sb.write('0\nSEQEND\n8\n$layer\n'); +} + +void _circle(StringBuffer sb, String layer, Offset c, double r) { + sb.write('0\nCIRCLE\n8\n$layer\n10\n${_n(c.dx)}\n20\n${_n(-c.dy)}\n30\n0\n' + '40\n${_n(r)}\n'); +} + +void _line(StringBuffer sb, String layer, Offset a, Offset b) { + sb.write('0\nLINE\n8\n$layer\n10\n${_n(a.dx)}\n20\n${_n(-a.dy)}\n30\n0\n' + '11\n${_n(b.dx)}\n21\n${_n(-b.dy)}\n31\n0\n'); +} + +void _solidArrow(StringBuffer sb, String layer, Offset from, Offset to) { + final Offset d = to - from; + final double len = d.distance; + if (len < 1) return; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + const double hl = 11; + const double hw = 5.5; + final Offset p1 = to - u * hl + n * hw; + final Offset p2 = to - u * hl - n * hw; + sb.write('0\nSOLID\n8\n$layer\n' + '10\n${_n(to.dx)}\n20\n${_n(-to.dy)}\n30\n0\n' + '11\n${_n(p1.dx)}\n21\n${_n(-p1.dy)}\n31\n0\n' + '12\n${_n(p2.dx)}\n22\n${_n(-p2.dy)}\n32\n0\n' + '13\n${_n(p2.dx)}\n23\n${_n(-p2.dy)}\n33\n0\n'); +} + +void _text(StringBuffer sb, String layer, String text, Offset center, double size) { + final List lines = text.split('\n'); + final double lh = size * 1.25; + final double y0 = center.dy - (lines.length - 1) * lh / 2; + for (int i = 0; i < lines.length; i++) { + final double yy = y0 + i * lh; + sb.write('0\nTEXT\n8\n$layer\n' + '10\n${_n(center.dx)}\n20\n${_n(-yy)}\n30\n0\n' + '40\n${_n(size)}\n1\n${_esc(lines[i])}\n' + '72\n1\n73\n2\n' + '11\n${_n(center.dx)}\n21\n${_n(-yy)}\n31\n0\n'); + } +} + +/// 沿路径按固定步长采样为折线(圆弧近似)。 +void _samplePath(StringBuffer sb, String layer, Path path, + {required bool closed}) { + final List pts = []; + for (final PathMetric m in path.computeMetrics()) { + final int count = math.max(4, (m.length / 6).ceil()); + for (int i = 0; i <= count; i++) { + final Tangent? t = m.getTangentForOffset(m.length * i / count); + if (t != null) pts.add(t.position); + } + } + if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) { + pts.removeLast(); + } + _polyline(sb, layer, pts, closed); +} + +/// 每条子路径各自输出一条折线(图元库符号:多段线互不相连,不能合并)。 +void _samplePathEach(StringBuffer sb, String layer, Path path) { + for (final PathMetric m in path.computeMetrics()) { + final int count = math.max(2, (m.length / 6).ceil()); + final List pts = []; + for (int i = 0; i <= count; i++) { + final Tangent? t = m.getTangentForOffset(m.length * i / count); + if (t != null) pts.add(t.position); + } + if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) { + pts.removeLast(); + } + _polyline(sb, layer, pts, m.isClosed); + } +} + +// ===================== 工具 ===================== + +String _layerName(ArchDoc doc, String layerId) => + _name(doc.layerById(layerId).name); + +/// 图层 / 实体名安全化(DXF 名称不允许空格等特殊字符)。 +String _name(String raw) { + final String n = raw.replaceAll(RegExp(r'[^\w\u4e00-\u9fa5\-]'), '_'); + return n.isEmpty ? 'LAYER' : n; +} + +/// 颜色近似为 AutoCAD 颜色号(R12 兼容)。 +int _aci(int argb) { + const List<(int, int)> table = <(int, int)>[ + (0xFF4CC9F0, 4), + (0xFF34D399, 3), + (0xFFFFD166, 2), + (0xFFFF8A5C, 30), + (0xFFF472B6, 6), + (0xFFA78BFA, 200), + (0xFF38BDF8, 5), + (0xFF94A3B8, 8), + (0xFF7C8DA6, 8), + ]; + final int r = (argb >> 16) & 0xFF; + final int g = (argb >> 8) & 0xFF; + final int b = argb & 0xFF; + int best = 7; + double bestD = double.infinity; + for (final (int rgb, int aci) in table) { + final int rr = (rgb >> 16) & 0xFF; + final int gg = (rgb >> 8) & 0xFF; + final int bb = rgb & 0xFF; + final double d = ((r - rr) * (r - rr) + + (g - gg) * (g - gg) + + (b - bb) * (b - bb)) + .toDouble(); + if (d < bestD) { + bestD = d; + best = aci; + } + } + return best; +} + +String _n(double v) { + if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString(); + return v.toStringAsFixed(2); +} + +String _esc(String s) => s.replaceAll('\n', ' ').replaceAll('\r', ' '); diff --git a/lib/arch/arch_export.dart b/lib/arch/arch_export.dart new file mode 100644 index 0000000..b23f5f3 --- /dev/null +++ b/lib/arch/arch_export.dart @@ -0,0 +1,607 @@ +/// 架构图导出:SVG(矢量,可直接进文档 / 二次编辑)与 PNG(3840×2160 位图)。 +/// +/// 与其他导出保持同一约定: +/// - 导出始终使用**纯白背景**([exportTokens]),与屏幕主题无关; +/// - PNG 画布固定 1920×1080 逻辑尺寸 × 2 倍像素; +/// - 不导出网格点阵与选中框,只导出设计内容。 +library; + +import 'dart:math' as math; +import 'dart:typed_data'; +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 'arch_models.dart'; +import 'arch_painter.dart'; + +// ===================== PNG ===================== + +/// 渲染架构图 PNG(3840×2160 位图)并返回字节。 +Future renderArchPng({ + required ArchDoc doc, + required Tokens baseTokens, + required String projectName, +}) async { + final Tokens et = exportTokens(baseTokens); + final ui.PictureRecorder recorder = ui.PictureRecorder(); + final Canvas canvas = Canvas(recorder); + const double w = 1920; + const double h = 1080; + canvas.scale(kExportPixelRatio); + canvas.drawRect( + const Rect.fromLTWH(0, 0, w, h), + Paint()..color = Colors.white, + ); + + // 标题与副标题(固定左上角)。 + _text(canvas, '架构图设计', const Offset(48, 36), + color: et.text, size: 34, weight: FontWeight.w700); + _text(canvas, 'EDC|易得设计 · Easy Design Collection · 手绘识别架构图', const Offset(48, 88), + color: et.sub, size: 16, weight: FontWeight.w400); + + // 内容适配(白底令牌 + 关闭网格点阵)。 + final Rect b = doc.contentBounds().inflate(40); + final ExportFit fit = _contentFit(b, kExportContentArea); + canvas.save(); + canvas.translate(fit.tx, fit.ty); + ArchPainter( + doc: doc.copyWith(zoom: fit.scale, panX: 0, panY: 0, gridSize: 0), + t: et, + ).paint(canvas, const Size(w, h)); + canvas.restore(); + + _text( + canvas, + 'EDC|易得设计 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 ' + '${doc.connectors.length} · 墨迹 ${doc.strokes.length}', + Offset(48, h - 38), + color: et.sub, + size: 15, + weight: FontWeight.w400, + ); + + final ui.Image image = await recorder.endRecording().toImage( + (w * kExportPixelRatio).toInt(), + (h * kExportPixelRatio).toInt(), + ); + final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png); + return data!.buffer.asUint8List(); +} + +/// 内容适配:等比缩放并居中到 [area]。 +ExportFit _contentFit(Rect bounds, Rect area) { + if (bounds.width <= 1 || bounds.height <= 1) { + return const ExportFit(1, 0, 0); + } + final double s = math + .min(area.width / bounds.width, area.height / bounds.height) + .clamp(0.1, 1.6) + .toDouble(); + final double tx = + area.left + (area.width - bounds.width * s) / 2 - bounds.left * s; + final double ty = + area.top + (area.height - bounds.height * s) / 2 - bounds.top * s; + return ExportFit(s, tx, ty); +} + +/// 用统一字体绘制单行文本。 +void _text( + Canvas canvas, + String s, + Offset at, { + required Color color, + required double size, + required FontWeight weight, +}) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle( + color: color, + fontSize: size, + fontWeight: weight, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const [ + 'Microsoft YaHei', + 'Noto Sans SC', + 'sans-serif', + ], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2)); +} + +// ===================== SVG ===================== + +/// 构造架构图 SVG 文本(viewBox = 内容范围 + 留白;纯白背景)。 +String buildArchSvg({required ArchDoc doc, required Tokens baseTokens}) { + final Tokens t = exportTokens(baseTokens); + final Rect b = doc.contentBounds().inflate(40); + final double w = math.max(b.width, 200); + final double h = math.max(b.height, 160); + final StringBuffer sb = StringBuffer(); + sb.writeln(''); + sb.writeln( + ''); + sb.writeln(''); + + // 连线(底层)。 + for (final ArchConnector c in doc.connectors) { + if (!doc.isLayerVisible(c.layerId)) continue; + _svgConnector(sb, doc, c); + } + // 图形。 + for (final ArchShape s in doc.shapes) { + if (!doc.isLayerVisible(s.layerId)) continue; + _svgShape(sb, s, t); + } + // 手绘墨迹。 + for (final ArchStroke s in doc.strokes) { + if (!doc.isLayerVisible(s.layerId)) continue; + sb.writeln( + ''); + } + sb.writeln(''); + return sb.toString(); +} + +/// 连线(含正交折线、虚线、箭头与标签)。 +void _svgConnector(StringBuffer sb, ArchDoc doc, ArchConnector c) { + final ArchConnGeometry g = archConnectorGeometry(doc, c); + final String d = _polyD(g.pts); + final String color = _hex(c.color); + final String dash = c.dash ? ' stroke-dasharray="8 6"' : ''; + sb.writeln( + ''); + // 箭头(终点方向)。 + if (g.pts.length >= 2) { + final Offset a = g.pts[g.pts.length - 2]; + final Offset b2 = g.end; + final Offset dv = b2 - a; + final double len = dv.distance; + if (len > 1) { + final Offset u = dv / len; + final Offset n = Offset(-u.dy, u.dx); + const double hl = 11; + const double hw = 5.5; + final Offset p1 = b2 - u * hl + n * hw; + final Offset p2 = b2 - u * hl - n * hw; + sb.writeln( + ''); + } + } + // 标签(白底片 + 文本)。 + if (c.label.isNotEmpty) { + final double lw = math.max(20, c.label.length * 10.5 + 10); + final Rect bg = Rect.fromCenter(center: g.label, width: lw, height: 18); + sb.writeln( + ''); + sb.writeln( + '${_esc(c.label)}'); + } +} + +/// 单个标准图形。 +void _svgShape(StringBuffer sb, ArchShape s, Tokens t) { + final String fill = _hex(s.fill); + final String fillOp = _op(s.fill); + final String stroke = _hex(s.stroke); + final String sw = _n(s.sw); + final Rect r = s.rect; + switch (s.type) { + case ArchShapeType.rect: + sb.writeln( + ''); + break; + case ArchShapeType.roundRect: + final double rad = math.min(s.radius, math.min(r.width, r.height) * 0.45); + sb.writeln( + ''); + break; + case ArchShapeType.ellipse: + case ArchShapeType.circle: + sb.writeln( + ''); + break; + case ArchShapeType.triangle: + sb.writeln( + ''); + break; + case ArchShapeType.diamond: + sb.writeln( + ''); + break; + case ArchShapeType.hexagon: + sb.writeln( + ''); + break; + case ArchShapeType.cylinder: + final double ry = math.min(r.height * 0.20, r.width * 0.32); + final double l = r.left; + final double rt = r.right; + final double tp = r.top; + final double bt = r.bottom; + // 柱体(含底部弧)。 + sb.writeln( + ''); + // 顶盖(稍亮)。 + final double lidOp = + math.min(1.0, (_opValue(s.fill) + 0.10)); + sb.writeln( + ''); + break; + case ArchShapeType.cloud: + // 双层绘制:第一层带描边,第二层纯填充覆盖内部接缝 → 外轮廓保持描边。 + final List circles = [ + Offset(r.left + r.width * 0.24, r.top + r.height * 0.62), + Offset(r.left + r.width * 0.42, r.top + r.height * 0.40), + Offset(r.left + r.width * 0.64, r.top + r.height * 0.34), + Offset(r.left + r.width * 0.82, r.top + r.height * 0.58), + ]; + final List radii = [ + r.height * 0.26, + r.height * 0.30, + r.height * 0.28, + r.height * 0.24, + ]; + final Rect base = Rect.fromLTRB( + r.left + r.width * 0.06, + r.top + r.height * 0.55, + r.right - r.width * 0.06, + r.top + r.height * 0.86, + ); + for (int pass = 0; pass < 2; pass++) { + final bool strokePass = pass == 0; + for (int i = 0; i < circles.length; i++) { + sb.writeln( + ''); + } + sb.writeln( + ''); + } + break; + case ArchShapeType.server: + case ArchShapeType.client: + case ArchShapeType.mobile: + case ArchShapeType.firewall: + case ArchShapeType.netSwitch: + case ArchShapeType.queue: + _svgItShape(sb, s, r, fill, fillOp, stroke, sw); + break; + case ArchShapeType.symbol: + _svgSymbol(sb, s, r, fill, fillOp, stroke, sw); + break; + case ArchShapeType.text: + break; + case ArchShapeType.line: + final Offset a = s.a ?? r.topLeft; + final Offset b2 = s.b ?? r.bottomRight; + sb.writeln( + ''); + if (s.arrow) { + _svgArrow(sb, a, b2, stroke); + } + break; + case ArchShapeType.polyline: + if (s.pts.length >= 2) { + sb.writeln( + ''); + } + break; + case ArchShapeType.curve: + if (s.pts.length >= 2) { + sb.writeln( + ''); + } + break; + } + + // 图内文字。 + if (s.text.isNotEmpty) { + final String tc = s.type == ArchShapeType.text + ? _hex(s.stroke) + : _hex(0xFF1B2740); + double size = 12.5; + if (s.type == ArchShapeType.text) { + size = (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble(); + } + Offset center = s.rect.center; + if (s.type == ArchShapeType.cloud) { + center = center.translate(0, s.rect.height * 0.12); + } else if (s.type == ArchShapeType.cylinder) { + center = center.translate( + 0, + math.min(s.rect.height * 0.20, s.rect.width * 0.32) * 0.8); + } else if (s.type == ArchShapeType.client) { + center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.32); + } else if (s.type == ArchShapeType.netSwitch) { + center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.30); + } + _svgMultilineText(sb, s.text, center.dx, center.dy, tc, size); + } +} + +/// IT 图形(服务器 / PC / 移动端 / 防火墙 / 交换机 / 队列)的 SVG 绘制。 +void _svgItShape(StringBuffer sb, ArchShape s, Rect r, String fill, + String fillOp, String stroke, String sw) { + final double rad = switch (s.type) { + ArchShapeType.server => math.min(12.0, math.min(r.width, r.height) * 0.12), + ArchShapeType.client => math.min(10.0, r.height * 0.08), + ArchShapeType.mobile => math.min(16.0, r.width * 0.22), + ArchShapeType.firewall => math.min(6.0, r.height * 0.10), + ArchShapeType.netSwitch => math.min(10.0, r.height * 0.20), + ArchShapeType.queue => r.height * 0.5, + _ => 0.0, + }; + sb.writeln( + ''); + final String inner = + 'stroke="$stroke" stroke-width="${_n(math.max(1, s.sw * 0.7))}" stroke-linecap="round"'; + void hline(double y, double x0, double x1) { + sb.writeln(''); + } + + void dot(double x, double y, double radius) { + sb.writeln( + ''); + } + + switch (s.type) { + case ArchShapeType.server: + for (int i = 1; i <= 3; i++) { + final double y = r.top + r.height * i / 4; + hline(y, r.left + r.width * 0.10, r.right - r.width * 0.10); + } + for (int i = 0; i < 4; i++) { + dot(r.left + r.width * 0.16, r.top + r.height * (i + 0.5) / 4, + math.min(2.4, r.width * 0.035)); + } + case ArchShapeType.client: + final Rect screen = + Rect.fromLTWH(r.left, r.top, r.width, r.height * 0.72); + sb.writeln( + ''); + sb.writeln( + ''); + hline(r.bottom - r.height * 0.08, r.center.dx - r.width * 0.18, + r.center.dx + r.width * 0.18); + case ArchShapeType.mobile: + hline(r.top + r.height * 0.055, r.center.dx - r.width * 0.14, + r.center.dx + r.width * 0.14); + hline(r.bottom - r.height * 0.05, r.center.dx - r.width * 0.12, + r.center.dx + r.width * 0.12); + case ArchShapeType.firewall: + for (int i = 1; i < 3; i++) { + hline(r.top + r.height * i / 3, r.left, r.right); + } + for (int i = 0; i < 3; i++) { + final double y0 = r.top + r.height * i / 3; + final double y1 = r.top + r.height * (i + 1) / 3; + final double offset = i.isEven ? 0.5 : 0.25; + for (double fx = offset; fx < 0.95; fx += 0.5) { + final double x = r.left + r.width * fx; + sb.writeln( + ''); + } + } + case ArchShapeType.netSwitch: + final double size = math.min(r.height * 0.20, 8.0); + for (int i = 0; i < 6; i++) { + final double x = r.left + r.width * (0.10 + i * 0.135); + sb.writeln( + ''); + } + case ArchShapeType.queue: + final double h = r.height * 0.30; + for (int i = 0; i < 3; i++) { + final double x = r.left + r.width * (0.30 + i * 0.18); + sb.writeln( + ''); + } + default: + break; + } +} + +/// 图元库符号的 SVG 绘制(按 100×100 归一化基元映射到矩形)。 +void _svgSymbol(StringBuffer sb, ArchShape s, Rect r, String fill, + String fillOp, String stroke, String sw) { + final LibSymbol? sym = SymbolCache.byId(s.symbolId); + if (sym == null || s.symbolId.isEmpty) { + sb.writeln( + ''); + return; + } + Offset p2(double x, double y) => symPt(x, y, r); + final double rad = (r.width + r.height) / 2 / 100; + for (final SymPrim p in sym.prims) { + switch (p.kind) { + case SymPrimKind.text: + if (p.pts.length < 2 || p.label.isEmpty) break; + final Offset tl = p2(p.pts[0], p.pts[1]); + final double size = + (r.height * 0.14).clamp(7.0, 18.0).toDouble(); + sb.writeln( + '${_esc(p.label)}'); + case SymPrimKind.line: + if (p.pts.length < 4) break; + final Offset a = p2(p.pts[0], p.pts[1]); + final Offset b = p2(p.pts[2], p.pts[3]); + sb.writeln( + ''); + case SymPrimKind.polyline: + if (p.pts.length < 4) break; + final List pts = [ + for (int i = 0; i + 1 < p.pts.length; i += 2) p2(p.pts[i], p.pts[i + 1]), + ]; + sb.writeln( + ''); + case SymPrimKind.circle: + if (p.pts.length < 2) break; + final Offset c = p2(p.pts[0], p.pts[1]); + final double rr = p.r * rad; + sb.writeln( + ''); + case SymPrimKind.rect: + if (p.pts.length < 4) break; + final Offset tl = p2(p.pts[0], p.pts[1]); + sb.writeln( + ''); + case SymPrimKind.arc: + if (p.pts.length < 2) break; + final Offset c = p2(p.pts[0], p.pts[1]); + final double rr = p.r * rad; + final double a0 = p.startDeg * math.pi / 180; + final double a1 = (p.startDeg + p.sweepDeg) * math.pi / 180; + final Offset s0 = + c + Offset(math.cos(a0) * rr, math.sin(a0) * rr); + final Offset s1 = + c + Offset(math.cos(a1) * rr, math.sin(a1) * rr); + final int large = p.sweepDeg.abs() > 180 ? 1 : 0; + final int sweep = p.sweepDeg >= 0 ? 1 : 0; + sb.writeln( + ''); + } + } +} + +/// 箭头头部(line 图形用)。 +void _svgArrow(StringBuffer sb, Offset a, Offset b, String color) { + final Offset dv = b - a; + final double len = dv.distance; + if (len < 1) return; + final Offset u = dv / len; + final Offset n = Offset(-u.dy, u.dx); + const double hl = 11; + const double hw = 5.5; + final Offset p1 = b - u * hl + n * hw; + final Offset p2 = b - u * hl - n * hw; + sb.writeln( + ''); +} + +/// 多行居中文本(每行一个 tspan)。 +void _svgMultilineText( + StringBuffer sb, String text, double cx, double cy, String color, double size) { + final List lines = text.split('\n'); + final double lineH = size * 1.25; + final double startY = cy - (lines.length - 1) * lineH / 2; + sb.writeln( + ''); + for (int i = 0; i < lines.length; i++) { + sb.writeln( + '${_esc(lines[i])}'); + } + sb.writeln(''); +} + +// ===================== 工具 ===================== + +/// 数字格式化(最多 2 位小数、去掉多余 0)。 +String _n(double v) { + if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString(); + return v.toStringAsFixed(2); +} + +/// ARGB → `#rrggbb`。 +String _hex(int argb) { + final int rgb = argb & 0xFFFFFF; + return '#${rgb.toRadixString(16).padLeft(6, '0')}'; +} + +/// ARGB → 不透明度字符串。 +String _op(int argb) => _opValue(argb).toStringAsFixed(3); + +/// ARGB → 不透明度值(0..1)。 +double _opValue(int argb) => ((argb >> 24) & 0xFF) / 255; + +/// 点列表 → polygon points。 +String _points(List pts) => + pts.map((Offset p) => '${_n(p.dx)},${_n(p.dy)}').join(' '); + +/// 折线 d。 +String _polyD(List pts) { + if (pts.isEmpty) return ''; + final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); + for (int i = 1; i < pts.length; i++) { + sb.write(' L ${_n(pts[i].dx)} ${_n(pts[i].dy)}'); + } + return sb.toString(); +} + +/// 样条 d(Catmull-Rom → 三次贝塞尔,与画布绘制一致)。 +String _splineD(List pts) { + if (pts.isEmpty) return ''; + final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); + if (pts.length == 2) { + sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}'); + return sb.toString(); + } + for (int i = 0; i < pts.length - 1; i++) { + final Offset p0 = i == 0 ? pts[i] : pts[i - 1]; + final Offset p1 = pts[i]; + final Offset p2 = pts[i + 1]; + final Offset p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1]; + final Offset c1 = p1 + (p2 - p0) / 6; + final Offset c2 = p2 - (p3 - p1) / 6; + sb.write( + ' C ${_n(c1.dx)} ${_n(c1.dy)} ${_n(c2.dx)} ${_n(c2.dy)} ${_n(p2.dx)} ${_n(p2.dy)}'); + } + return sb.toString(); +} + +/// 平滑墨迹 d(与画布 `archSmoothPath` 一致的二次贝塞尔)。 +String _smoothD(List pts) { + if (pts.isEmpty) return ''; + final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); + if (pts.length == 2) { + sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}'); + return sb.toString(); + } + for (int i = 1; i < pts.length - 1; i++) { + final Offset mid = (pts[i] + pts[i + 1]) / 2; + sb.write(' Q ${_n(pts[i].dx)} ${_n(pts[i].dy)} ${_n(mid.dx)} ${_n(mid.dy)}'); + } + sb.write(' L ${_n(pts.last.dx)} ${_n(pts.last.dy)}'); + return sb.toString(); +} + +/// XML 文本转义。 +String _esc(String s) => s + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); diff --git a/lib/arch/arch_models.dart b/lib/arch/arch_models.dart new file mode 100644 index 0000000..36a0577 --- /dev/null +++ b/lib/arch/arch_models.dart @@ -0,0 +1,1647 @@ +/// 架构图模块数据模型:图形(矩形 / 圆 / 云 / 圆柱……)、手绘墨迹与连线。 +/// +/// 独立于时序图(条形 / 圆周 / 流程)三视图:数据存放在 [ArchDoc], +/// 由 `Project.arch` 挂在同一份工程文件里随存随取,**暂不与时序图互通** +/// (不引用工位 / 动作,也不参与节拍计算)。 +/// +/// 约定: +/// - 颜色以 32 位 ARGB 整数保存,序列化为 8 位十六进制 `#aarrggbb`(保留透明度, +/// 因为架构图要用「半透明填充 + 实色描边」的画法); +/// - 所有几何均为「世界坐标」(画布坐标),缩放 / 平移由 [ArchDoc.zoom]/[ArchDoc.panX] +/// / [ArchDoc.panY] 描述; +/// - 所有模型提供 copyWith / toJson / fromJson,保证 JSON 往返。 +library; + +import 'dart:convert'; +import 'dart:math' as math; +import 'dart:ui' show Offset, Path, Rect, Size; + +import '../sketch/sketch_models.dart'; + +/// 架构图画布当前工具。 +enum ArchTool { + /// 选择 / 移动 / 缩放。 + select, + + /// 手绘(松开自动识别成标准图形)。 + pen, + + /// 连线(从一个图形拖到另一个图形,自动吸附并跟随移动)。 + connect, +} + +/// 连线走线方式。 +enum ArchRoute { + /// 直线。 + straight, + + /// 正交折线(横平竖直走线)。 + ortho, +} + +/// 对齐 / 均布方式(PPT 风格;作用于多选图形,以选中范围为参照)。 +enum ArchAlign { + /// 左对齐。 + left, + + /// 横向居中对齐。 + hCenter, + + /// 右对齐。 + right, + + /// 顶对齐。 + top, + + /// 纵向居中对齐。 + vCenter, + + /// 底对齐。 + bottom, + + /// 横向均布(至少 3 个)。 + distributeH, + + /// 纵向均布(至少 3 个)。 + distributeV, +} + +/// 架构图标准图形类型。 +enum ArchShapeType { + /// 矩形。 + rect, + + /// 圆角矩形。 + roundRect, + + /// 椭圆。 + ellipse, + + /// 圆形。 + circle, + + /// 三角形([ArchShape.dir] 控制朝向:0 上 / 1 右 / 2 下 / 3 左)。 + triangle, + + /// 菱形。 + diamond, + + /// 圆柱(数据库 / 存储的标准画法)。 + cylinder, + + /// 云(外部系统 / 云端)。 + cloud, + + /// 六边形。 + hexagon, + + /// 纯文本(无边框)。 + text, + + /// 直线 / 箭头(用 [ArchShape.a]、[ArchShape.b]、[ArchShape.arrow] 描述)。 + line, + + /// 折线(用 [ArchShape.pts] 描述顶点;近水平 / 垂直的段会自动扶正)。 + polyline, + + /// 曲线(样条;用 [ArchShape.pts] 描述通过点,绘制时平滑)。 + curve, + + /// 服务器(IT 系统设计:机架抽屉式)。 + server, + + /// 客户端 / PC(显示器 + 底座)。 + client, + + /// 移动端(手机外形)。 + mobile, + + /// 防火墙(砖墙)。 + firewall, + + /// 交换机(网络设备:端口方块)。 + netSwitch, + + /// 消息队列 / 数据流(管道 + 箭头)。 + queue, + + /// 图元库符号(可扩展;[ArchShape.symbolId] 指向图元库条目)。 + symbol, +} + +/// 可编辑尺寸类型(识别后图形的直接尺寸;不走约束求解器)。 +enum ArchDimKind { + /// 宽度(水平尺寸)。 + width, + + /// 高度(垂直尺寸)。 + height, + + /// 长度(线类图形的路径长度)。 + length, + + /// 直径(圆)。 + diameter, +} + +/// 尺寸类型 JSON 名称。 +String archDimKindName(ArchDimKind k) => switch (k) { + ArchDimKind.width => 'width', + ArchDimKind.height => 'height', + ArchDimKind.length => 'length', + ArchDimKind.diameter => 'diameter', + }; + +/// JSON 名称 → 尺寸类型。 +ArchDimKind archDimKindFrom(String s) => switch (s) { + 'height' => ArchDimKind.height, + 'length' => ArchDimKind.length, + 'diameter' => ArchDimKind.diameter, + _ => ArchDimKind.width, + }; + +/// 尺寸类型中文名。 +String archDimKindLabel(ArchDimKind k) => switch (k) { + ArchDimKind.width => '宽度', + ArchDimKind.height => '高度', + ArchDimKind.length => '长度', + ArchDimKind.diameter => '直径', + }; + +/// 图形适用的尺寸类型(右栏编辑 / 画布标注用)。 +List archShapeDimKinds(ArchShape s) { + if (s.isLinear) { + return const [ + ArchDimKind.length, + ArchDimKind.width, + ArchDimKind.height, + ]; + } + if (s.type == ArchShapeType.circle) { + return const [ArchDimKind.diameter]; + } + return const [ArchDimKind.width, ArchDimKind.height]; +} + +/// 线类图形的外接矩形(pts / a-b)。 +Rect archLinearBounds(ArchShape s) { + if (s.type == ArchShapeType.line && s.a != null && s.b != null) { + return Rect.fromPoints(s.a!, s.b!); + } + if (s.pts.isEmpty) return s.rect; + double l = s.pts.first.dx, r = l, t = s.pts.first.dy, b = t; + for (final Offset p in s.pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + return Rect.fromLTRB(l, t, r, b); +} + +/// 线类图形的路径长度(直线 / 折线 / 曲线按顶点折线近似)。 +double archShapeLength(ArchShape s) { + if (s.type == ArchShapeType.line && s.a != null && s.b != null) { + return (s.b! - s.a!).distance; + } + double len = 0; + for (int i = 1; i < s.pts.length; i++) { + len += (s.pts[i] - s.pts[i - 1]).distance; + } + return len; +} + +/// 测量图形当前尺寸值。 +double archShapeDimValue(ArchShape s, ArchDimKind k) { + switch (k) { + case ArchDimKind.length: + return archShapeLength(s); + case ArchDimKind.diameter: + return s.rect.width; + case ArchDimKind.width: + return s.isLinear ? archLinearBounds(s).width : s.rect.width; + case ArchDimKind.height: + return s.isLinear ? archLinearBounds(s).height : s.rect.height; + } +} + +/// 线类图形按比例缩放(绕外接框中心;[fx]/[fy] 为横纵缩放系数)。 +ArchShape _scaleLinear(ArchShape s, double fx, double fy) { + final Rect b = archLinearBounds(s); + final Offset c0 = b.center; + Offset map(Offset p) => + Offset(c0.dx + (p.dx - c0.dx) * fx, c0.dy + (p.dy - c0.dy) * fy); + if (s.type == ArchShapeType.line && s.a != null && s.b != null) { + final Offset a2 = map(s.a!); + final Offset b2 = map(s.b!); + return s.copyWith(a: a2, b: b2, rect: Rect.fromPoints(a2, b2)); + } + final List pts = [for (final Offset p in s.pts) map(p)]; + if (pts.isEmpty) return s; + double l = pts.first.dx, r = l, t = pts.first.dy, bo = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > bo) bo = p.dy; + } + return s.copyWith(pts: pts, rect: Rect.fromLTRB(l, t, r, bo)); +} + +/// 应用尺寸(直接缩放几何,中心保持;值 <= 0.1 时按 0.1 处理)。 +ArchShape archShapeApplyDim(ArchShape s, ArchDimKind k, double value) { + final double v = value <= 0.1 ? 0.1 : value; + switch (k) { + case ArchDimKind.width: + if (s.isLinear) { + final double w = archLinearBounds(s).width; + return _scaleLinear(s, w <= 1e-6 ? 1 : v / w, 1); + } + return s.copyWith( + rect: Rect.fromCenter( + center: s.rect.center, width: v, height: s.rect.height)); + case ArchDimKind.height: + if (s.isLinear) { + final double h = archLinearBounds(s).height; + return _scaleLinear(s, 1, h <= 1e-6 ? 1 : v / h); + } + return s.copyWith( + rect: Rect.fromCenter( + center: s.rect.center, width: s.rect.width, height: v)); + case ArchDimKind.diameter: + return s.copyWith( + rect: Rect.fromCenter(center: s.rect.center, width: v, height: v)); + case ArchDimKind.length: + final double len = archShapeLength(s); + if (len <= 1e-6) return s; + final double f = v / len; + return _scaleLinear(s, f, f); + } +} + +/// 尺寸标签锚点(世界坐标;屏幕恒定间距由 [zoom] 折算)。 +Offset archShapeDimLabelPos( + ArchShape s, + ArchDimKind k, + int index, + double zoom, +) { + final double z = zoom <= 0.05 ? 1 : zoom; + final double gap = 17 / z; + final Rect b = s.isLinear ? archLinearBounds(s) : s.rect; + final bool wide = + s.type == ArchShapeType.line || s.type == ArchShapeType.curve; + return Offset( + b.center.dx + (wide ? gap * 0.9 : 0), + b.bottom + gap * (index + 0.8), + ); +} + +/// 命中的尺寸标签(双击编辑用);未命中返回 null。 +(ArchShape, ArchDimKind)? archShapeDimHitAt( + ArchDoc doc, + Offset p, + double zoom, +) { + final double z = zoom <= 0.05 ? 1 : zoom; + final double tol = 14 / z + 6; + for (final ArchShape s in doc.shapes) { + if (!doc.isLayerVisible(s.layerId)) continue; + final List kinds = [ + for (final ArchDimKind k in archShapeDimKinds(s)) + if (s.dims.contains(k)) k, + ]; + for (int i = 0; i < kinds.length; i++) { + final Offset a = archShapeDimLabelPos(s, kinds[i], i, z); + if ((p - a).distance <= tol) return (s, kinds[i]); + } + } + return null; +} + +/// 默认画布(图纸)尺寸:A0 横放(1189 × 841 mm;1 世界单位 = 1 mm)。 +const Size kArchPageSize = Size(1189, 841); + +/// 图形类型的中文名(界面展示用)。 +String archShapeTypeLabel(ArchShapeType t) { + switch (t) { + case ArchShapeType.rect: + return '矩形'; + case ArchShapeType.roundRect: + return '圆角矩形'; + case ArchShapeType.ellipse: + return '椭圆'; + case ArchShapeType.circle: + return '圆形'; + case ArchShapeType.triangle: + return '三角形'; + case ArchShapeType.diamond: + return '菱形'; + case ArchShapeType.cylinder: + return '圆柱'; + case ArchShapeType.cloud: + return '云'; + case ArchShapeType.hexagon: + return '六边形'; + case ArchShapeType.text: + return '文本'; + case ArchShapeType.line: + return '直线'; + case ArchShapeType.polyline: + return '折线'; + case ArchShapeType.curve: + return '曲线'; + case ArchShapeType.server: + return '服务器'; + case ArchShapeType.client: + return '客户端(PC)'; + case ArchShapeType.mobile: + return '移动端'; + case ArchShapeType.firewall: + return '防火墙'; + case ArchShapeType.netSwitch: + return '交换机'; + case ArchShapeType.queue: + return '消息队列'; + case ArchShapeType.symbol: + return '图元'; + } +} + +/// 图形库中新图形的默认尺寸(世界坐标 px)。 +Size archDefaultSize(ArchShapeType t) { + switch (t) { + case ArchShapeType.circle: + return const Size(120, 120); + case ArchShapeType.ellipse: + return const Size(160, 96); + case ArchShapeType.triangle: + return const Size(140, 116); + case ArchShapeType.diamond: + return const Size(160, 116); + case ArchShapeType.cylinder: + return const Size(132, 136); + case ArchShapeType.cloud: + return const Size(184, 126); + case ArchShapeType.text: + return const Size(200, 48); + case ArchShapeType.line: + return const Size(180, 0); + case ArchShapeType.polyline: + case ArchShapeType.curve: + return const Size(180, 80); + case ArchShapeType.rect: + case ArchShapeType.roundRect: + case ArchShapeType.hexagon: + return const Size(176, 88); + case ArchShapeType.server: + return const Size(104, 132); + case ArchShapeType.client: + return const Size(152, 118); + case ArchShapeType.mobile: + return const Size(76, 132); + case ArchShapeType.firewall: + return const Size(160, 76); + case ArchShapeType.netSwitch: + return const Size(176, 68); + case ArchShapeType.queue: + return const Size(184, 72); + case ArchShapeType.symbol: + return const Size(120, 120); + } +} + +/// 架构图默认调色板(与整体应用视觉一致,ARGB)。 +const List kArchPalette = [ + 0xFF4CC9F0, // 钢蓝 + 0xFF34D399, // 绿 + 0xFFFFD166, // 琥珀 + 0xFFFF8A5C, // 橙 + 0xFFF472B6, // 粉 + 0xFFA78BFA, // 紫 + 0xFF38BDF8, // 天蓝 + 0xFF94A3B8, // 灰蓝 +]; + +/// 架构图连线的默认颜色(中性蓝灰,深浅主题下都清晰)。 +const int kArchConnectorColor = 0xFF7C8DA6; + +/// 把 32 位 ARGB 序列化为 `#aarrggbb`(保留透明度通道)。 +String archColorHex(int argb) => + '#${(argb & 0xFFFFFFFF).toRadixString(16).padLeft(8, '0')}'; + +/// 解析 `#aarrggbb` / `#rrggbb` / `#rgb` 为 ARGB 整数;失败时回退 [fallback]。 +int archHexColor(Object? hex, {int fallback = 0xFF4CC9F0}) { + if (hex is! String) return fallback; + final String h = hex.replaceAll('#', '').trim(); + final int? v = int.tryParse(h, radix: 16); + if (v == null) return fallback; + if (h.length <= 6) return 0xFF000000 | (v & 0xFFFFFF); + return v & 0xFFFFFFFF; +} + +/// 由主色派生默认填充色(低透明度,深浅主题下都呈「浅色块 + 实色描边」)。 +int archFillOf(int color, {int alpha = 0x26}) => + (alpha << 24) | (color & 0xFFFFFF); + +/// 生成架构图内不重复的 id(如 `S3` / `C2` / `K5`)。 +String archNewId(String prefix, Iterable existing) { + final Set used = existing.toSet(); + int n = 1; + while (used.contains('$prefix$n')) { + n++; + } + return '$prefix$n'; +} + +/// 点到线段距离(命中测试用)。 +double archDistToSegment(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.0001) return (p - a).distance; + double t = ((p.dx - a.dx) * ab.dx + (p.dy - a.dy) * ab.dy) / len2; + t = t.clamp(0.0, 1.0); + return (p - (a + ab * t)).distance; +} + +/// 从图形边框上取一点:连线从图形中心指向 [target] 时与边框的交点。 +/// +/// 椭圆 / 圆用归一化椭圆求交;其余图形统一按外接矩形求交(三角形 / 菱形 / +/// 云的边界近似为矩形,视觉上可接受且实现简单)。 +Offset archBorderPoint(ArchShape s, Offset target) { + final Offset c = s.rect.center; + Offset d = target - c; + if (d.distance < 0.001) d = const Offset(1, 0); + if (s.type == ArchShapeType.ellipse || s.type == ArchShapeType.circle) { + final double rx = math.max(1, s.rect.width / 2); + final double ry = math.max(1, s.rect.height / 2); + final double t = 1 / math.sqrt((d.dx / rx) * (d.dx / rx) + (d.dy / ry) * (d.dy / ry)); + return c + d * t; + } + final double hw = math.max(1, s.rect.width / 2); + final double hh = math.max(1, s.rect.height / 2); + final double tx = d.dx.abs() < 0.001 ? double.infinity : hw / d.dx.abs(); + final double ty = d.dy.abs() < 0.001 ? double.infinity : hh / d.dy.abs(); + final double t = math.min(tx, ty); + return c + d * t; +} + +/// 计算连线当前端点:吸附到图形时按「图形中心连线与边框的交点」实时计算, +/// 因此移动图形后连线自动跟随([override] 供拖拽预览替换图形几何)。 +(Offset, Offset) archConnectorEnds( + ArchDoc doc, + ArchConnector c, { + ArchShape? Function(ArchShape)? override, +}) { + final ArchConnGeometry g = archConnectorGeometry(doc, c, override: override); + return (g.start, g.end); +} + +/// 网格吸附:把点吸附到最近网格点(关闭吸附或粒度 <= 1 时原样返回)。 +Offset archSnapPoint(ArchDoc doc, Offset p) { + if (!doc.gridSnap || doc.gridSize <= 1) return p; + final double g = doc.gridSize; + return Offset( + (p.dx / g).roundToDouble() * g, + (p.dy / g).roundToDouble() * g, + ); +} + +/// 移动吸附结果:校正后的位移 + 磁力对齐线(世界坐标,null 表示该轴无对齐)。 +typedef ArchMoveSnap = ({Offset delta, double? guideX, double? guideY}); + +/// 计算移动时的吸附位移: +/// - **磁力对齐**:移动集合(并集外框)的左 / 中 / 右与其它图形的左 / 中 / 右 +/// 在 [tol](世界像素)内接近时,吸附对齐并返回虚线导引位置; +/// - 未命中的轴回退到**网格吸附**(以主选中图形为准)。 +ArchMoveSnap archSnapMoveDelta({ + required ArchDoc doc, + required Set movingIds, + required Rect union, + required Offset rawDelta, + required double tol, + required bool gridSnap, +}) { + double? guideX; + double? guideY; + double? matchCandX; + double? matchCandY; + double bestDX = double.infinity; + double bestDY = double.infinity; + for (final ArchShape o in doc.shapes) { + if (movingIds.contains(o.id)) continue; + final Rect b = o.bounds; + for (final double cand in [ + union.left, + union.center.dx, + union.right, + ]) { + for (final double t in [b.left, b.center.dx, b.right]) { + final double d = (t - cand).abs(); + if (d <= tol && d < bestDX) { + bestDX = d; + guideX = t; + matchCandX = cand; + } + } + } + for (final double cand in [ + union.top, + union.center.dy, + union.bottom, + ]) { + for (final double t in [b.top, b.center.dy, b.bottom]) { + final double d = (t - cand).abs(); + if (d <= tol && d < bestDY) { + bestDY = d; + guideY = t; + matchCandY = cand; + } + } + } + } + double dx = rawDelta.dx; + double dy = rawDelta.dy; + if (guideX != null && matchCandX != null) { + dx = rawDelta.dx + (guideX - matchCandX); + } + if (guideY != null && matchCandY != null) { + dy = rawDelta.dy + (guideY - matchCandY); + } + if (gridSnap) { + final ArchShape? primary = + doc.shapeById(movingIds.isEmpty ? null : movingIds.first); + if (primary != null) { + final Offset targetTL = primary.rect.topLeft + rawDelta; + final Offset snappedTL = archSnapPoint(doc, targetTL); + final Offset snapDelta = snappedTL - primary.rect.topLeft; + if (guideX == null) dx = snapDelta.dx; + if (guideY == null) dy = snapDelta.dy; + } + } + return (delta: Offset(dx, dy), guideX: guideX, guideY: guideY); +} + +/// 连线走线的几何结果:折点序列 + 平滑路径 + 标签锚点。 +class ArchConnGeometry { + /// 构造几何结果。 + const ArchConnGeometry(this.pts, this.path, this.label); + + /// 折点序列(起 → 中间折点 → 止)。 + final List pts; + + /// 绘制路径(正交折线的中间折点带圆角)。 + final Path path; + + /// 标签锚点(最长段的中点)。 + final Offset label; + + /// 起点。 + Offset get start => pts.first; + + /// 终点。 + Offset get end => pts.last; +} + +/// 图形边界上距 [p] 最近的点(连线「开始 / 结束」吸附用)。 +/// +/// 椭圆 / 圆按径向投影到边界;矩形类(含圆角矩形 / 多边形 / 云 / 圆柱) +/// 取外接矩形边界上的最近点(外部点 clamp、内部点投影到最近一条边)。 +Offset archNearestBorderPoint(ArchShape s, Offset p) { + final Rect r = s.rect; + if (s.type == ArchShapeType.ellipse || s.type == ArchShapeType.circle) { + final double rx = math.max(1, r.width / 2); + final double ry = math.max(1, r.height / 2); + final Offset d = p - r.center; + if (d.distance < 0.001) return Offset(r.right, r.center.dy); + final double t = + 1 / math.sqrt((d.dx / rx) * (d.dx / rx) + (d.dy / ry) * (d.dy / ry)); + return r.center + d * t; + } + if (r.contains(p)) { + final double dl = (p.dx - r.left).abs(); + final double dr = (r.right - p.dx).abs(); + final double dt = (p.dy - r.top).abs(); + final double db = (r.bottom - p.dy).abs(); + final double m = math.min(math.min(dl, dr), math.min(dt, db)); + if (m == dl) return Offset(r.left, p.dy); + if (m == dr) return Offset(r.right, p.dy); + if (m == dt) return Offset(p.dx, r.top); + return Offset(p.dx, r.bottom); + } + return Offset(p.dx.clamp(r.left, r.right), p.dy.clamp(r.top, r.bottom)); +} + +/// 计算连线几何:直线端点为「创建时吸附的最近边缘点」在当前图形上的投影; +/// [ArchRoute.ortho] 时自动生成横平竖直的正交折线(带圆角)。 +ArchConnGeometry archConnectorGeometry( + ArchDoc doc, + ArchConnector c, { + ArchShape? Function(ArchShape)? override, +}) { + ArchShape? resolve(String? id) { + final ArchShape? s = doc.shapeById(id); + if (s == null) return null; + return override == null ? s : override(s); + } + + final ArchShape? sf = resolve(c.fromId); + final ArchShape? st = resolve(c.toId); + final Offset cFrom = sf?.rect.center ?? c.from; + final Offset cTo = st?.rect.center ?? c.to; + + if (c.route == ArchRoute.ortho) { + return _orthoGeometry(sf, st, cFrom, cTo, c.from, c.to); + } + + final Offset a = sf == null ? c.from : archNearestBorderPoint(sf, c.from); + final Offset b = st == null ? c.to : archNearestBorderPoint(st, c.to); + // 手画折线:经过识别出的中间折点。 + final List raw = [a, ...c.mids, b]; + final List clean = []; + for (final Offset p in raw) { + if (clean.isEmpty || (p - clean.last).distance > 0.5) clean.add(p); + } + if (clean.length < 2) { + clean + ..clear() + ..addAll([a, b]); + } + final Path path = Path()..moveTo(clean.first.dx, clean.first.dy); + for (int i = 1; i < clean.length; i++) { + path.lineTo(clean[i].dx, clean[i].dy); + } + return ArchConnGeometry(clean, path, _labelPoint(clean)); +} + +/// 正交走线:按两图形中心的主方向决定「先横后竖 / 先竖后横」, +/// 端点从相应方向的边框射出,中间折一次。 +ArchConnGeometry _orthoGeometry( + ArchShape? sf, + ArchShape? st, + Offset cFrom, + Offset cTo, + Offset freeFrom, + Offset freeTo, +) { + final bool horizontalFirst = + (cTo.dx - cFrom.dx).abs() >= (cTo.dy - cFrom.dy).abs(); + Offset a; + Offset b; + if (horizontalFirst) { + a = sf == null + ? freeFrom + : archBorderPoint( + sf, + Offset( + cTo.dx >= cFrom.dx ? sf.rect.right + 1e5 : sf.rect.left - 1e5, + cFrom.dy, + ), + ); + b = st == null + ? freeTo + : archBorderPoint( + st, + Offset( + cTo.dx >= cFrom.dx ? st.rect.left - 1e5 : st.rect.right + 1e5, + cTo.dy, + ), + ); + } else { + a = sf == null + ? freeFrom + : archBorderPoint( + sf, + Offset( + cFrom.dx, + cTo.dy >= cFrom.dy ? sf.rect.bottom + 1e5 : sf.rect.top - 1e5, + ), + ); + b = st == null + ? freeTo + : archBorderPoint( + st, + Offset( + cTo.dx, + cTo.dy >= cFrom.dy ? st.rect.top - 1e5 : st.rect.bottom + 1e5, + ), + ); + } + final List pts = horizontalFirst + ? [a, Offset(b.dx, a.dy), b] + : [a, Offset(a.dx, b.dy), b]; + final List clean = []; + for (final Offset p in pts) { + if (clean.isEmpty || (p - clean.last).distance > 0.5) clean.add(p); + } + return ArchConnGeometry( + clean, + _roundedOrthoPath(clean, 8), + _labelPoint(clean), + ); +} + +/// 标签锚点:最长段的中点。 +Offset _labelPoint(List pts) { + double best = -1; + Offset mid = pts.first; + for (int i = 0; i < pts.length - 1; i++) { + final double len = (pts[i + 1] - pts[i]).distance; + if (len > best) { + best = len; + mid = (pts[i] + pts[i + 1]) / 2; + } + } + return mid; +} + +/// 正交折线路径:中间折点用圆角过渡。 +Path _roundedOrthoPath(List pts, double radius) { + final Path path = Path()..moveTo(pts.first.dx, pts.first.dy); + for (int i = 1; i < pts.length - 1; i++) { + final Offset prev = pts[i - 1]; + final Offset cur = pts[i]; + final Offset next = pts[i + 1]; + final double d1 = (cur - prev).distance; + final double d2 = (next - cur).distance; + if (d1 < 0.001 || d2 < 0.001) continue; + final double r = math.min(radius, math.min(d1, d2) * 0.4); + if (r < 0.5) { + path.lineTo(cur.dx, cur.dy); + continue; + } + final Offset p1 = cur - (cur - prev) / d1 * r; + final Offset p2 = cur + (next - cur) / d2 * r; + path.lineTo(p1.dx, p1.dy); + path.quadraticBezierTo(cur.dx, cur.dy, p2.dx, p2.dy); + } + path.lineTo(pts.last.dx, pts.last.dy); + return path; +} + +/// 图形默认归属图层 id:空串表示「未指定」→ 由控制器补充为当前活动图层。 +const String kArchDefaultLayerId = ''; + +/// 架构图图层(AutoCAD 风格):名称 / 颜色 / 可见 / 锁定。 +class ArchLayer { + /// 构造图层。 + const ArchLayer({ + required this.id, + required this.name, + required this.color, + this.visible = true, + this.locked = false, + }); + + /// 唯一标识(如 `L0` / `LY2`)。 + final String id; + + /// 图层名称。 + final String name; + + /// 图层颜色(ARGB;用于色块展示与新建图形的默认取色)。 + final int color; + + /// 是否可见(隐藏后不绘制、不可选、不可吸附)。 + final bool visible; + + /// 是否锁定(可见但不可选 / 不可移动;仍可作为吸附参照)。 + final bool locked; + + /// 默认图层(旧文件 / 未指定归属时的兜底)。 + static const ArchLayer fallback = ArchLayer( + id: 'L0', + name: '默认图层', + color: 0xFF4CC9F0, + ); + + /// 复制并覆盖部分字段。 + ArchLayer copyWith({ + String? id, + String? name, + int? color, + bool? visible, + bool? locked, + }) { + return ArchLayer( + id: id ?? this.id, + name: name ?? this.name, + color: color ?? this.color, + visible: visible ?? this.visible, + locked: locked ?? this.locked, + ); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'id': id, + 'name': name, + 'c': archColorHex(color), + if (!visible) 'vis': false, + if (locked) 'lok': true, + }; + + /// 从 JSON 反序列化。 + static ArchLayer fromJson(Map j) { + return ArchLayer( + id: j['id'] as String? ?? 'L0', + name: j['name'] as String? ?? '图层', + color: archHexColor(j['c'], fallback: 0xFF4CC9F0), + visible: j['vis'] as bool? ?? true, + locked: j['lok'] as bool? ?? false, + ); + } +} + +/// 正交 / 极轴约束:把移动位移约束到主轴(正交)或极轴角度(极轴)。 +Offset archConstrainDelta({ + required Offset raw, + required bool ortho, + required bool polar, + required double polarDeg, +}) { + if (ortho) { + return raw.dx.abs() >= raw.dy.abs() + ? Offset(raw.dx, 0) + : Offset(0, raw.dy); + } + if (polar) { + final double len = raw.distance; + if (len < 1.5) return raw; + final double step = math.max(1.0, polarDeg) * math.pi / 180; + final double ang = (math.atan2(raw.dy, raw.dx) / step).round() * step; + return Offset(math.cos(ang) * len, math.sin(ang) * len); + } + return raw; +} + +/// 架构图标准图形(矩形 / 圆 / 云 / 圆柱……;[ArchShapeType.line] 直线 / 箭头)。 +class ArchShape { + /// 构造一个图形。 + const ArchShape({ + required this.id, + required this.type, + required this.rect, + this.radius = 0, + this.dir = 0, + this.a, + this.b, + this.arrow = false, + this.fill = 0x264CC9F0, + this.stroke = 0xFF4CC9F0, + this.sw = 1.8, + this.text = '', + this.pts = const [], + this.layerId = kArchDefaultLayerId, + this.symbolId = '', + this.dims = const {}, + }); + + /// 唯一标识(如 `S1`)。 + final String id; + + /// 图形类型。 + final ArchShapeType type; + + /// 外接矩形(世界坐标)。 + final Rect rect; + + /// 圆角半径(仅 [ArchShapeType.roundRect] 使用)。 + final double radius; + + /// 朝向(仅三角形使用):0 上 / 1 右 / 2 下 / 3 左。 + final int dir; + + /// 直线起点(仅 [ArchShapeType.line] 使用)。 + final Offset? a; + + /// 直线终点(仅 [ArchShapeType.line] 使用)。 + final Offset? b; + + /// 是否为箭头(仅 [ArchShapeType.line] 使用)。 + final bool arrow; + + /// 填充色(ARGB,默认半透明主色)。 + final int fill; + + /// 描边色(ARGB)。 + final int stroke; + + /// 描边宽度(世界像素)。 + final double sw; + + /// 图内文字(多行以 `\n` 分隔)。 + final String text; + + /// 折线 / 曲线的通过点(世界坐标;[ArchShapeType.polyline] / [ArchShapeType.curve])。 + final List pts; + + /// 所属图层 id(空串 = 未指定,由控制器补充为当前活动图层)。 + final String layerId; + + /// 图元库符号 id(仅 [ArchShapeType.symbol] 使用;空串 = 未指定)。 + final String symbolId; + + /// 画布上标注的尺寸类型(识别后图形可直接改值缩放,见 [archShapeApplyDim])。 + final Set dims; + + /// 是否为「线类」图形(直线 / 箭头 / 折线 / 曲线)。 + bool get isLinear => + type == ArchShapeType.line || + type == ArchShapeType.polyline || + type == ArchShapeType.curve; + + /// 命中范围(用于选择与删除判定)。 + Rect get bounds { + if (type == ArchShapeType.line && a != null && b != null) { + return Rect.fromPoints(a!, b!).inflate(6); + } + if (pts.isNotEmpty) { + double l = pts.first.dx, r = l, t = pts.first.dy, b = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + return Rect.fromLTRB(l, t, r, b).inflate(6); + } + return rect; + } + + /// 点 [p] 是否命中本图形([pad] 为宽容度)。 + bool hitTest(Offset p, {double pad = 2}) { + if (isLinear) { + final List line = isLinear ? _linePoints() : const []; + if (line.length < 2) return false; + final double tol = math.max(8, sw + 4) + pad; + for (int i = 0; i < line.length - 1; i++) { + if (archDistToSegment(p, line[i], line[i + 1]) <= tol) return true; + } + return false; + } + if (type == ArchShapeType.ellipse || type == ArchShapeType.circle) { + final double rx = math.max(1, rect.width / 2); + final double ry = math.max(1, rect.height / 2); + final double nx = (p.dx - rect.center.dx) / rx; + final double ny = (p.dy - rect.center.dy) / ry; + return nx * nx + ny * ny <= 1.18; + } + return rect.inflate(pad).contains(p); + } + + /// 线类图形的折线点列(命中测试与范围计算用)。 + List _linePoints() { + if (type == ArchShapeType.line) { + final Offset? p1 = a; + final Offset? p2 = b; + return p1 == null || p2 == null ? const [] : [p1, p2]; + } + return pts; + } + + /// 复制并覆盖部分字段。 + ArchShape copyWith({ + String? id, + ArchShapeType? type, + Rect? rect, + double? radius, + int? dir, + Offset? a, + Offset? b, + bool? arrow, + int? fill, + int? stroke, + double? sw, + String? text, + List? pts, + String? layerId, + String? symbolId, + Set? dims, + }) { + return ArchShape( + id: id ?? this.id, + type: type ?? this.type, + rect: rect ?? this.rect, + radius: radius ?? this.radius, + dir: dir ?? this.dir, + a: a ?? this.a, + b: b ?? this.b, + arrow: arrow ?? this.arrow, + fill: fill ?? this.fill, + stroke: stroke ?? this.stroke, + sw: sw ?? this.sw, + text: text ?? this.text, + pts: pts ?? this.pts, + layerId: layerId ?? this.layerId, + symbolId: symbolId ?? this.symbolId, + dims: dims ?? this.dims, + ); + } + + /// 平移图形(线类图形同时平移端点 / 经过点)。 + ArchShape translated(Offset d) { + if (type == ArchShapeType.line && a != null && b != null) { + return copyWith(a: a! + d, b: b! + d, rect: rect.shift(d)); + } + if (pts.isNotEmpty) { + return copyWith( + pts: [for (final Offset p in pts) p + d], + rect: rect.shift(d), + ); + } + return copyWith(rect: rect.shift(d)); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'id': id, + 't': type.name, + 'x': rect.left, + 'y': rect.top, + 'w': rect.width, + 'h': rect.height, + if (radius != 0) 'r': radius, + if (dir != 0) 'dir': dir, + if (a != null) 'ax': a!.dx, + if (a != null) 'ay': a!.dy, + if (b != null) 'bx': b!.dx, + if (b != null) 'by': b!.dy, + if (arrow) 'arw': true, + 'f': archColorHex(fill), + 's': archColorHex(stroke), + 'sw': sw, + if (text.isNotEmpty) 'txt': text, + if (pts.isNotEmpty) + 'pts': [for (final Offset p in pts) ...[p.dx, p.dy]], + if (layerId.isNotEmpty) 'ly': layerId, + if (symbolId.isNotEmpty) 'sy': symbolId, + if (dims.isNotEmpty) + 'dim': [ + for (final ArchDimKind k in dims) archDimKindName(k), + ], + }; + + /// 从 JSON 反序列化(字段缺失时使用安全默认值)。 + static ArchShape fromJson(Map j) { + final double x = (j['x'] as num?)?.toDouble() ?? 0; + final double y = (j['y'] as num?)?.toDouble() ?? 0; + final double w = (j['w'] as num?)?.toDouble() ?? 100; + final double h = (j['h'] as num?)?.toDouble() ?? 60; + final ArchShapeType type = ArchShapeType.values.firstWhere( + (ArchShapeType t) => t.name == j['t'], + orElse: () => ArchShapeType.rect, + ); + final List flat = (j['pts'] as List?) ?? []; + final List pts = []; + for (int i = 0; i + 1 < flat.length; i += 2) { + pts.add(Offset( + (flat[i] as num).toDouble(), + (flat[i + 1] as num).toDouble(), + )); + } + return ArchShape( + id: j['id'] as String? ?? 'S?', + type: type, + rect: Rect.fromLTWH(x, y, w, h), + radius: (j['r'] as num?)?.toDouble() ?? 0, + dir: (j['dir'] as num?)?.toInt() ?? 0, + a: j['ax'] == null + ? null + : Offset((j['ax'] as num).toDouble(), (j['ay'] as num?)?.toDouble() ?? 0), + b: j['bx'] == null + ? null + : Offset((j['bx'] as num).toDouble(), (j['by'] as num?)?.toDouble() ?? 0), + arrow: j['arw'] as bool? ?? false, + fill: archHexColor(j['f'], fallback: 0x264CC9F0), + stroke: archHexColor(j['s']), + sw: (j['sw'] as num?)?.toDouble() ?? 1.8, + text: j['txt'] as String? ?? '', + pts: pts, + layerId: j['ly'] as String? ?? kArchDefaultLayerId, + symbolId: j['sy'] as String? ?? '', + dims: { + for (final dynamic e in (j['dim'] as List?) ?? []) + archDimKindFrom(e.toString()), + }, + ); + } +} + +/// 一段手绘墨迹(未识别或关闭识别时保留的原始笔迹)。 +class ArchStroke { + /// 构造一段墨迹。 + const ArchStroke({ + required this.id, + required this.pts, + this.color = 0xFF4CC9F0, + this.w = 2.2, + this.layerId = kArchDefaultLayerId, + }); + + /// 唯一标识(如 `K1`)。 + final String id; + + /// 笔迹采样点(世界坐标)。 + final List pts; + + /// 颜色(ARGB)。 + final int color; + + /// 线宽(世界像素)。 + final double w; + + /// 所属图层 id(空串 = 未指定)。 + final String layerId; + + /// 笔迹外接矩形。 + Rect get bounds { + if (pts.isEmpty) return Rect.zero; + double l = pts.first.dx, r = l, t = pts.first.dy, b = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + return Rect.fromLTRB(l, t, r, b); + } + + /// 点 [p] 是否命中了这段笔迹。 + bool hitTest(Offset p, {double pad = 4}) { + if (pts.length < 2) return pts.isNotEmpty && (pts.first - p).distance <= 8; + for (int i = 0; i < pts.length - 1; i++) { + if (archDistToSegment(p, pts[i], pts[i + 1]) <= math.max(6, w + pad)) { + return true; + } + } + return false; + } + + /// 复制并覆盖部分字段。 + ArchStroke copyWith({String? id, List? pts, int? color, double? w, String? layerId}) { + return ArchStroke( + id: id ?? this.id, + pts: pts ?? this.pts, + color: color ?? this.color, + w: w ?? this.w, + layerId: layerId ?? this.layerId, + ); + } + + /// 序列化为 JSON;点列表压平为 `[x1,y1,x2,y2,...]`。 + Map toJson() => { + 'id': id, + 'pts': [for (final Offset p in pts) ...[p.dx, p.dy]], + 'c': archColorHex(color), + 'w': w, + if (layerId.isNotEmpty) 'ly': layerId, + }; + + /// 从 JSON 反序列化。 + static ArchStroke fromJson(Map j) { + final List flat = (j['pts'] as List?) ?? []; + final List pts = []; + for (int i = 0; i + 1 < flat.length; i += 2) { + pts.add(Offset( + (flat[i] as num).toDouble(), + (flat[i + 1] as num).toDouble(), + )); + } + return ArchStroke( + id: j['id'] as String? ?? 'K?', + pts: pts, + color: archHexColor(j['c'], fallback: 0xFF4CC9F0), + w: (j['w'] as num?)?.toDouble() ?? 2.2, + layerId: j['ly'] as String? ?? kArchDefaultLayerId, + ); + } +} + +/// 架构图连线:连接两个图形(或自由端点),带箭头与可选标签。 +/// +/// [fromId]/[toId] 非空时表示吸附在对应图形上:端点每次绘制时按「图形中心 +/// 连线与边框的交点」实时计算,因此移动图形后连线自动跟随。 +/// [route] 控制走线:直线或正交折线。 +class ArchConnector { + /// 构造一条连线。 + const ArchConnector({ + required this.id, + this.fromId, + required this.from, + this.toId, + required this.to, + this.label = '', + this.dash = false, + this.color = kArchConnectorColor, + this.route = ArchRoute.straight, + this.mids = const [], + this.layerId = kArchDefaultLayerId, + }); + + /// 唯一标识(如 `C1`)。 + final String id; + + /// 起点吸附的图形 id(null 表示自由端点)。 + final String? fromId; + + /// 起点坐标(自由端点或图形缺失时的回退值)。 + final Offset from; + + /// 终点吸附的图形 id(null 表示自由端点)。 + final String? toId; + + /// 终点坐标(自由端点或图形缺失时的回退值)。 + final Offset to; + + /// 连线标签(可为空)。 + final String label; + + /// 是否虚线(云 / 外部系统连接常用)。 + final bool dash; + + /// 颜色(ARGB)。 + final int color; + + /// 走线方式(直线 / 正交折线)。 + final ArchRoute route; + + /// 中间折点(手画连线的轨迹识别结果;端点吸附图形时随图形移动, + /// 折点保持在世界坐标,可继续拖动编辑)。 + final List mids; + + /// 所属图层 id(空串 = 未指定)。 + final String layerId; + + /// 复制并覆盖部分字段。 + ArchConnector copyWith({ + String? id, + Object? fromId = _keep, + Offset? from, + Object? toId = _keep, + Offset? to, + String? label, + bool? dash, + int? color, + ArchRoute? route, + List? mids, + String? layerId, + }) { + return ArchConnector( + id: id ?? this.id, + fromId: identical(fromId, _keep) ? this.fromId : fromId as String?, + from: from ?? this.from, + toId: identical(toId, _keep) ? this.toId : toId as String?, + to: to ?? this.to, + label: label ?? this.label, + dash: dash ?? this.dash, + color: color ?? this.color, + route: route ?? this.route, + mids: mids ?? this.mids, + layerId: layerId ?? this.layerId, + ); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'id': id, + if (fromId != null) 'fi': fromId, + 'fx': from.dx, + 'fy': from.dy, + if (toId != null) 'ti': toId, + 'tx': to.dx, + 'ty': to.dy, + if (label.isNotEmpty) 'lb': label, + if (dash) 'dsh': true, + 'c': archColorHex(color), + if (route != ArchRoute.straight) 'rt': route.name, + if (mids.isNotEmpty) + 'mid': [for (final Offset p in mids) ...[p.dx, p.dy]], + if (layerId.isNotEmpty) 'ly': layerId, + }; + + /// 从 JSON 反序列化。 + static ArchConnector fromJson(Map j) { + final List flat = (j['mid'] as List?) ?? []; + final List mids = []; + for (int i = 0; i + 1 < flat.length; i += 2) { + mids.add(Offset( + (flat[i] as num).toDouble(), + (flat[i + 1] as num).toDouble(), + )); + } + return ArchConnector( + id: j['id'] as String? ?? 'C?', + fromId: j['fi'] as String?, + from: Offset( + (j['fx'] as num?)?.toDouble() ?? 0, + (j['fy'] as num?)?.toDouble() ?? 0, + ), + toId: j['ti'] as String?, + to: Offset( + (j['tx'] as num?)?.toDouble() ?? 0, + (j['ty'] as num?)?.toDouble() ?? 0, + ), + label: j['lb'] as String? ?? '', + dash: j['dsh'] as bool? ?? false, + color: archHexColor(j['c'], fallback: kArchConnectorColor), + route: (j['rt'] as String?) == 'ortho' + ? ArchRoute.ortho + : ArchRoute.straight, + mids: mids, + layerId: j['ly'] as String? ?? kArchDefaultLayerId, + ); + } +} + +/// 哨兵:用于 [ArchConnector.copyWith] 区分「未传参」与「显式置 null」。 +const Object _keep = Object(); + +/// 架构图文档:图形 + 墨迹 + 连线 + 视口,是架构图模块的整体单元。 +/// +/// 通过 `Project.arch` 挂在工程文件里(暂不与时序图互通)。 +class ArchDoc { + /// 构造文档。 + const ArchDoc({ + this.shapes = const [], + this.strokes = const [], + this.connectors = const [], + this.zoom = 1, + this.panX = 0, + this.panY = 0, + this.gridSnap = true, + this.gridSize = 20, + this.layers = const [ArchLayer.fallback], + this.activeLayerId = 'L0', + this.sketch = SketchDoc.empty, + }); + + /// 空文档(新建工程 / 首次进入架构图时的初始状态)。 + static const ArchDoc empty = ArchDoc(); + + /// 图形列表(后添加的绘制在上层)。 + final List shapes; + + /// 墨迹列表(后添加的绘制在上层)。 + final List strokes; + + /// 连线列表。 + final List connectors; + + /// 视口缩放。 + final double zoom; + + /// 视口水平平移。 + final double panX; + + /// 视口垂直平移。 + final double panY; + + /// 是否吸附网格(默认开启;识别 / 移动 / 缩放时对位到网格)。 + final bool gridSnap; + + /// 网格粒度(世界像素,控制点阵间距与吸附步长;默认 20)。 + final double gridSize; + + /// 图层列表(AutoCAD 风格;至少一个)。 + final List layers; + + /// 当前活动图层 id(新建图形 / 墨迹 / 连线的归属)。 + final String activeLayerId; + + /// 参数化草图(点 / 几何 / 约束 / 驱动尺寸)。 + final SketchDoc sketch; + + /// 按 id 查找图层;未找到时返回兜底图层。 + ArchLayer layerById(String? id) { + for (final ArchLayer l in layers) { + if (l.id == id) return l; + } + return layers.isEmpty ? ArchLayer.fallback : layers.first; + } + + /// 当前活动图层 id(不合法时回退到第一个图层)。 + String get activeLayer { + if (activeLayerId.isNotEmpty && + layers.any((ArchLayer l) => l.id == activeLayerId)) { + return activeLayerId; + } + return layers.isEmpty ? ArchLayer.fallback.id : layers.first.id; + } + + /// 图层是否可见(未指定归属视为可见)。 + bool isLayerVisible(String? id) => + id == null || id.isEmpty || layerById(id).visible; + + /// 图层是否锁定(未指定归属视为未锁定)。 + bool isLayerLocked(String? id) => + id != null && id.isNotEmpty && layerById(id).locked; + + /// 是否为空文档(无任何内容)。 + bool get isEmpty => + shapes.isEmpty && + strokes.isEmpty && + connectors.isEmpty && + sketch.isEmpty; + + /// 元素总数(供状态栏展示)。 + int get elementCount => shapes.length + strokes.length + connectors.length; + + /// 按 id 查找图形。 + ArchShape? shapeById(String? id) { + if (id == null) return null; + for (final ArchShape s in shapes) { + if (s.id == id) return s; + } + return null; + } + + /// 按 id 查找墨迹。 + ArchStroke? strokeById(String? id) { + if (id == null) return null; + for (final ArchStroke s in strokes) { + if (s.id == id) return s; + } + return null; + } + + /// 按 id 查找连线。 + ArchConnector? connectorById(String? id) { + if (id == null) return null; + for (final ArchConnector c in connectors) { + if (c.id == id) return c; + } + return null; + } + + /// 所有已用 id(生成新 id 时避免冲突)。 + Iterable get allIds => [ + for (final ArchShape s in shapes) s.id, + for (final ArchStroke s in strokes) s.id, + for (final ArchConnector c in connectors) c.id, + ]; + + /// 内容外接矩形(「适应视图」用);隐藏图层不计入。 + Rect contentBounds() { + double? l, t, r, b; + void include(Rect x) { + l = (l == null || x.left < l!) ? x.left : l; + t = (t == null || x.top < t!) ? x.top : t; + r = (r == null || x.right > r!) ? x.right : r; + b = (b == null || x.bottom > b!) ? x.bottom : b; + } + + for (final ArchShape s in shapes) { + if (!isLayerVisible(s.layerId)) continue; + include(s.bounds); + } + for (final ArchStroke s in strokes) { + if (!isLayerVisible(s.layerId)) continue; + include(s.bounds); + } + for (final ArchConnector c in connectors) { + if (!isLayerVisible(c.layerId)) continue; + include(Rect.fromPoints(c.from, c.to)); + } + final Rect? sk = sketch.contentBounds(); + if (sk != null) include(sk); + if (l == null || t == null || r == null || b == null) { + // 空文档默认按 A0 图纸(1 世界单位 = 1 mm)。 + return Rect.fromLTWH(0, 0, kArchPageSize.width, kArchPageSize.height); + } + return Rect.fromLTRB(l!, t!, r!, b!); + } + + /// 复制并覆盖部分字段。 + ArchDoc copyWith({ + List? shapes, + List? strokes, + List? connectors, + double? zoom, + double? panX, + double? panY, + bool? gridSnap, + double? gridSize, + List? layers, + String? activeLayerId, + SketchDoc? sketch, + }) { + return ArchDoc( + shapes: shapes ?? this.shapes, + strokes: strokes ?? this.strokes, + connectors: connectors ?? this.connectors, + zoom: zoom ?? this.zoom, + panX: panX ?? this.panX, + panY: panY ?? this.panY, + gridSnap: gridSnap ?? this.gridSnap, + gridSize: gridSize ?? this.gridSize, + layers: layers ?? this.layers, + activeLayerId: activeLayerId ?? this.activeLayerId, + sketch: sketch ?? this.sketch, + ); + } + + /// 移除若干 id:图形被移除时,吸附在它上面的连线一并移除。 + ArchDoc removeIds(Set ids) { + final List nextShapes = + shapes.where((ArchShape s) => !ids.contains(s.id)).toList(); + final Set gone = { + for (final ArchShape s in shapes) + if (ids.contains(s.id)) s.id, + }; + final List nextStrokes = + strokes.where((ArchStroke s) => !ids.contains(s.id)).toList(); + final List nextConnectors = connectors + .where((ArchConnector c) => + !ids.contains(c.id) && + !gone.contains(c.fromId) && + !gone.contains(c.toId)) + .toList(); + return copyWith( + shapes: nextShapes, + strokes: nextStrokes, + connectors: nextConnectors, + ); + } + + /// 替换图形(id 相同则原位替换,否则追加到末尾)。 + ArchDoc replaceShape(ArchShape s) { + bool found = false; + final List next = []; + for (final ArchShape x in shapes) { + if (x.id == s.id) { + next.add(s); + found = true; + } else { + next.add(x); + } + } + if (!found) next.add(s); + return copyWith(shapes: next); + } + + /// 序列化为 JSON。 + Map toJson() => { + 'shapes': >[ + for (final ArchShape s in shapes) s.toJson(), + ], + 'strokes': >[ + for (final ArchStroke s in strokes) s.toJson(), + ], + 'connectors': >[ + for (final ArchConnector c in connectors) c.toJson(), + ], + 'zoom': zoom, + 'pan': [panX, panY], + 'gridSnap': gridSnap, + 'gridSize': gridSize, + 'layers': >[ + for (final ArchLayer l in layers) l.toJson(), + ], + 'activeLayer': activeLayerId, + 'sketch': sketch.toJson(), + }; + + /// 序列化为带两空格缩进的 JSON 文本(架构图文档 `*.arch.json` 用)。 + String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); + + /// 从 JSON 文本解码为 [ArchDoc]。 + static ArchDoc decode(String source) => + ArchDoc.fromJson(jsonDecode(source) as Map); + + /// 从 JSON 反序列化(缺失字段使用安全默认值,保证旧文件可加载)。 + static ArchDoc fromJson(Map j) { + final List sh = (j['shapes'] as List?) ?? []; + final List st = (j['strokes'] as List?) ?? []; + final List cn = + (j['connectors'] as List?) ?? []; + final List pan = (j['pan'] as List?) ?? [0, 0]; + return ArchDoc( + shapes: sh + .map((dynamic e) => ArchShape.fromJson(e as Map)) + .toList(), + strokes: st + .map((dynamic e) => ArchStroke.fromJson(e as Map)) + .toList(), + connectors: cn + .map((dynamic e) => ArchConnector.fromJson(e as Map)) + .toList(), + zoom: (j['zoom'] as num?)?.toDouble() ?? 1, + panX: (pan.isNotEmpty ? (pan[0] as num?)?.toDouble() : 0) ?? 0, + panY: (pan.length > 1 ? (pan[1] as num?)?.toDouble() : 0) ?? 0, + gridSnap: j['gridSnap'] as bool? ?? true, + gridSize: (j['gridSize'] as num?)?.toDouble() ?? 20, + layers: (() { + final List ls = (j['layers'] as List?) ?? []; + final List out = ls + .map((dynamic e) => ArchLayer.fromJson(e as Map)) + .toList(); + return out.isEmpty ? const [ArchLayer.fallback] : out; + })(), + activeLayerId: j['activeLayer'] as String? ?? 'L0', + sketch: j['sketch'] == null + ? SketchDoc.empty + : SketchDoc.fromJson(j['sketch'] as Map), + ); + } +} diff --git a/lib/arch/arch_painter.dart b/lib/arch/arch_painter.dart new file mode 100644 index 0000000..b15ba07 --- /dev/null +++ b/lib/arch/arch_painter.dart @@ -0,0 +1,1356 @@ +/// 架构图绘制引擎:标准图形(矩形 / 圆 / 云 / 圆柱 / 折线 / 曲线……)、 +/// 连线(直线 / 正交折线,箭头 + 标签)、手绘墨迹、框选预览、 +/// 「墨迹 → 标准图形」转化动画与多选选中框。 +/// +/// 纯绘制:不持有状态,所有数据经构造函数传入;画布坐标(世界坐标)通过 +/// [ArchDoc.zoom] / [ArchDoc.panX] / [ArchDoc.panY] 变换到屏幕。 +library; + +import 'dart:math' as math; +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 'arch_models.dart'; + +/// 一次「墨迹 → 标准图形」的转化动画记录。 +class ArchConversion { + /// 构造转化记录;[startMs] 为开始时间(毫秒时间戳)。 + ArchConversion({ + required this.pts, + required this.shape, + required this.startMs, + this.undo = true, + this.removeIds = const {}, + }); + + /// 原始笔迹点。 + final List pts; + + /// 识别出的标准图形。 + final ArchShape shape; + + /// 动画开始时间(毫秒时间戳)。 + final double startMs; + + /// 完成后写入文档时是否记录撤销历史。 + final bool undo; + + /// 完成后要移除的元素 id(两笔合并 / 圆柱拼接 / 识别演示批量转化用)。 + final Set removeIds; + + /// 动画时长(毫秒)。 + static const double durMs = 280; + + /// 当前动画进度(0..1)。 + double progress(double nowMs) => + ((nowMs - startMs) / durMs).clamp(0.0, 1.0).toDouble(); +} + +/// 由图形几何构造路径(绘制、墨迹采样、命中测试共用)。 +Path archShapePath(ArchShape s) { + final Rect r = s.rect; + switch (s.type) { + case ArchShapeType.rect: + return Path()..addRect(r); + case ArchShapeType.roundRect: + case ArchShapeType.server: + case ArchShapeType.client: + case ArchShapeType.mobile: + case ArchShapeType.firewall: + case ArchShapeType.netSwitch: + case ArchShapeType.queue: + case ArchShapeType.symbol: + final double rad = switch (s.type) { + ArchShapeType.server => + math.min(12.0, math.min(r.width, r.height) * 0.12), + ArchShapeType.client => math.min(10.0, r.height * 0.08), + ArchShapeType.mobile => math.min(16.0, r.width * 0.22), + ArchShapeType.firewall => math.min(6.0, r.height * 0.10), + ArchShapeType.netSwitch => math.min(10.0, r.height * 0.20), + ArchShapeType.queue => r.height * 0.5, + _ => math.min(s.radius, math.min(r.width, r.height) * 0.45), + }; + return Path() + ..addRRect(RRect.fromRectAndRadius(r, Radius.circular(math.max(0, rad)))); + case ArchShapeType.ellipse: + case ArchShapeType.circle: + return Path()..addOval(r); + case ArchShapeType.triangle: + return _polyPath(archTrianglePoints(s), close: true); + case ArchShapeType.diamond: + return _polyPath(archDiamondPoints(r), close: true); + case ArchShapeType.hexagon: + return _polyPath(archHexagonPoints(r), close: true); + case ArchShapeType.cylinder: + final (Path body, Path lid) = archCylinderPaths(r); + return Path() + ..addPath(body, Offset.zero) + ..addPath(lid, Offset.zero); + case ArchShapeType.cloud: + return archCloudPath(r); + case ArchShapeType.text: + return Path()..addRect(r); + case ArchShapeType.line: + final Offset a = s.a ?? r.topLeft; + final Offset b = s.b ?? r.bottomRight; + return Path() + ..moveTo(a.dx, a.dy) + ..lineTo(b.dx, b.dy); + case ArchShapeType.polyline: + return _polyPath(s.pts, close: false); + case ArchShapeType.curve: + return archSplinePath(s.pts); + } +} + +/// 样条路径:以 [pts] 为通过点做 Catmull-Rom 平滑(转三次贝塞尔)。 +Path archSplinePath(List pts) { + final Path path = Path(); + if (pts.isEmpty) return path; + path.moveTo(pts.first.dx, pts.first.dy); + if (pts.length == 2) { + path.lineTo(pts[1].dx, pts[1].dy); + return path; + } + for (int i = 0; i < pts.length - 1; i++) { + final Offset p0 = i == 0 ? pts[i] : pts[i - 1]; + final Offset p1 = pts[i]; + final Offset p2 = pts[i + 1]; + final Offset p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1]; + final Offset c1 = p1 + (p2 - p0) / 6; + final Offset c2 = p2 - (p3 - p1) / 6; + path.cubicTo(c1.dx, c1.dy, c2.dx, c2.dy, p2.dx, p2.dy); + } + return path; +} + +/// 三角形顶点(按 [ArchShape.dir] 朝向)。 +List archTrianglePoints(ArchShape s) { + final Rect r = s.rect; + switch (s.dir) { + case 1: + return [ + Offset(r.left, r.top), + Offset(r.right, r.center.dy), + Offset(r.left, r.bottom), + ]; + case 2: + return [ + Offset(r.left, r.top), + Offset(r.right, r.top), + Offset(r.center.dx, r.bottom), + ]; + case 3: + return [ + Offset(r.right, r.top), + Offset(r.left, r.center.dy), + Offset(r.right, r.bottom), + ]; + default: + return [ + Offset(r.left, r.bottom), + Offset(r.center.dx, r.top), + Offset(r.right, r.bottom), + ]; + } +} + +/// 菱形顶点(外接矩形四边中点)。 +List archDiamondPoints(Rect r) => [ + Offset(r.center.dx, r.top), + Offset(r.right, r.center.dy), + Offset(r.center.dx, r.bottom), + Offset(r.left, r.center.dy), + ]; + +/// 六边形顶点(长边方向自适应:宽 → 左右尖,高 → 上下尖)。 +List archHexagonPoints(Rect r) { + final double w = r.width; + final double h = r.height; + if (w >= h) { + final double d = w * 0.25; + return [ + Offset(r.left, r.center.dy), + Offset(r.left + d, r.top), + Offset(r.right - d, r.top), + Offset(r.right, r.center.dy), + Offset(r.right - d, r.bottom), + Offset(r.left + d, r.bottom), + ]; + } + final double d = h * 0.25; + return [ + Offset(r.center.dx, r.top), + Offset(r.right, r.top + d), + Offset(r.right, r.bottom - d), + Offset(r.center.dx, r.bottom), + Offset(r.left, r.bottom - d), + Offset(r.left, r.top + d), + ]; +} + +/// 圆柱路径:柱体(含底部弧)+ 顶盖椭圆。 +(Path, Path) archCylinderPaths(Rect r) { + final double ry = math.min(r.height * 0.20, r.width * 0.32); + final double l = r.left; + final double rt = r.right; + final double tp = r.top; + final double bt = r.bottom; + final Path body = Path() + ..moveTo(l, tp + ry) + ..lineTo(l, bt - ry) + ..arcTo(Rect.fromLTRB(l, bt - 2 * ry, rt, bt), math.pi, -math.pi, false) + ..lineTo(rt, tp + ry) + ..close(); + final Path lid = Path()..addOval(Rect.fromLTRB(l, tp, rt, tp + 2 * ry)); + return (body, lid); +} + +/// 云路径:4 个圆弧 + 底座圆角矩形求并集。 +Path archCloudPath(Rect r) { + final double w = r.width; + final double h = r.height; + final double cx = r.left; + final double cy = r.top; + Path acc = Path() + ..addOval(Rect.fromCircle( + center: Offset(cx + w * 0.24, cy + h * 0.62), + radius: h * 0.26, + )); + acc = Path.combine( + PathOperation.union, + acc, + Path() + ..addOval(Rect.fromCircle( + center: Offset(cx + w * 0.42, cy + h * 0.40), + radius: h * 0.30, + )), + ); + acc = Path.combine( + PathOperation.union, + acc, + Path() + ..addOval(Rect.fromCircle( + center: Offset(cx + w * 0.64, cy + h * 0.34), + radius: h * 0.28, + )), + ); + acc = Path.combine( + PathOperation.union, + acc, + Path() + ..addOval(Rect.fromCircle( + center: Offset(cx + w * 0.82, cy + h * 0.58), + radius: h * 0.24, + )), + ); + acc = Path.combine( + PathOperation.union, + acc, + Path() + ..addRRect(RRect.fromRectAndRadius( + Rect.fromLTRB(cx + w * 0.06, cy + h * 0.55, cx + w * 0.94, cy + h * 0.86), + Radius.circular(h * 0.22), + )), + ); + return acc; +} + +/// 平滑折线路径(手绘墨迹用:以中点为锚做二次贝塞尔)。 +Path archSmoothPath(List pts) { + final Path p = Path(); + if (pts.isEmpty) return p; + p.moveTo(pts.first.dx, pts.first.dy); + if (pts.length == 2) { + p.lineTo(pts[1].dx, pts[1].dy); + return p; + } + for (int i = 1; i < pts.length - 1; i++) { + final Offset mid = (pts[i] + pts[i + 1]) / 2; + p.quadraticBezierTo(pts[i].dx, pts[i].dy, mid.dx, mid.dy); + } + p.lineTo(pts.last.dx, pts.last.dy); + return p; +} + +/// 选中手柄(8 个)的世界坐标矩形;顺序:0 左上 / 1 上 / 2 右上 / 3 右 / +/// 4 右下 / 5 下 / 6 左下 / 7 左。 +List archHandleRects(Rect r, double zoom) { + final double z = zoom < 0.05 ? 1 : zoom; + final double s = 8 / z; + final double h = s / 2; + final List cs = [ + r.topLeft, + Offset(r.center.dx, r.top), + r.topRight, + Offset(r.right, r.center.dy), + r.bottomRight, + Offset(r.center.dx, r.bottom), + r.bottomLeft, + Offset(r.left, r.center.dy), + ]; + return [ + for (final Offset c in cs) Rect.fromLTWH(c.dx - h, c.dy - h, s, s), + ]; +} + +/// 架构图画笔:一次绘制完整文档(含草稿 / 框选 / 动画 / 多选)。 +class ArchPainter extends CustomPainter { + /// 构造画笔。 + ArchPainter({ + required this.doc, + required this.t, + this.selectedIds = const {}, + this.conversions = const [], + this.nowMs = 0, + this.draft, + this.penColor = 0xFF4CC9F0, + this.connectPts, + this.connectTargetId, + this.moveDeltas, + this.resizeId, + this.resizeRect, + this.marquee, + this.previewShape, + this.previewConnector, + this.guideXs = const [], + this.guideYs = const [], + this.cursorWorld, + this.showRulers = true, + this.sketchMode = false, + this.sketchSel = const {}, + this.sketchPreview, + this.sketchSnap, + }); + + /// 当前文档。 + final ArchDoc doc; + + /// 主题令牌。 + final Tokens t; + + /// 选中元素 id 集合(图形 / 连线 / 墨迹)。 + final Set selectedIds; + + /// 进行中的转化动画。 + final List conversions; + + /// 当前时间(毫秒时间戳,驱动转化动画)。 + final double nowMs; + + /// 正在手绘的草稿点(世界坐标)。 + final List? draft; + + /// 手绘草稿颜色(ARGB)。 + final int penColor; + + /// 连线拖拽预览的折点(世界坐标)。 + final List? connectPts; + + /// 连线拖拽悬停的目标图形 id。 + final String? connectTargetId; + + /// 多选移动预览:图形 id → 位移。 + final Map? moveDeltas; + + /// 缩放预览:拖拽中的图形 id 与新矩形。 + final String? resizeId; + final Rect? resizeRect; + + /// 框选预览矩形(世界坐标)。 + final Rect? marquee; + + /// 折点拖动预览(覆盖对应图形,用于折线 / 曲线编点)。 + final ArchShape? previewShape; + + /// 连线折点拖动预览(覆盖对应连线)。 + final ArchConnector? previewConnector; + + /// 移动时的磁力对齐虚线(世界坐标 x)。 + final List guideXs; + + /// 移动时的磁力对齐虚线(世界坐标 y)。 + final List guideYs; + + /// 鼠标当前位置(世界坐标;四边标尺上的滑动虚线用)。 + final Offset? cursorWorld; + + /// 是否显示四边标尺。 + final bool showRulers; + + /// 参数化草图模式:只绘制草图内容。 + final bool sketchMode; + + /// 草图选中 id(点 / 实体 / 尺寸)。 + final Set sketchSel; + + /// 草图绘制预览。 + final SketchPreview? sketchPreview; + + /// 草图捕捉标记。 + final Offset? sketchSnap; + + /// 取图形预览(拖拽中应用临时位移 / 尺寸 / 折点)。 + ArchShape _preview(ArchShape s) { + final ArchShape? ps = previewShape; + if (ps != null && ps.id == s.id) return ps; + final Map? deltas = moveDeltas; + if (deltas != null && deltas.containsKey(s.id)) { + return s.translated(deltas[s.id]!); + } + if (resizeId != null && resizeRect != null && s.id == resizeId) { + return s.copyWith(rect: resizeRect); + } + return s; + } + + /// 绘制。 + @override + void paint(Canvas canvas, Size size) { + _grid(canvas, size); + canvas.save(); + canvas.translate(doc.panX, doc.panY); + canvas.scale(doc.zoom); + + if (sketchMode) { + // 参数化草图模式:只显示草图内容(架构图形 / 墨迹 / 连线隐藏)。 + paintSketch(canvas, doc.sketch, t, + sel: sketchSel, preview: sketchPreview, snapMark: sketchSnap); + } else { + // A0 图纸边界(1 世界单位 = 1 mm;浅色描边示意画布范围)。 + canvas.drawRect( + Rect.fromLTWH(0, 0, kArchPageSize.width, kArchPageSize.height), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 / (doc.zoom < 0.05 ? 1 : doc.zoom) + ..color = t.line2, + ); + // 连线在底层(图形遮住线头,视觉更干净;隐藏图层不绘制)。 + for (final ArchConnector c in doc.connectors) { + if (!doc.isLayerVisible(c.layerId)) continue; + _connector(canvas, c); + } + for (final ArchShape s in doc.shapes) { + if (!doc.isLayerVisible(s.layerId)) continue; + _drawShape(canvas, _preview(s)); + } + for (final ArchStroke s in doc.strokes) { + if (!doc.isLayerVisible(s.layerId)) continue; + canvas.drawPath( + archSmoothPath(s.pts), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = s.w + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = Color(s.color), + ); + } + + // 转化动画:墨迹淡出 + 标准图形浮现。 + for (final ArchConversion c in conversions) { + final double p = c.progress(nowMs); + canvas.drawPath( + archSmoothPath(c.pts), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.2 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = Color(c.shape.stroke).withValues(alpha: (1 - p) * 0.9), + ); + canvas.saveLayer( + c.shape.bounds.inflate(12), + Paint()..color = Color.fromARGB((255 * p).round(), 0, 0, 0), + ); + _drawShape(canvas, c.shape); + canvas.restore(); + } + } + + _selection(canvas); + + // 磁力对齐虚线(移动吸附时显示,贯穿当前可视区域)。 + if (guideXs.isNotEmpty || guideYs.isNotEmpty) { + final double z = doc.zoom < 0.05 ? 1 : doc.zoom; + final double x0 = -doc.panX / z; + final double y0 = -doc.panY / z; + final double x1 = (size.width - doc.panX) / z; + final double y1 = (size.height - doc.panY) / z; + final Paint gp = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 / z + ..color = t.accent; + for (final double x in guideXs) { + _dash( + canvas, + Path() + ..moveTo(x, y0) + ..lineTo(x, y1), + gp, + ); + } + for (final double y in guideYs) { + _dash( + canvas, + Path() + ..moveTo(x0, y) + ..lineTo(x1, y), + gp, + ); + } + } + + // 框选预览。 + final Rect? mq = marquee; + if (mq != null) { + canvas.drawRect( + mq, + Paint()..color = t.accent.withValues(alpha: 0.10), + ); + _dash( + canvas, + Path()..addRect(mq), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 / doc.zoom + ..color = t.accent, + ); + } + + // 手绘草稿(实时墨迹)。 + final List? d = draft; + if (d != null && d.length > 1) { + canvas.drawPath( + archSmoothPath(d), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2.2 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = Color(penColor), + ); + } + + // 连线拖拽预览(直线 / 正交)。 + final List? cp = connectPts; + if (cp != null && cp.length >= 2) { + final List clean = []; + for (final Offset p in cp) { + if (clean.isEmpty || (p - clean.last).distance > 0.5) clean.add(p); + } + final Path path = Path()..moveTo(clean.first.dx, clean.first.dy); + for (int i = 1; i < clean.length; i++) { + path.lineTo(clean[i].dx, clean[i].dy); + } + _dash( + canvas, + path, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6 + ..color = t.accent, + ); + if (clean.length >= 2) { + _arrowHead(canvas, clean[clean.length - 2], clean.last, t.accent); + } + final ArchShape? target = doc.shapeById(connectTargetId); + if (target != null) { + canvas.drawPath( + archShapePath(_preview(target)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = t.accent.withValues(alpha: 0.8), + ); + } + } + canvas.restore(); + + // 四边标尺 + 鼠标滑动虚线(屏幕空间,最后绘制覆盖在内容之上)。 + _rulers(canvas, size); + } + + /// 四边标尺 + 鼠标位置实线(Adobe 风格:上标尺 + 右标尺带数字,单位强制 mm)。 + /// + /// 约定:世界坐标 1 单位 = 1 毫米(绘图 / 标尺统一按 mm 显示)。 + void _rulers(Canvas canvas, Size size) { + if (!showRulers) return; + final double z = doc.zoom < 0.05 ? 1 : doc.zoom; + const double band = 16; + final Paint bandPaint = Paint()..color = t.panel.withValues(alpha: 0.94); + final Paint edgePaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = t.line2; + final Paint tickPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = t.dim; + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, band), bandPaint); + canvas.drawRect( + Rect.fromLTWH(0, size.height - band, size.width, band), bandPaint); + canvas.drawRect(Rect.fromLTWH(0, 0, band, size.height), bandPaint); + canvas.drawRect( + Rect.fromLTWH(size.width - band, 0, band, size.height), bandPaint); + + // 主刻度步长:屏幕上约 80px 一格。 + double niceStep(double raw) { + final double mag = math + .pow(10, (math.log(raw) / math.ln10).floorToDouble()) + .toDouble(); + for (final double m in [1, 2, 5, 10]) { + if (mag * m >= raw) return mag * m; + } + return mag * 10; + } + + final double step = niceStep(80 / z); + final double x0 = -doc.panX / z; + final double x1 = (size.width - doc.panX) / z; + final double y0 = -doc.panY / z; + final double y1 = (size.height - doc.panY) / z; + for (double wx = (x0 / step).floorToDouble() * step; wx <= x1; wx += step) { + final double sx = wx * z + doc.panX; + canvas.drawLine(Offset(sx, band - 5), Offset(sx, band), tickPaint); + canvas.drawLine(Offset(sx, size.height - band), + Offset(sx, size.height - band + 5), tickPaint); + // 水平轴:数字在上标尺。 + _rulerLabel(canvas, _fmtMm(wx), Offset(sx + 2, band - 10)); + } + for (double wy = (y0 / step).floorToDouble() * step; wy <= y1; wy += step) { + final double sy = wy * z + doc.panY; + canvas.drawLine(Offset(band - 5, sy), Offset(band, sy), tickPaint); + canvas.drawLine(Offset(size.width - band, sy), + Offset(size.width - band + 5, sy), tickPaint); + // 垂直轴:数字在右标尺(旋转 90°),左侧不显示数字。 + _rulerLabelVertical( + canvas, _fmtMm(wy), size.width - band + 2.5, sy); + } + // 单位徽标(强制 mm):左上角。 + _rulerLabel(canvas, 'mm', const Offset(2, 3)); + + // 鼠标滑动实线:四条标尺上各显示一段(指示当前位置)。 + final Offset? cw = cursorWorld; + if (cw != null) { + final double sx = cw.dx * z + doc.panX; + final double sy = cw.dy * z + doc.panY; + final Paint solid = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 + ..color = t.accent; + canvas.drawLine(Offset(sx, 0), Offset(sx, band), solid); + canvas.drawLine( + Offset(sx, size.height - band), Offset(sx, size.height), solid); + canvas.drawLine(Offset(0, sy), Offset(band, sy), solid); + canvas.drawLine( + Offset(size.width - band, sy), Offset(size.width, sy), solid); + } + + canvas.drawLine(Offset(0, band), Offset(size.width, band), edgePaint); + canvas.drawLine(Offset(0, size.height - band), + Offset(size.width, size.height - band), edgePaint); + canvas.drawLine(Offset(band, 0), Offset(band, size.height), edgePaint); + canvas.drawLine(Offset(size.width - band, 0), + Offset(size.width - band, size.height), edgePaint); + } + + /// 标尺刻度数字。 + void _rulerLabel(Canvas canvas, String s, Offset at) { + _labelPainter(s).paint(canvas, at); + } + + /// 垂直标尺数字(旋转 90°,沿右刻度带向上排布;[centerY] 为刻度线位置)。 + void _rulerLabelVertical( + Canvas canvas, String s, double x, double centerY) { + final TextPainter tp = _labelPainter(s); + canvas.save(); + canvas.translate(x, centerY + tp.width / 2); + canvas.rotate(-math.pi / 2); + tp.paint(canvas, Offset.zero); + canvas.restore(); + } + + /// 标尺数字的文本排版(9px,等宽数字观感)。 + TextPainter _labelPainter(String s) => TextPainter( + text: TextSpan( + text: s, + style: TextStyle( + color: t.sub, + fontSize: 9, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Segoe UI'], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + + /// mm 数值显示:整数不带小数,其余保留一位小数。 + static String _fmtMm(double v) { + if ((v - v.roundToDouble()).abs() < 0.05) return v.round().toString(); + return v.toStringAsFixed(1); + } + + /// 背景点阵(间距 = 文档网格粒度,随缩放自适应避免过密)。 + void _grid(Canvas canvas, Size size) { + final double z = doc.zoom < 0.05 ? 1 : doc.zoom; + double step = doc.gridSize <= 4 ? 0 : doc.gridSize; + if (step <= 0) return; + while (step * z < 9) { + step *= 2; + } + final double x0 = (0 - doc.panX) / z; + final double y0 = (0 - doc.panY) / z; + final double x1 = (size.width - doc.panX) / z; + final double y1 = (size.height - doc.panY) / z; + final Paint dot = Paint()..color = t.grid.withValues(alpha: 0.6); + final double r = 1.1 / z; + for (double x = (x0 / step).floorToDouble() * step; x <= x1; x += step) { + for (double y = (y0 / step).floorToDouble() * step; y <= y1; y += step) { + canvas.drawCircle(Offset(x, y), r, dot); + } + } + } + + /// 服务器(机架抽屉式):外框 + 槽位线 + 状态灯。 + void _drawServer(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Path frame = archShapePath(s); + if (s.fill != 0) canvas.drawPath(frame, fill); + canvas.drawPath(frame, line); + final Color c = Color(s.stroke); + final Paint slot = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(1, s.sw * 0.7) + ..color = c.withValues(alpha: 0.8); + for (int i = 1; i <= 3; i++) { + final double y = r.top + r.height * i / 4; + canvas.drawLine( + Offset(r.left + r.width * 0.10, y), + Offset(r.right - r.width * 0.10, y), + slot, + ); + } + final Paint led = Paint()..color = c.withValues(alpha: 0.85); + for (int i = 0; i < 4; i++) { + final double y = r.top + r.height * (i + 0.5) / 4; + canvas.drawCircle( + Offset(r.left + r.width * 0.16, y), + math.min(2.4, r.width * 0.035), + led, + ); + } + } + + /// 客户端 / PC:显示器 + 支架 + 底座。 + void _drawClient(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Rect screen = + Rect.fromLTWH(r.left, r.top, r.width, r.height * 0.72); + final Path p = Path() + ..addRRect(RRect.fromRectAndRadius( + screen, Radius.circular(math.min(8, screen.height * 0.12)))); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + canvas.drawLine( + Offset(r.center.dx, screen.bottom), + Offset(r.center.dx, r.bottom - r.height * 0.10), + line, + ); + canvas.drawLine( + Offset(r.center.dx - r.width * 0.18, r.bottom - r.height * 0.08), + Offset(r.center.dx + r.width * 0.18, r.bottom - r.height * 0.08), + line, + ); + } + + /// 移动端:手机外形(圆角矩形 + 听筒线 + 底部横线)。 + void _drawMobile(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Path p = archShapePath(s); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + final Color c = Color(s.stroke); + final Paint thin = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(1, s.sw * 0.7) + ..color = c.withValues(alpha: 0.85); + canvas.drawLine( + Offset(r.center.dx - r.width * 0.14, r.top + r.height * 0.055), + Offset(r.center.dx + r.width * 0.14, r.top + r.height * 0.055), + thin, + ); + canvas.drawLine( + Offset(r.center.dx - r.width * 0.12, r.bottom - r.height * 0.05), + Offset(r.center.dx + r.width * 0.12, r.bottom - r.height * 0.05), + thin, + ); + } + + /// 防火墙:砖墙(错缝)+ 外框。 + void _drawFirewall(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Path p = archShapePath(s); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + final Color c = Color(s.stroke); + final Paint brick = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(1, s.sw * 0.7) + ..color = c.withValues(alpha: 0.85); + const int rows = 3; + for (int i = 1; i < rows; i++) { + final double y = r.top + r.height * i / rows; + canvas.drawLine(Offset(r.left, y), Offset(r.right, y), brick); + } + for (int i = 0; i < rows; i++) { + final double y0 = r.top + r.height * i / rows; + final double y1 = r.top + r.height * (i + 1) / rows; + final double offset = i.isEven ? 0.5 : 0.25; + for (double fx = offset; fx < 0.95; fx += 0.5) { + final double x = r.left + r.width * fx; + canvas.drawLine(Offset(x, y0), Offset(x, y1), brick); + } + } + } + + /// 交换机:扁盒 + 端口方块 + 状态灯。 + void _drawNetSwitch(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Path p = archShapePath(s); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + final Color c = Color(s.stroke); + final Paint port = Paint()..color = c.withValues(alpha: 0.85); + final double size = math.min(r.height * 0.20, 8.0); + for (int i = 0; i < 6; i++) { + final double x = r.left + r.width * (0.10 + i * 0.135); + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(x, r.bottom - r.height * 0.42, size * 1.4, size), + const Radius.circular(1.5), + ), + port, + ); + } + } + + /// 消息队列 / 数据流:管道 + 三个箭头。 + void _drawQueue(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final Rect r = s.rect; + final Path p = archShapePath(s); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + final Color c = Color(s.stroke); + final Paint arrow = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(1.2, s.sw * 0.9) + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = c.withValues(alpha: 0.9); + final double h = r.height * 0.30; + for (int i = 0; i < 3; i++) { + final double x = r.left + r.width * (0.30 + i * 0.18); + canvas.drawPath( + Path() + ..moveTo(x - h * 0.35, r.center.dy - h * 0.5) + ..lineTo(x + h * 0.35, r.center.dy) + ..lineTo(x - h * 0.35, r.center.dy + h * 0.5), + arrow, + ); + } + } + + /// 图元库符号:按 100×100 归一化基元绘制到图形矩形; + /// 图元缺失(文件来自其它设备且未导入)时画占位框 + 虚线提示。 + void _drawSymbol(Canvas canvas, ArchShape s, Paint fill, Paint line) { + final LibSymbol? sym = SymbolCache.byId(s.symbolId); + if (sym == null || s.symbolId.isEmpty) { + final RRect rr = RRect.fromRectAndRadius( + s.rect, + const Radius.circular(6), + ); + canvas.drawRRect(rr, line); + _dash( + canvas, + Path()..addRRect(rr.deflate(4)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = Color(s.stroke).withValues(alpha: 0.5), + ); + return; + } + final Color c = Color(s.stroke); + for (final SymPrim p in sym.prims) { + if (p.kind == SymPrimKind.text) { + if (p.pts.length < 2 || p.label.isEmpty) continue; + final Offset tl = symPt(p.pts[0], p.pts[1], s.rect); + final double size = (s.rect.height * 0.14).clamp(7.0, 18.0).toDouble(); + final TextPainter tp = TextPainter( + text: TextSpan( + text: p.label, + style: TextStyle( + color: c, + fontSize: size, + fontWeight: FontWeight.w600, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const [ + 'Microsoft YaHei', + 'Segoe UI', + ], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, tl); + continue; + } + final Path? path = symPrimPath(p, s.rect); + if (path == null) continue; + if (s.fill != 0 && + (p.kind == SymPrimKind.rect || p.kind == SymPrimKind.circle)) { + canvas.drawPath(path, fill); + } + canvas.drawPath(path, line); + } + } + + /// 绘制一个标准图形(含图内文字)。 + void _drawShape(Canvas canvas, ArchShape s) { + final Paint fill = Paint() + ..style = PaintingStyle.fill + ..color = Color(s.fill); + final Paint line = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = s.sw + ..strokeJoin = StrokeJoin.round + ..strokeCap = StrokeCap.round + ..color = Color(s.stroke); + + switch (s.type) { + case ArchShapeType.rect: + case ArchShapeType.roundRect: + case ArchShapeType.ellipse: + case ArchShapeType.circle: + case ArchShapeType.triangle: + case ArchShapeType.diamond: + case ArchShapeType.hexagon: + case ArchShapeType.cloud: + final Path p = archShapePath(s); + if (s.fill != 0) canvas.drawPath(p, fill); + canvas.drawPath(p, line); + break; + case ArchShapeType.cylinder: + final (Path body, Path lid) = archCylinderPaths(s.rect); + if (s.fill != 0) { + canvas.drawPath(body, fill); + // 顶盖用稍亮的填充,呈现「桶口」层次。 + canvas.drawPath( + lid, + Paint() + ..style = PaintingStyle.fill + ..color = Color(s.fill).withValues( + alpha: (Color(s.fill).a + 0.10).clamp(0.0, 1.0), + ), + ); + } + canvas.drawPath(body, line); + canvas.drawPath(lid, line); + break; + case ArchShapeType.text: + break; + case ArchShapeType.line: + final Offset a = s.a ?? s.rect.topLeft; + final Offset b = s.b ?? s.rect.bottomRight; + canvas.drawLine(a, b, line); + if (s.arrow) _arrowHead(canvas, a, b, Color(s.stroke)); + break; + case ArchShapeType.polyline: + case ArchShapeType.curve: + if (s.pts.length >= 2) { + final Path path = s.type == ArchShapeType.curve + ? archSplinePath(s.pts) + : _polyPath(s.pts, close: false); + canvas.drawPath(path, line); + } + break; + case ArchShapeType.server: + _drawServer(canvas, s, fill, line); + break; + case ArchShapeType.client: + _drawClient(canvas, s, fill, line); + break; + case ArchShapeType.mobile: + _drawMobile(canvas, s, fill, line); + break; + case ArchShapeType.firewall: + _drawFirewall(canvas, s, fill, line); + break; + case ArchShapeType.netSwitch: + _drawNetSwitch(canvas, s, fill, line); + break; + case ArchShapeType.queue: + _drawQueue(canvas, s, fill, line); + break; + case ArchShapeType.symbol: + _drawSymbol(canvas, s, fill, line); + break; + } + + if (s.text.isNotEmpty) { + final Color tc = s.type == ArchShapeType.text ? Color(s.stroke) : t.text; + Offset center = s.rect.center; + if (s.type == ArchShapeType.line) { + center = center - const Offset(0, 14); + } else if (s.type == ArchShapeType.cloud) { + center = center.translate(0, s.rect.height * 0.12); + } else if (s.type == ArchShapeType.cylinder) { + center = center.translate( + 0, + math.min(s.rect.height * 0.20, s.rect.width * 0.32) * 0.8, + ); + } else if (s.type == ArchShapeType.client) { + center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.32); + } else if (s.type == ArchShapeType.netSwitch) { + center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.30); + } + _label( + canvas, + s.text, + center, + tc, + maxWidth: math.max(24, s.rect.width - 12), + size: s.type == ArchShapeType.text + ? (s.rect.height * 0.72).clamp(10.0, 120.0) + : 12.5, + ); + } + + // 尺寸标注(识别后图形 / 曲线 / 图元可直接改值缩放;标签屏幕字号恒定)。 + if (s.dims.isNotEmpty) { + final double z = doc.zoom < 0.05 ? 1 : doc.zoom; + final List kinds = [ + for (final ArchDimKind k in archShapeDimKinds(s)) + if (s.dims.contains(k)) k, + ]; + for (int i = 0; i < kinds.length; i++) { + final ArchDimKind k = kinds[i]; + _dimBadge(canvas, s, k, archShapeDimLabelPos(s, k, i, z), z); + } + } + } + + /// 尺寸标签(小圆角底片 + 数值;屏幕尺寸恒定,双击可改值)。 + void _dimBadge( + Canvas canvas, + ArchShape s, + ArchDimKind k, + Offset center, + double z, + ) { + final double inv = 1 / z; + final double v = archShapeDimValue(s, k); + final String txt = switch (k) { + ArchDimKind.width => 'W ${_fmtDim(v)}', + ArchDimKind.height => 'H ${_fmtDim(v)}', + ArchDimKind.length => 'L ${_fmtDim(v)}', + ArchDimKind.diameter => '⌀ ${_fmtDim(v)}', + }; + final TextPainter tp = TextPainter( + text: TextSpan( + text: txt, + style: TextStyle( + color: const Color(0xFF0F766E), + fontSize: 10 * inv, + fontWeight: FontWeight.w600, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Segoe UI'], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + final Rect r = Rect.fromCenter( + center: center, + width: tp.width + 8 * inv, + height: tp.height + 3 * inv, + ); + final RRect rr = RRect.fromRectAndRadius(r, Radius.circular(4 * inv)); + canvas.drawRRect(rr, Paint()..color = t.panel.withValues(alpha: 0.94)); + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 * inv + ..color = const Color(0xFF0F766E).withValues(alpha: 0.5), + ); + tp.paint(canvas, r.center - Offset(tp.width / 2, tp.height / 2)); + } + + static String _fmtDim(double v) => (v - v.roundToDouble()).abs() < 0.05 + ? v.round().toString() + : v.toStringAsFixed(1); + + /// 绘制连线(吸附端实时求边框交点;直线 / 正交折线;箭头 + 标签)。 + void _connector(Canvas canvas, ArchConnector c) { + final ArchConnGeometry g = + archConnectorGeometry(doc, c, override: _preview); + final Color color = Color(c.color); + final Paint p = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6 + ..strokeCap = StrokeCap.round + ..color = color; + if (c.dash) { + _dash(canvas, g.path, p); + } else { + canvas.drawPath(g.path, p); + } + _arrowHead(canvas, g.pts[g.pts.length - 2], g.end, color); + if (c.label.isNotEmpty) { + _connLabel(canvas, g.label, c.label); + } + } + + /// 连线标签(底片 + 文本)。 + void _connLabel(Canvas canvas, Offset mid, String text) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + color: t.text2, + fontSize: 10.5, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ), + textDirection: TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: 180); + final Rect bg = Rect.fromCenter( + center: mid, + width: tp.width + 10, + height: tp.height + 6, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(bg, const Radius.circular(5)), + Paint()..color = t.panel, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(bg, const Radius.circular(5)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = t.line2, + ); + tp.paint(canvas, mid - Offset(tp.width / 2, tp.height / 2)); + } + + /// 图形 / 文本标签(居中,多行按 `\n` 拆分)。 + void _label( + Canvas canvas, + String text, + Offset center, + Color color, { + required double maxWidth, + double size = 12.5, + }) { + final List lines = text.split('\n'); + final List tps = []; + double totalH = 0; + for (final String ln in lines) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: ln, + style: TextStyle( + color: color, + fontSize: size, + fontWeight: FontWeight.w600, + height: 1.25, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ), + textDirection: TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: maxWidth); + tps.add(tp); + totalH += tp.height; + } + double y = center.dy - totalH / 2; + for (final TextPainter tp in tps) { + tp.paint(canvas, Offset(center.dx - tp.width / 2, y)); + y += tp.height; + } + } + + /// 箭头头部。 + void _arrowHead(Canvas canvas, Offset from, Offset to, Color color) { + final Offset d = to - from; + final double len = d.distance; + if (len < 1) return; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + const double hl = 11; + const double hw = 5.5; + final Path path = Path() + ..moveTo(to.dx, to.dy) + ..lineTo(to.dx - u.dx * hl + n.dx * hw, to.dy - u.dy * hl + n.dy * hw) + ..lineTo(to.dx - u.dx * hl - n.dx * hw, to.dy - u.dy * hl - n.dy * hw) + ..close(); + canvas.drawPath(path, Paint()..color = color); + } + + /// 虚线绘制。 + void _dash(Canvas canvas, Path path, Paint paint) { + for (final ui.PathMetric m in path.computeMetrics()) { + double d = 0; + while (d < m.length) { + final double end = math.min(d + 8, m.length); + canvas.drawPath(m.extractPath(d, end), paint); + d = end + 6; + } + } + } + + /// 选中框与手柄(支持多选)。 + void _selection(Canvas canvas) { + if (selectedIds.isEmpty) return; + final double z = doc.zoom < 0.05 ? 1 : doc.zoom; + final Paint sp = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.3 / z + ..color = t.accent; + + Rect? combined; + for (final String id in selectedIds) { + final ArchShape? s = doc.shapeById(id); + if (s != null) { + if (!doc.isLayerVisible(s.layerId)) continue; + final ArchShape ps = _preview(s); + final Rect box = ps.isLinear ? ps.bounds : ps.rect.inflate(4); + combined = combined == null ? box : combined.expandToInclude(box); + if (ps.isLinear) { + final List vs = [ + if (ps.type == ArchShapeType.line && ps.a != null && ps.b != null) + ...[ps.a!, ps.b!] + else + ...ps.pts, + ]; + for (final Offset p in vs) { + _handleDot(canvas, p, z); + } + } else { + _dash( + canvas, + Path() + ..addRRect(RRect.fromRectAndRadius(box, const Radius.circular(4))), + sp, + ); + for (final Rect h in archHandleRects(ps.rect, z)) { + _handleRect(canvas, h, z); + } + } + continue; + } + final ArchConnector? c = doc.connectorById(id); + if (c != null) { + if (!doc.isLayerVisible(c.layerId)) continue; + final ArchConnGeometry g = + archConnectorGeometry(doc, c, override: _preview); + for (final Offset p in g.pts) { + _handleDot(canvas, p, z); + } + combined = combined == null + ? Rect.fromPoints(g.start, g.end).inflate(6) + : combined.expandToInclude(Rect.fromPoints(g.start, g.end)); + continue; + } + final ArchStroke? k = doc.strokeById(id); + if (k != null) { + if (!doc.isLayerVisible(k.layerId)) continue; + final Rect box = k.bounds.inflate(5); + combined = combined == null ? box : combined.expandToInclude(box); + _dash( + canvas, + Path() + ..addRRect(RRect.fromRectAndRadius(box, const Radius.circular(4))), + sp, + ); + } + } + // 多选时加一圈总框。 + if (selectedIds.length > 1 && combined != null) { + _dash( + canvas, + Path() + ..addRRect(RRect.fromRectAndRadius(combined.inflate(8), const Radius.circular(6))), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 / z + ..color = t.accent.withValues(alpha: 0.6), + ); + } + } + + /// 方形手柄。 + void _handleRect(Canvas canvas, Rect r, double z) { + canvas.drawRect( + r, + Paint() + ..style = PaintingStyle.fill + ..color = t.panel, + ); + canvas.drawRect( + r, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.3 / z + ..color = t.accent, + ); + } + + /// 圆形手柄(线类端点 / 折点 / 连线折点)。 + void _handleDot(Canvas canvas, Offset c, double z) { + final double r = 4 / z; + canvas.drawCircle(c, r, Paint()..color = t.panel); + canvas.drawCircle( + c, + r, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.3 / z + ..color = t.accent, + ); + } + + /// 任何输入变化都重绘(画布尺寸有限,开销可接受)。 + @override + bool shouldRepaint(covariant ArchPainter oldDelegate) => true; +} + +/// 构造多边形路径。 +Path _polyPath(List pts, {required bool close}) { + final Path p = Path(); + if (pts.isEmpty) return p; + p.moveTo(pts.first.dx, pts.first.dy); + for (int i = 1; i < pts.length; i++) { + p.lineTo(pts[i].dx, pts[i].dy); + } + if (close) p.close(); + return p; +} diff --git a/lib/arch/arch_recognizer.dart b/lib/arch/arch_recognizer.dart new file mode 100644 index 0000000..18dd04c --- /dev/null +++ b/lib/arch/arch_recognizer.dart @@ -0,0 +1,971 @@ +/// 手绘识别:把一笔自由曲线识别成标准图形(直线 / 箭头 / 矩形 / 圆角矩形 / +/// 圆 / 椭圆 / 三角形 / 菱形 / 六边形)。 +/// +/// 设计目标:像 iOS 手写便签那样——随手画个大概,松手后自动「扶正」成标准 +/// 图形;识别不了的笔迹保留为墨迹(不丢内容)。 +/// +/// 算法概览(纯几何、无依赖、可单测): +/// 1. 清洗 & 重采样成均匀点列; +/// 2. 首尾距离判定「闭合 / 开放」; +/// 3. 开放笔迹:直线拟合(含水平 / 垂直吸附)→ 箭头(箭杆直线 + 尖端折返); +/// 4. 闭合笔迹:径向椭圆残差 + Douglas-Peucker 顶点化简 + 折点合并, +/// 按顶点数分流(3 三角 / 4 矩形或菱形 / 6 六边形 / ≥7 或残差小 → 椭圆)。 +library; + +import 'dart:math' as math; +import 'dart:ui' show Offset, Rect; + +import 'arch_models.dart'; + +/// 识别结果:标准图形类型 + 规范化几何。 +class ArchRecognition { + /// 构造识别结果。 + const ArchRecognition({ + required this.type, + required this.rect, + this.radius = 0, + this.dir = 0, + this.a, + this.b, + this.arrow = false, + this.pts, + }); + + /// 图形类型(含 [ArchShapeType.line] 直线 / 箭头)。 + final ArchShapeType type; + + /// 规范化后的外接矩形。 + final Rect rect; + + /// 圆角半径([ArchShapeType.roundRect])。 + final double radius; + + /// 三角形朝向:0 上 / 1 右 / 2 下 / 3 左。 + final int dir; + + /// 直线起点。 + final Offset? a; + + /// 直线终点。 + final Offset? b; + + /// 是否为箭头(仅 [ArchShapeType.line])。 + final bool arrow; + + /// 折线 / 曲线的通过点([ArchShapeType.polyline] / [ArchShapeType.curve])。 + final List? pts; +} + +/// 识别一笔手绘:成功返回标准图形,失败返回 null(调用方保留墨迹)。 +ArchRecognition? recognizeArchStroke(List raw) { + final List pts = _clean(raw); + if (pts.length < 5) return null; + final double len = _polyLength(pts); + if (len < 18) return null; + final Rect bb = _bounds(pts); + if (math.max(bb.width, bb.height) < 14) return null; + final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height); + + // 单笔「圆柱」:柱体 + 顶盖两圈轮廓,路径长度显著大于外接矩形周长。 + final double gap = (pts.last - pts.first).distance; + final double hullPer = 2 * (bb.width + bb.height); + if (hullPer > 40 && len > hullPer * 1.38) { + final List> parts = _splitOnJumps(pts, diag); + if (parts.length == 2) { + final ArchRecognition? cyl = _cylinderFromParts(parts[0], parts[1]) ?? + _cylinderFromParts(parts[1], parts[0]); + if (cyl != null) return cyl; + } + // 无内部跳变(顶盖起点与柱体起点重合)时:接近闭合即视为圆柱。 + if (gap <= 0.45 * diag) { + return ArchRecognition(type: ArchShapeType.cylinder, rect: bb); + } + } + + final bool closed = gap <= math.max(16, 0.22 * diag); + if (closed) { + if (math.min(bb.width, bb.height) < 10) return null; + return _classifyClosed(pts, bb, diag); + } + return _classifyOpen(pts, len); +} + +/// 多笔合并识别(如:两笔画出的矩形、先画柱体再画顶盖的圆柱)。 +/// +/// 按端点最近邻串接各笔后走单笔识别管线;接缝过大(两笔相距太远)时放弃。 +ArchRecognition? recognizeArchStrokes(List> strokes) { + final List> parts = >[ + for (final List s in strokes) + if (_clean(s).length >= 4) _clean(s), + ]; + if (parts.isEmpty) return null; + if (parts.length == 1) return recognizeArchStroke(parts.first); + if (parts.length > 2) return null; + final List a = parts[0]; + final List b = parts[1]; + final double g1 = (a.last - b.first).distance; + final double g2 = (a.last - b.last).distance; + final double g3 = (a.first - b.first).distance; + final double g4 = (a.first - b.last).distance; + List merged; + double gap; + if (g1 <= g2 && g1 <= g3 && g1 <= g4) { + merged = [...a, ...b]; + gap = g1; + } else if (g2 <= g3 && g2 <= g4) { + merged = [...a, ...b.reversed]; + gap = g2; + } else if (g3 <= g4) { + merged = [...a.reversed, ...b]; + gap = g3; + } else { + merged = [...a.reversed, ...b.reversed]; + gap = g4; + } + final Rect bb = _bounds(merged); + final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height); + if (gap > math.max(26.0, 0.30 * diag)) return null; + return recognizeArchStroke(merged); +} + +/// 两个「部件」识别结果组合成圆柱(顶盖椭圆 + 柱体矩形,形状层面快速判定)。 +ArchRecognition? archCylinderFromRecognitions( + ArchRecognition body, + ArchRecognition lid, +) { + final bool bodyIsRect = + body.type == ArchShapeType.rect || body.type == ArchShapeType.roundRect; + final bool lidIsEllipse = + lid.type == ArchShapeType.ellipse || lid.type == ArchShapeType.circle; + if (!bodyIsRect || !lidIsEllipse) return null; + final Rect br = body.rect; + final Rect lr = lid.rect; + final bool geomOk = + (lr.center.dx - br.center.dx).abs() <= math.max(14, br.width * 0.20) && + (lr.width - br.width).abs() <= math.max(18, br.width * 0.38) && + lr.center.dy <= br.top + lr.height * 0.9 && + lr.bottom >= br.top - lr.height * 0.6; + if (!geomOk) return null; + return ArchRecognition( + type: ArchShapeType.cylinder, + rect: Rect.fromLTRB( + math.min(lr.left, br.left), + math.min(lr.top, br.top), + math.max(lr.right, br.right), + math.max(lr.bottom, br.bottom), + ), + ); +} + +/// 按跳变(相邻点距离过大)把一笔拆成多段(单笔圆柱的柱体 + 顶盖)。 +List> _splitOnJumps(List pts, double diag) { + final double thr = math.max(14.0, 0.18 * diag); + final List> parts = >[]; + List cur = [pts.first]; + for (int i = 1; i < pts.length; i++) { + if ((pts[i] - pts[i - 1]).distance > thr) { + if (cur.length >= 4) parts.add(cur); + cur = [pts[i]]; + } else { + cur.add(pts[i]); + } + } + if (cur.length >= 4) parts.add(cur); + return parts; +} + +/// 圆柱顶盖(扁椭圆)识别:放宽椭圆残差阈值(扁椭圆曲率大、抖动残差偏高), +/// 只要「近椭圆」即可作为顶盖。 +ArchRecognition? _recognizeLid(List lidPts) { + final Rect lb = _bounds(lidPts); + if (math.min(lb.width, lb.height) < 10) return null; + final List pts = _resample(lidPts, 72); + final double res90 = _percentile(_ellipseResiduals(pts, lb), 0.90); + if (res90 <= 0.24) return _ellipseFrom(lb); + return null; +} + +/// 两段轮廓组合成圆柱:一段是柱体(矩形类),一段是顶盖(椭圆类)。 +ArchRecognition? _cylinderFromParts(List bodyPts, List lidPts) { + final Rect bb = _bounds(bodyPts); + final double bd = math.sqrt(bb.width * bb.width + bb.height * bb.height); + final Rect lb = _bounds(lidPts); + final double ld = math.sqrt(lb.width * lb.width + lb.height * lb.height); + final double gapB = (bodyPts.last - bodyPts.first).distance; + final double gapL = (lidPts.last - lidPts.first).distance; + if (math.min(bb.width, bb.height) < 12 || math.min(lb.width, lb.height) < 10) { + return null; + } + if (gapB > math.max(20, 0.35 * bd) || gapL > math.max(20, 0.35 * ld)) { + return null; + } + final ArchRecognition? lid = _recognizeLid(lidPts); + if (lid == null || + (lid.type != ArchShapeType.ellipse && lid.type != ArchShapeType.circle)) { + return null; + } + final ArchRecognition? body = _classifyClosed(bodyPts, bb, bd); + final bool bodyRect = body != null && + (body.type == ArchShapeType.rect || + body.type == ArchShapeType.roundRect); + if (!bodyRect && !_hasTwoSideEdges(bodyPts, bb)) return null; + final Rect lr = lid.rect; + final bool geomOk = + (lr.center.dx - bb.center.dx).abs() <= math.max(14, bb.width * 0.20) && + (lr.width - bb.width).abs() <= math.max(18, bb.width * 0.38) && + lr.center.dy <= bb.top + lr.height * 0.9 && + lr.bottom >= bb.top - lr.height * 0.6; + if (!geomOk) return null; + return ArchRecognition( + type: ArchShapeType.cylinder, + rect: Rect.fromLTRB( + math.min(lr.left, bb.left), + math.min(lr.top, bb.top), + math.max(lr.right, bb.right), + math.max(lr.bottom, bb.bottom), + ), + ); +} + +/// 柱体结构判定:左右两侧各有一条较长的竖直侧边(圆柱轮廓的必要条件)。 +bool _hasTwoSideEdges(List bodyPts, Rect bb) { + final double eps = math.max(3.0, 0.04 * math.min(bb.width, bb.height)); + double lMin = double.infinity, lMax = -double.infinity; + double rMin = double.infinity, rMax = -double.infinity; + for (final Offset p in bodyPts) { + if ((p.dx - bb.left).abs() <= eps) { + if (p.dy < lMin) lMin = p.dy; + if (p.dy > lMax) lMax = p.dy; + } + if ((p.dx - bb.right).abs() <= eps) { + if (p.dy < rMin) rMin = p.dy; + if (p.dy > rMax) rMax = p.dy; + } + } + final double lSpan = lMax - lMin; + final double rSpan = rMax - rMin; + return lSpan >= bb.height * 0.4 && rSpan >= bb.height * 0.4; +} + +/// 把识别结果转成标准图形(画布提交 / 示例场景共用)。 +ArchShape archShapeFromRecognition( + ArchRecognition r, { + required String id, + required int color, + String text = '', +}) { + if (r.type == ArchShapeType.line) { + final Offset a = r.a ?? Offset.zero; + final Offset b = r.b ?? Offset.zero; + return ArchShape( + id: id, + type: ArchShapeType.line, + rect: Rect.fromPoints(a, b), + a: a, + b: b, + arrow: r.arrow, + fill: 0, + stroke: color, + sw: 2.4, + text: text, + ); + } + if (r.type == ArchShapeType.polyline || r.type == ArchShapeType.curve) { + final List pts = r.pts ?? const []; + return ArchShape( + id: id, + type: r.type, + rect: r.rect, + fill: 0, + stroke: color, + sw: 2.4, + text: text, + pts: pts, + ); + } + return ArchShape( + id: id, + type: r.type, + rect: r.rect, + radius: r.radius, + dir: r.dir, + fill: archFillOf(color), + stroke: color, + sw: 1.8, + text: text, + ); +} + +// ===================== 开放笔迹:直线 / 箭头 ===================== + +/// 开放笔迹分类:先试直线(含水平/垂直吸附),再试箭头。 +ArchRecognition? _classifyOpen(List pts, double len) { + final Offset a = pts.first; + final Offset b = pts.last; + final double chord = (b - a).distance; + + // 1) 直线:路径基本沿首尾弦推进,且最大偏距很小。 + if (chord >= 0.72 * len) { + final double dev = _maxDeviation(pts, a, b); + if (dev <= math.max(4.0, 0.075 * chord)) { + return _line(a, b, arrow: false); + } + } + + // 2) 箭头:离起点最远的点为箭尖;箭杆近似直线;尖端之后有明显折返 + // (手绘箭头的头部是一笔折返的「>」)。 + int tip = 0; + double best = -1; + for (int i = 0; i < pts.length; i++) { + final double d = (pts[i] - a).distance; + if (d > best) { + best = d; + tip = i; + } + } + if (tip >= 2 && pts.length - 1 - tip >= 2) { + final Offset t = pts[tip]; + final double shaft = best; + if (shaft >= 0.5 * len && shaft >= 14) { + final double shaftDev = _maxDeviation(pts.sublist(0, tip + 1), a, t); + if (shaftDev <= math.max(4.0, 0.065 * shaft)) { + final double headLen = len - _polyLength(pts.sublist(0, tip + 1)); + if (headLen <= 0.45 * len && headLen >= math.max(5.0, 0.035 * len)) { + final Offset u = (t - a) / shaft; + double minProj = shaft; + for (int i = tip + 1; i < pts.length; i++) { + final double pr = _dot(pts[i] - a, u); + if (pr < minProj) minProj = pr; + } + if (minProj <= shaft - math.max(5.0, 0.065 * len)) { + return _line(a, t, arrow: true); + } + } + } + } + } + + // 3) 折线 / 曲线:既不是直线也不是箭头。 + return _classifyPolyOrCurve(pts, len); +} + +/// 折线 / 曲线分流: +/// - 有集中的尖折点(折点转角大)→ 折线(近轴段自动扶正); +/// - 平缓弯曲 → 曲线(样条通过点)。 +ArchRecognition? _classifyPolyOrCurve(List pts, double len) { + final Rect bb = _bounds(pts); + final double diag = + math.max(1, math.sqrt(bb.width * bb.width + bb.height * bb.height)); + final List idx = + _rdpIndices(pts, math.max(3.0, 0.03 * diag)); + final List merged = _mergeOpen(pts, idx, 24); + final List v = [for (final int i in merged) pts[i]]; + if (v.length < 2) return null; + final double chord = (v.last - v.first).distance; + if (v.length == 2) { + // 轻微弯曲的笔迹:保留弧度成为曲线(不弯曲的早走直线分支了)。 + if (len >= chord * 1.015 && len <= chord * 2.2) { + return ArchRecognition( + type: ArchShapeType.curve, + rect: _bounds(v), + pts: v, + ); + } + return null; + } + double maxTurn = 0; + for (int i = 1; i < v.length - 1; i++) { + maxTurn = math.max(maxTurn, _turnDeg(v[i - 1], v[i], v[i + 1])); + } + // 优先级:直线 > 曲线 > 折线。只有「折点犀利 + 每段足够直」才判为折线; + // 否则一律归为曲线(曲线识别优先)。 + if (maxTurn >= 55 && v.length <= 9 && _segmentsStraight(pts, v)) { + final List snapped = _snapAxisSegments(v, 12); + return ArchRecognition( + type: ArchShapeType.polyline, + rect: _bounds(snapped), + pts: snapped, + ); + } + // 平缓弯曲 → 曲线:用更粗的简化取「通过点」,保留动势。 + final List idx2 = _rdpIndices(pts, math.max(5.0, 0.07 * diag)); + final List cv = [for (final int i in idx2) pts[i]]; + if (cv.length < 3) return null; + return ArchRecognition( + type: ArchShapeType.curve, + rect: _bounds(cv), + pts: cv, + ); +} + +/// 判断折点之间的每一段是否足够「直」: +/// 直线段 → 折线候选;带明显弧度的段 → 归为曲线(曲线优先)。 +bool _segmentsStraight(List pts, List v) { + if (v.length < 2) return false; + final List idx = []; + for (final Offset t in v) { + int bestI = 0; + double bestD = double.infinity; + for (int i = 0; i < pts.length; i++) { + final double d = (pts[i] - t).distance; + if (d < bestD) { + bestD = d; + bestI = i; + } + } + idx.add(bestI); + } + for (int i = 1; i < idx.length; i++) { + if (idx[i] <= idx[i - 1]) return false; + } + for (int s = 0; s < idx.length - 1; s++) { + final Offset a = pts[idx[s]]; + final Offset b = pts[idx[s + 1]]; + final double segLen = (b - a).distance; + if (segLen < 6) continue; + double maxDev = 0; + for (int i = idx[s] + 1; i < idx[s + 1]; i++) { + final double d = archDistToSegment(pts[i], a, b); + if (d > maxDev) maxDev = d; + } + if (maxDev > math.max(3.5, segLen * 0.055)) return false; + } + return true; +} + +/// 把一段手画轨迹简化为折线顶点(连线轨迹识别用): +/// RDP 抽稀 + 共线合并 + 近轴段扶正(±12° 吸附为水平 / 垂直)。 +List simplifyArchPolyline(List pts) { + final List clean = _clean(pts); + if (clean.length < 2) return clean; + final Rect b = _bounds(clean); + final double diag = math.sqrt(b.width * b.width + b.height * b.height); + final List idx = _rdpIndices(clean, math.max(4.0, 0.035 * diag)); + final List merged = _mergeOpen(clean, idx, 24); + final List v = [for (final int i in merged) clean[i]]; + if (v.length < 2) return [clean.first, clean.last]; + return _snapAxisSegments(v, 12); +} + +/// 合并共线折点(开放折线:只处理内部顶点)。 +List _mergeOpen(List pts, List idx, double tolDeg) { + final List cur = List.of(idx); + bool changed = true; + while (changed && cur.length > 2) { + changed = false; + for (int i = 1; i < cur.length - 1; i++) { + if (_turnDeg(pts[cur[i - 1]], pts[cur[i]], pts[cur[i + 1]]) < tolDeg) { + cur.removeAt(i); + changed = true; + break; + } + } + } + return cur; +} + +/// 近水平 / 垂直的折线段扶正(±[tolDeg] 内吸附为水平 / 垂直)。 +List _snapAxisSegments(List v, double tolDeg) { + final List out = List.of(v); + for (int i = 0; i < out.length - 1; i++) { + final Offset d = out[i + 1] - out[i]; + if (d.distance < 0.001) continue; + final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi; + double m = ang % 180; + if (m > 90) m -= 180; + final double devH = m.abs(); + final double devV = 90 - m.abs(); + if (devH <= tolDeg) { + final double y = (out[i].dy + out[i + 1].dy) / 2; + out[i] = Offset(out[i].dx, y); + out[i + 1] = Offset(out[i + 1].dx, y); + } else if (devV <= tolDeg) { + final double x = (out[i].dx + out[i + 1].dx) / 2; + out[i] = Offset(x, out[i].dy); + out[i + 1] = Offset(x, out[i + 1].dy); + } + } + return out; +} + +/// 云判定:统计闭合曲线上的「凹口」段数(鼓包相接处方向反转)。 +/// +/// 矩形 / 圆角矩形 / 椭圆边界全程同向(凸),凹口数为 0; +/// 云由多个鼓包拼接而成,凹口 ≥ 3。 +int _concaveRunCount(List pts) { + final int total = pts.length; + if (total < 24) return 0; + final int k = math.max(2, total ~/ 20); + final List turns = []; + for (int i = 0; i < total; i++) { + final Offset a = pts[(i + k) % total] - pts[i]; + final Offset b = pts[(i + 2 * k) % total] - pts[(i + k) % total]; + final double la = a.distance; + final double lb = b.distance; + if (la < 0.001 || lb < 0.001) { + turns.add(0); + continue; + } + double s = (a.dx * b.dy - a.dy * b.dx) / (la * lb); + s = s.clamp(-1.0, 1.0); + turns.add(math.asin(s) * 180 / math.pi); + } + double totalTurn = 0; + for (final double v in turns) { + totalTurn += v; + } + final double dir = totalTurn >= 0 ? 1 : -1; + int runs = 0; + bool inRun = false; + for (int i = 0; i < total * 2; i++) { + final bool concave = turns[i % total] * dir < -10.0; + if (concave && !inRun) { + runs++; + inRun = true; + } else if (!concave) { + inRun = false; + } + } + return (runs / 2).round(); +} + +/// 构造直线识别结果;方向接近水平 / 垂直(±8°)时吸附到正轴。 +ArchRecognition _line(Offset a, Offset b, {required bool arrow}) { + Offset aa = a; + Offset bb = b; + final Offset d = b - a; + if (d.distance > 0.001) { + final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi; + double m = ang % 180; + if (m > 90) m -= 180; // 归一化到 (-90, 90]:0 = 水平,±90 = 垂直 + final double devH = m.abs(); + final double devV = 90 - m.abs(); + if (devH <= 8) { + final double y = (a.dy + b.dy) / 2; + aa = Offset(a.dx, y); + bb = Offset(b.dx, y); + } else if (devV <= 8) { + final double x = (a.dx + b.dx) / 2; + aa = Offset(x, a.dy); + bb = Offset(x, b.dy); + } + } + return ArchRecognition( + type: ArchShapeType.line, + rect: Rect.fromPoints(aa, bb), + a: aa, + b: bb, + arrow: arrow, + ); +} + +// ===================== 闭合笔迹:多边形 / 椭圆 ===================== + +/// 闭合笔迹分类:顶点数 + 椭圆残差(分位)+ 贴边率。 +ArchRecognition? _classifyClosed(List raw, Rect bb, double diag) { + final List pts = _resample(raw, 72); + final double res90 = _percentile(_ellipseResiduals(pts, bb), 0.90); + final List poly = + _rdpIndices(pts, math.max(2.2, 0.016 * diag), closed: true); + final List merged = _mergeCollinear( + pts, + poly, + 13, + math.max(3.0, 0.075 * diag), + ); + final int n = merged.length; + + // 顶点很少(光滑闭合曲线)→ 椭圆残差小则是圆 / 椭圆。 + if (n <= 2) { + return res90 <= 0.15 ? _ellipseFrom(bb) : null; + } + + if (n >= 7) { + if (res90 <= 0.15) return _ellipseFrom(bb); + // 云:边界上有多个「凹口」(鼓包相接处);矩形类边界全凸、椭圆已排除。 + if (_concaveRunCount(pts) >= 3) { + return ArchRecognition(type: ArchShapeType.cloud, rect: bb); + } + // 大圆角矩形会被化简出很多顶点:贴边率高 → 按矩形(含圆角)处理。 + if (_sideFit(pts, bb) >= 0.5) return _quadFromRect(pts, bb); + return null; + } + if (n == 6) { + if (res90 <= 0.15) return _ellipseFrom(bb); + // 起笔 / 收笔接缝可能带来 1–2 个多余顶点,先尝试合并回四边形。 + final List? quad = _tryMergeToQuad(pts, merged, 13); + if (quad != null && _sideFit(pts, bb) >= 0.45) { + return _quad(pts, bb, quad); + } + return ArchRecognition(type: ArchShapeType.hexagon, rect: bb); + } + if (n == 5) { + final List? quad = _tryMergeToQuad(pts, merged, 13); + if (quad != null && _sideFit(pts, bb) >= 0.45) { + return _quad(pts, bb, quad); + } + // 五边形等暂无对应标准图形:保留墨迹。 + return null; + } + if (n == 3) return _triangle(pts, bb, merged); + return _quad(pts, bb, merged); +} + +/// 由外接矩形构造椭圆 / 圆(长短边接近时归一为圆)。 +ArchRecognition _ellipseFrom(Rect bb) { + final double w = bb.width; + final double h = bb.height; + if (w > 0 && h > 0 && (w - h).abs() <= 0.18 * math.max(w, h)) { + final double d = (w + h) / 2; + return ArchRecognition( + type: ArchShapeType.circle, + rect: Rect.fromCenter(center: bb.center, width: d, height: d), + ); + } + return ArchRecognition(type: ArchShapeType.ellipse, rect: bb); +} + +/// 四顶点:按边方向判别矩形(含圆角矩形)与菱形。 +ArchRecognition? _quad(List pts, Rect bb, List merged) { + final List v = [for (final int i in merged) pts[i]]; + double axisScore = 0; + double diagScore = 0; + for (int i = 0; i < 4; i++) { + final Offset e = v[(i + 1) % 4] - v[i]; + if (e.distance < 0.5) return null; + final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi; + double m = ang % 90; + if (m < 0) m += 90; + final double b = math.min(m, 90 - m); // 与最近坐标轴的夹角(0..45) + axisScore += b; + diagScore += 45 - b; + } + if (axisScore > diagScore) { + return ArchRecognition(type: ArchShapeType.diamond, rect: bb); + } + return _quadFromRect(pts, bb); +} + +/// 矩形系列:估计圆角半径(外接矩形四角到笔迹的最小距离 / 0.414), +/// 明显圆角 → 圆角矩形。 +ArchRecognition _quadFromRect(List pts, Rect bb) { + final double minSide = math.min(bb.width, bb.height); + final double r = _cornerRadiusFromBbox(pts, bb); + if (r > math.max(9, 0.075 * minSide)) { + return ArchRecognition( + type: ArchShapeType.roundRect, + rect: bb, + radius: math.min(r, 0.45 * minSide), + ); + } + return ArchRecognition(type: ArchShapeType.rect, rect: bb); +} + +/// 三角形:最长边为底,把顶点吸附到外接矩形的对应边上(正三角 / 直角靠边)。 +ArchRecognition? _triangle(List pts, Rect bb, List merged) { + final List v = [for (final int i in merged) pts[i]]; + double bestLen = -1; + int baseI = 0; + for (int i = 0; i < 3; i++) { + final double d = (v[(i + 1) % 3] - v[i]).distance; + if (d > bestLen) { + bestLen = d; + baseI = i; + } + } + final Offset b0 = v[baseI]; + final Offset b1 = v[(baseI + 1) % 3]; + final Offset apex = v[(baseI + 2) % 3]; + final Offset baseMid = (b0 + b1) / 2; + final bool horiz = (b1.dx - b0.dx).abs() >= (b1.dy - b0.dy).abs(); + if (horiz) { + final bool up = apex.dy < baseMid.dy; + final double baseY = up ? bb.bottom : bb.top; + final double apexY = up ? bb.top : bb.bottom; + return ArchRecognition( + type: ArchShapeType.triangle, + rect: Rect.fromLTRB( + bb.left, + math.min(apexY, baseY), + bb.right, + math.max(apexY, baseY), + ), + dir: up ? 0 : 2, + ); + } + final bool left = apex.dx < baseMid.dx; + final double baseX = left ? bb.right : bb.left; + final double apexX = left ? bb.left : bb.right; + return ArchRecognition( + type: ArchShapeType.triangle, + rect: Rect.fromLTRB( + math.min(apexX, baseX), + bb.top, + math.max(apexX, baseX), + bb.bottom, + ), + dir: left ? 3 : 1, + ); +} + +// ===================== 几何工具 ===================== + +/// 椭圆残差列表:以 [bb] 为「拟合椭圆」,逐点计算归一化偏差。 +List _ellipseResiduals(List pts, Rect bb) { + final double rx = bb.width / 2; + final double ry = bb.height / 2; + if (rx < 1 || ry < 1 || pts.isEmpty) return [1]; + final List out = []; + for (final Offset p in pts) { + final double nx = (p.dx - bb.center.dx) / rx; + final double ny = (p.dy - bb.center.dy) / ry; + out.add((math.sqrt(nx * nx + ny * ny) - 1).abs()); + } + return out; +} + +/// 分位数([q] 0..1)。 +double _percentile(List values, double q) { + if (values.isEmpty) return 1; + final List s = List.of(values)..sort(); + final int idx = ((s.length - 1) * q).round().clamp(0, s.length - 1); + return s[idx]; +} + +/// 贴边率:笔迹点贴近外接矩形四条边的比例 +/// (区分「有直边的矩形」与「全曲线的椭圆」)。 +double _sideFit(List pts, Rect bb) { + if (pts.isEmpty) return 0; + final double eps = math.max(4.0, 0.05 * math.min(bb.width, bb.height)); + int hit = 0; + for (final Offset p in pts) { + final double d = math.min( + math.min((p.dy - bb.top).abs(), (p.dy - bb.bottom).abs()), + math.min((p.dx - bb.left).abs(), (p.dx - bb.right).abs()), + ); + if (d <= eps) hit++; + } + return hit / pts.length; +} + +/// 估计圆角半径:外接矩形四个角到笔迹的最小距离 / (√2−1) +/// (90° 圆角弧线到尖角的距离恰为 0.414r),再减去手抖带来的基础偏差。 +double _cornerRadiusFromBbox(List pts, Rect bb) { + final List corners = [ + bb.topLeft, + bb.topRight, + bb.bottomRight, + bb.bottomLeft, + ]; + double sum = 0; + for (final Offset c in corners) { + double dmin = double.infinity; + for (final Offset p in pts) { + final double d = (p - c).distance; + if (d < dmin) dmin = d; + } + sum += dmin; + } + return math.max(0, (sum / 4) / 0.4142 - 3.5); +} + +/// 四边形的「与坐标轴 / 对角线贴合度」:各边到最近轴(0° / 90°)或 +/// 对角线(45°)的平均偏差(度)。越小越像矩形 / 菱形。 +double _quadDeviation(List pts, List quad) { + final List v = [for (final int i in quad) pts[i]]; + double axis = 0; + double diag = 0; + for (int i = 0; i < 4; i++) { + final Offset e = v[(i + 1) % 4] - v[i]; + if (e.distance < 0.5) return double.infinity; + final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi; + double m = ang % 90; + if (m < 0) m += 90; + final double b = math.min(m, 90 - m); + axis += b; + diag += 45 - b; + } + return math.min(axis, diag) / 4; +} + +/// 尝试把 5 / 6 个顶点合并成四边形(起笔 / 收笔接缝可能多出顶点): +/// 暴力尝试删除 1–2 个顶点,取「最像四边形」的组合;偏差超限返回 null。 +List? _tryMergeToQuad(List pts, List merged, double maxDev) { + final int n = merged.length; + if (n == 4) return merged; + if (n < 4 || n > 6) return null; + double best = maxDev; + List? bestSet; + if (n == 5) { + for (int i = 0; i < 5; i++) { + final List r = List.of(merged)..removeAt(i); + final double d = _quadDeviation(pts, r); + if (d < best) { + best = d; + bestSet = r; + } + } + } else { + for (int i = 0; i < 6; i++) { + for (int j = i + 1; j < 6; j++) { + final List r = List.of(merged) + ..removeAt(j) + ..removeAt(i); + final double d = _quadDeviation(pts, r); + if (d < best) { + best = d; + bestSet = r; + } + } + } + } + return bestSet; +} + +/// 最大偏距:所有点到直线 a–b 的距离最大值。 +double _maxDeviation(List pts, Offset a, Offset b) { + double m = 0; + for (final Offset p in pts) { + final double d = archDistToSegment(p, a, b); + if (d > m) m = d; + } + return m; +} + +/// 去掉间距过近的重复点。 +List _clean(List raw) { + final List out = []; + for (final Offset p in raw) { + if (out.isEmpty || (p - out.last).distance > 0.6) out.add(p); + } + return out; +} + +/// 折线总长。 +double _polyLength(List pts) { + double s = 0; + for (int i = 1; i < pts.length; i++) { + s += (pts[i] - pts[i - 1]).distance; + } + return s; +} + +/// 外接矩形。 +Rect _bounds(List pts) { + double l = pts.first.dx, r = l, t = pts.first.dy, b = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + return Rect.fromLTRB(l, t, r, b); +} + +/// 重采样成 [n] 个均匀点(按弧长)。 +List _resample(List pts, int n) { + final double len = _polyLength(pts); + if (len <= 0.0001 || pts.length < 2) return List.of(pts); + final double step = len / (n - 1); + final List out = [pts.first]; + double need = step; + Offset prev = pts.first; + for (int i = 1; i < pts.length && out.length < n; i++) { + Offset cur = pts[i]; + double segLen = (cur - prev).distance; + while (segLen >= need && segLen > 0.0001 && out.length < n) { + final Offset np = prev + (cur - prev) * (need / segLen); + out.add(np); + prev = np; + segLen = (cur - prev).distance; + need = step; + } + need -= segLen; + prev = cur; + } + while (out.length < n) { + out.add(pts.last); + } + return out; +} + +/// Douglas-Peucker 顶点索引([closed] 时把首点视为终点,去掉重复)。 +List _rdpIndices(List pts, double eps, {bool closed = false}) { + final List work = + closed ? [...pts, pts.first] : pts; + final List keep = List.filled(work.length, false); + keep[0] = true; + keep[work.length - 1] = true; + final List> stack = >[ + [0, work.length - 1], + ]; + while (stack.isNotEmpty) { + final List seg = stack.removeLast(); + final int s = seg[0]; + final int e = seg[1]; + double maxD = 0; + int idx = -1; + for (int i = s + 1; i < e; i++) { + final double d = archDistToSegment(work[i], work[s], work[e]); + if (d > maxD) { + maxD = d; + idx = i; + } + } + if (idx >= 0 && maxD > eps) { + keep[idx] = true; + stack.add([s, idx]); + stack.add([idx, e]); + } + } + final List out = []; + for (int i = 0; i < work.length; i++) { + if (keep[i]) out.add(i); + } + if (closed && out.isNotEmpty && out.last == work.length - 1) { + out.removeLast(); + } + return out; +} + +/// 合并近似共线的折点(也合并过短的边),直到稳定;最少保留 3 个顶点。 +List _mergeCollinear( + List pts, + List idx, + double tolDeg, + double minSeg, +) { + final List cur = List.of(idx); + bool changed = true; + while (changed && cur.length > 3) { + changed = false; + final int n = cur.length; + for (int i = 0; i < n; i++) { + final Offset p = pts[cur[(i - 1 + n) % n]]; + final Offset v = pts[cur[i]]; + final Offset q = pts[cur[(i + 1) % n]]; + final double turn = _turnDeg(p, v, q); + final bool tiny = (v - p).distance < minSeg || (q - v).distance < minSeg; + if (turn < tolDeg || tiny) { + cur.removeAt(i); + changed = true; + break; + } + } + } + return cur; +} + +/// 折点转向角(度):0 = 直线方向,90 = 直角折点。 +double _turnDeg(Offset p, Offset v, Offset q) { + final Offset a = v - p; + final Offset b = q - v; + final double la = a.distance; + final double lb = b.distance; + if (la < 0.001 || lb < 0.001) return 0; + final double c = (_dot(a, b) / (la * lb)).clamp(-1.0, 1.0); + return math.acos(c) * 180 / math.pi; +} + +/// 点积(dart:ui 的 Offset 无 dot,自带实现)。 +double _dot(Offset a, Offset b) => a.dx * b.dx + a.dy * b.dy; diff --git a/lib/arch/arch_samples.dart b/lib/arch/arch_samples.dart new file mode 100644 index 0000000..246835f --- /dev/null +++ b/lib/arch/arch_samples.dart @@ -0,0 +1,361 @@ +/// 架构图示例场景:自动化产线系统架构(手绘稿 / 完成图两种状态), +/// 以及「手绘识别对照表」的素材(用于演示与截图)。 +/// +/// 「手绘稿」= 把每个标准图形的轮廓采样成带抖动的单笔墨迹 + 箭头墨迹; +/// 「完成图」= 识别后的标准图形 + 吸附连线 + 标签文字。 +/// 两个场景共用同一套几何,保证演示「画 → 识别 → 成图」的完整链路。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import 'arch_models.dart'; +import 'arch_painter.dart'; + +/// 示例场景种类。 +enum ArchDemoKind { + /// 手绘稿(全部为墨迹,等待识别)。 + ink, + + /// 完成图(标准图形 + 连线 + 文字)。 + done, +} + +/// 示例场景中的一个图形定义。 +class ArchDemoEntry { + /// 构造图形定义。 + const ArchDemoEntry( + this.id, + this.type, + this.rect, + this.color, + this.text, { + this.radius = 0, + this.dir = 0, + }); + + /// 图形 id。 + final String id; + + /// 图形类型。 + final ArchShapeType type; + + /// 外接矩形(世界坐标)。 + final Rect rect; + + /// 主题色。 + final int color; + + /// 图内文字。 + final String text; + + /// 圆角半径(圆角矩形)。 + final double radius; + + /// 朝向(三角形)。 + final int dir; +} + +/// 示例场景中的一条连线定义。 +class ArchDemoConn { + /// 构造连线定义。 + const ArchDemoConn( + this.from, + this.to, + this.label, { + this.dash = false, + this.route = ArchRoute.straight, + }); + + /// 起点图形 id。 + final String from; + + /// 终点图形 id。 + final String to; + + /// 连线标签。 + final String label; + + /// 是否虚线。 + final bool dash; + + /// 走线方式(直线 / 正交折线)。 + final ArchRoute route; +} + +/// 示例图形清单(两个场景共用)。 +List archDemoEntries() => [ + const ArchDemoEntry('S1', ArchShapeType.cloud, + Rect.fromLTWH(620, 20, 250, 120), 0xFF94A3B8, '云平台 · 远程运维'), + const ArchDemoEntry('S2', ArchShapeType.rect, + Rect.fromLTWH(600, 186, 290, 78), 0xFF38BDF8, '组态上位机 (Windows)'), + const ArchDemoEntry('S3', ArchShapeType.roundRect, + Rect.fromLTWH(628, 310, 234, 66), 0xFFA78BFA, '工业交换机', + radius: 16), + const ArchDemoEntry('S4', ArchShapeType.rect, + Rect.fromLTWH(595, 424, 300, 84), 0xFF4CC9F0, 'PLC 主站\n(EtherCAT)'), + const ArchDemoEntry('S5', ArchShapeType.rect, + Rect.fromLTWH(120, 438, 190, 76), 0xFF34D399, '视觉相机\nGigE'), + const ArchDemoEntry('S6', ArchShapeType.roundRect, + Rect.fromLTWH(1030, 438, 190, 76), 0xFFF472B6, 'IO 模块', + radius: 14), + const ArchDemoEntry('S7', ArchShapeType.rect, + Rect.fromLTWH(540, 560, 240, 76), 0xFFFFD166, '伺服驱动器'), + const ArchDemoEntry('S8', ArchShapeType.ellipse, + Rect.fromLTWH(505, 706, 150, 96), 0xFF38BDF8, '伺服电机'), + const ArchDemoEntry('S9', ArchShapeType.ellipse, + Rect.fromLTWH(820, 706, 180, 96), 0xFF34D399, '气缸 / 传感器'), + const ArchDemoEntry('S10', ArchShapeType.cylinder, + Rect.fromLTWH(140, 690, 150, 130), 0xFFFF8A5C, '历史数据库'), + ]; + +/// 示例连线清单。 +List archDemoConns() => [ + const ArchDemoConn('S1', 'S2', '光纤 / 5G', dash: true), + const ArchDemoConn('S2', 'S3', 'Profinet'), + const ArchDemoConn('S3', 'S4', 'Profinet'), + const ArchDemoConn('S4', 'S5', 'GigE', route: ArchRoute.ortho), + const ArchDemoConn('S4', 'S7', 'EtherCAT'), + const ArchDemoConn('S4', 'S6', 'EtherCAT'), + const ArchDemoConn('S7', 'S8', '动力线'), + const ArchDemoConn('S6', 'S9', '24V IO / 气路'), + const ArchDemoConn('S4', 'S10', 'OPC UA', route: ArchRoute.ortho), + ]; + +/// 由定义构造标准图形。 +ArchShape _shapeOf(ArchDemoEntry e) => ArchShape( + id: e.id, + type: e.type, + rect: e.rect, + radius: e.radius, + dir: e.dir, + fill: archFillOf(e.color), + stroke: e.color, + sw: 1.8, + text: e.text, + ); + +/// 手绘稿场景:所有图形与连线的「原始墨迹」。 +ArchDoc archDemoInkScene() { + final List strokes = []; + final Map byId = {}; + int seed = 7; + const int inkColor = 0xFF64748B; + for (final ArchDemoEntry e in archDemoEntries()) { + byId[e.id] = _shapeOf(e); + final Path path = archShapePath(byId[e.id]!); + final List pts = + archInkOutline(path, seed: seed++, jitter: 1.7, gapFrac: 0.07); + if (pts.length > 4) { + strokes.add(ArchStroke( + id: 'K${strokes.length + 1}', + pts: pts, + color: inkColor, + )); + } + } + for (final ArchDemoConn c in archDemoConns()) { + final ArchShape f = byId[c.from]!; + final ArchShape t = byId[c.to]!; + final Offset a = archBorderPoint(f, t.rect.center); + final Offset b = archBorderPoint(t, f.rect.center); + final List pts = _inkArrow(a, b, seed: seed++); + if (pts.length > 6) { + strokes.add(ArchStroke( + id: 'K${strokes.length + 1}', + pts: pts, + color: inkColor, + )); + } + } + return ArchDoc(strokes: strokes); +} + +/// 完成图场景:标准图形 + 吸附连线 + 标题。 +ArchDoc archDemoDoneScene() { + final List shapes = [ + const ArchShape( + id: 'T0', + type: ArchShapeType.text, + rect: Rect.fromLTWH(120, 40, 430, 40), + fill: 0, + stroke: 0xFF64748B, + sw: 0, + text: '自动化产线 · 系统架构(示例)', + ), + for (final ArchDemoEntry e in archDemoEntries()) _shapeOf(e), + ]; + final Map byId = { + for (final ArchShape s in shapes) s.id: s, + }; + final List conns = []; + for (final ArchDemoConn c in archDemoConns()) { + final ArchShape f = byId[c.from]!; + final ArchShape t = byId[c.to]!; + conns.add(ArchConnector( + id: 'C${conns.length + 1}', + fromId: c.from, + from: f.rect.center, + toId: c.to, + to: t.rect.center, + label: c.label, + dash: c.dash, + route: c.route, + )); + } + return ArchDoc(shapes: shapes, connectors: conns); +} + +/// 「手绘识别对照表」素材:一组(标签, 手绘墨迹),供演示 / 截图逐个识别。 +List<(String, List)> archRecognitionSheet() { + final List<(String, List)> out = <(String, List)>[]; + int seed = 101; + void addStroke(String label, List pts) { + out.add((label, pts)); + } + + void addOutline(String label, ArchShape proto) { + addStroke( + label, + archInkOutline(archShapePath(proto), seed: seed++, jitter: 1.8, gapFrac: 0.07), + ); + } + + ArchShape proto(ArchShapeType type, Rect r, {double radius = 0}) => ArchShape( + id: 'x', + type: type, + rect: r, + radius: radius, + fill: 0, + stroke: 0xFF64748B, + sw: 1.8, + ); + + addStroke('直线', _inkLine(const Offset(24, 128), const Offset(196, 66), seed: seed++)); + addStroke('箭头', _inkArrow(const Offset(24, 132), const Offset(196, 60), seed: seed++)); + addOutline('矩形', proto(ArchShapeType.rect, const Rect.fromLTWH(34, 30, 152, 104))); + addOutline('圆角矩形', + proto(ArchShapeType.roundRect, const Rect.fromLTWH(34, 30, 152, 104), radius: 22)); + addOutline('圆形', proto(ArchShapeType.circle, const Rect.fromLTWH(46, 26, 128, 128))); + addOutline('椭圆', proto(ArchShapeType.ellipse, const Rect.fromLTWH(30, 42, 160, 92))); + addOutline('三角形', proto(ArchShapeType.triangle, const Rect.fromLTWH(44, 26, 140, 118))); + addOutline('菱形', proto(ArchShapeType.diamond, const Rect.fromLTWH(30, 32, 160, 108))); + addStroke( + '折线', + archInkOutline( + Path() + ..moveTo(26, 30) + ..lineTo(26, 96) + ..lineTo(118, 96) + ..lineTo(118, 142) + ..lineTo(196, 142), + seed: seed++, + jitter: 1.5, + gapFrac: 0, + ), + ); + addStroke( + '曲线', + archInkOutline( + Path() + ..moveTo(24, 122) + ..cubicTo(62, 36, 138, 150, 198, 62), + seed: seed++, + jitter: 1.7, + gapFrac: 0, + ), + ); + return out; +} + +// ===================== 墨迹采样 ===================== + +/// 沿路径采样成一段带抖动的「手绘墨迹」([gapFrac] 为收笔缺口占比)。 +List archInkOutline( + Path path, { + required int seed, + double jitter = 1.7, + double gapFrac = 0.07, +}) { + final List metrics = path.computeMetrics().toList(); + double total = 0; + for (final PathMetric m in metrics) { + total += m.length; + } + if (total < 10) return []; + final math.Random rnd = math.Random(seed); + final List out = []; + final double stop = total * (1 - gapFrac); + final double step = math.max(3.0, total / 260); + double walked = 0; + for (final PathMetric m in metrics) { + double d = 0; + while (d < m.length && walked < stop) { + final Tangent? tan = m.getTangentForOffset(d); + if (tan != null) { + final Offset dir = tan.vector; + final Offset nrm = Offset(-dir.dy, dir.dx); + final double j = (rnd.nextDouble() * 2 - 1) * jitter + + math.sin(d * 0.045 + seed) * jitter * 0.6; + out.add(tan.position + nrm * j); + } + d += step; + walked += step; + } + if (walked >= stop) break; + } + return out; +} + +/// 采样一段直线墨迹。 +List _inkLine(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) { + final math.Random rnd = math.Random(seed); + final List out = []; + final Offset d = b - a; + final double len = d.distance; + if (len < 4) return out; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + for (double t = 0; t <= len - 3; t += 6) { + out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter)); + } + out.add(b); + return out; +} + +/// 采样一段单笔箭头墨迹:箭杆 + 尖端折返的「>」形头部。 +List _inkArrow(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) { + final math.Random rnd = math.Random(seed); + final List out = []; + final Offset d = b - a; + final double len = d.distance; + if (len < 36) return out; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + // 箭杆 + for (double t = 0; t <= len - 4; t += 7) { + out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter)); + } + // 头部:尖端 → 左后 → 右后(同一笔完成) + final double hs = math.min(40, len * 0.18); + final Offset p1 = b + _rot(u, 155) * hs; + final Offset p2 = b + _rot(u, -155) * hs; + final Offset mid = (p1 + p2) / 2; + const int seg = 4; + for (int i = 1; i <= seg; i++) { + out.add(Offset.lerp(b, p1, i / seg)! + n * ((rnd.nextDouble() * 2 - 1) * jitter * 0.5)); + } + for (int i = 1; i <= seg; i++) { + out.add(i <= 2 + ? Offset.lerp(p1, mid, i / 2)! + : Offset.lerp(mid, p2, (i - 2) / (seg - 2))!); + } + return out; +} + +/// 向量旋转(度)。 +Offset _rot(Offset v, double deg) { + final double r = deg * math.pi / 180; + return Offset(v.dx * math.cos(r) - v.dy * math.sin(r), + v.dx * math.sin(r) + v.dy * math.cos(r)); +} diff --git a/lib/arch/arch_symbol_recognizer.dart b/lib/arch/arch_symbol_recognizer.dart new file mode 100644 index 0000000..eedd749 --- /dev/null +++ b/lib/arch/arch_symbol_recognizer.dart @@ -0,0 +1,201 @@ +/// 手绘识别 · 图元库匹配。 +/// +/// 把笔迹(可多笔,顺序无关)与图元库每个符号的轮廓做「归一化双向 +/// chamfer 距离」匹配,返回最相似的图元。 +/// +/// 与内置识别的关系:内置识别(矩形 / 圆 / 箭头 / 折线…)优先且保持不变; +/// **内置识别不了的笔迹再走本匹配器**——因此「图元库可扩展」等价于 +/// 「能手绘识别的图形可扩展」:用户导入 / 自建的图元也能被画出来识别。 +library; + +import 'dart:math' as math; +import 'dart:ui' show Offset, Path, PathMetric, Rect, Tangent; + +import '../library/symbol_library.dart'; + +/// 图元匹配结果。 +class ArchSymbolMatch { + /// 构造。 + const ArchSymbolMatch({required this.symbol, required this.score}); + + /// 命中的图元。 + final LibSymbol symbol; + + /// 双向 chamfer 平均距离(归一化坐标 0..1,越小越像)。 + final double score; +} + +/// 识别阈值(归一化单位):匹配分数大于该值视为「都不像」。 +/// +/// 标定依据(合成笔迹回归):真命中 0.006–0.03(接地 0.006 / 灯 0.013 / +/// 自定义图元≈0.01),乱涂 / 斜线等假命中 ≥0.07;取 0.06 保守稳妥。 +const double kArchSymbolMaxScore = 0.06; + +/// 最佳与次佳的分数差下限:相差太小说明特征不明显,宁可不错认。 +/// (灯 vs 电机 这类相似图形差约 0.010;取 0.008 兼顾召回与精度。) +const double kArchSymbolMargin = 0.008; + +/// 识别笔迹(多笔按点集合并)。 +ArchSymbolMatch? recognizeArchSymbol( + List> strokes, + List catalog, { + double maxScore = kArchSymbolMaxScore, + double margin = kArchSymbolMargin, + int inputSamples = 96, + int refSamples = 128, +}) { + // 每笔独立重采样(避免笔与笔之间产生"跳线"污染),按各笔长度分配采样数。 + final List> parts = >[]; + final List lens = []; + double total = 0; + for (final List s in strokes) { + if (s.length < 2) continue; + double len = 0; + for (int i = 1; i < s.length; i++) { + len += (s[i] - s[i - 1]).distance; + } + if (len < 1e-6) continue; + parts.add(s); + lens.add(len); + total += len; + } + if (parts.isEmpty || total < 1e-6 || catalog.isEmpty) return null; + final List pts = []; + for (int i = 0; i < parts.length; i++) { + final int count = math.max(4, (inputSamples * lens[i] / total).round()); + pts.addAll(_resample(parts[i], count)); + } + if (pts.length < 4) return null; + final _Np input = _Np.of(pts); + if (input.extent < 1e-6) return null; + + // 多尺度:手绘大小 / 完整度与图元不完全一致(少画一笔、比例不同都要容忍), + // 对输入做几档缩放,取最像的一档。 + const List scales = [0.7, 0.85, 1.0, 1.2, 1.45]; + final List> scaled = >[ + for (final double s in scales) + [for (final Offset p in input.pts) p * s], + ]; + + ArchSymbolMatch? best; + double second = double.infinity; + for (final LibSymbol sym in catalog) { + final List refPts = _sampleSymbol(sym, refSamples); + if (refPts.length < 4) continue; + final _Np ref = _Np.of(refPts); + if (ref.extent < 1e-6) continue; + double score = double.infinity; + for (final List sp in scaled) { + final double sc = _chamfer(sp, ref.pts); + if (sc < score) score = sc; + } + if (best == null || score < best.score) { + second = best?.score ?? second; + best = ArchSymbolMatch(symbol: sym, score: score); + } else if (score < second) { + second = score; + } + } + if (best == null) return null; + if (best.score > maxScore) return null; + if (second.isFinite && second - best.score < margin) return null; + return best; +} + +// ===================== 内部实现 ===================== + +/// 归一化点集:中心化 + 按最大边缩放(对平移 / 缩放不敏感)。 +class _Np { + const _Np(this.pts, this.extent); + + final List pts; + final double extent; + + static _Np of(List pts) { + if (pts.isEmpty) return const _Np([], 0); + double l = pts.first.dx, r = l, t = pts.first.dy, b = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + final double ext = math.max(r - l, b - t); + if (ext < 1e-6) return _Np(List.filled(pts.length, Offset.zero), 0); + final Offset c = Offset((l + r) / 2, (t + b) / 2); + return _Np([ + for (final Offset p in pts) + Offset((p.dx - c.dx) / ext, (p.dy - c.dy) / ext), + ], ext); + } +} + +/// 按弧长均匀重采样折线到 [n] 个点。 +List _resample(List pts, int n) { + if (pts.length <= 1) return List.of(pts); + double total = 0; + for (int i = 1; i < pts.length; i++) { + total += (pts[i] - pts[i - 1]).distance; + } + if (total < 1e-6) return [pts.first]; + final List out = [pts.first]; + int seg = 0; + double acc = 0; + double segLen = (pts[1] - pts[0]).distance; + for (int i = 1; i < n; i++) { + final double target = total * i / (n - 1); + while (acc + segLen < target && seg < pts.length - 2) { + acc += segLen; + seg++; + segLen = (pts[seg + 1] - pts[seg]).distance; + } + final double rest = target - acc; + final double t = segLen <= 1e-9 ? 0 : (rest / segLen).clamp(0.0, 1.0); + out.add(Offset.lerp(pts[seg], pts[seg + 1], t)!); + } + return out; +} + +/// 采样图元轮廓(在 100×100 归一化盒内按各子路径长度分配采样点)。 +List _sampleSymbol(LibSymbol sym, int n) { + final Path path = buildSymbolPath(sym, const Rect.fromLTWH(0, 0, 100, 100)); + final List metrics = path.computeMetrics().toList(); + double total = 0; + for (final PathMetric m in metrics) { + total += m.length; + } + if (total < 1e-6) return const []; + final List out = []; + for (final PathMetric m in metrics) { + final int count = math.max(2, (n * m.length / total).round()); + for (int i = 0; i <= count; i++) { + final Tangent? t = m.getTangentForOffset(m.length * i / count); + if (t != null) out.add(t.position); + } + } + return out; +} + +/// 双向 chamfer 平均距离。 +double _chamfer(List a, List b) { + double d1 = 0; + for (final Offset p in a) { + d1 += _nearest(p, b); + } + d1 /= a.length; + double d2 = 0; + for (final Offset p in b) { + d2 += _nearest(p, a); + } + d2 /= b.length; + return (d1 + d2) / 2; +} + +double _nearest(Offset p, List pts) { + double best = double.infinity; + for (final Offset q in pts) { + final double d = (p - q).distanceSquared; + if (d < best) best = d; + } + return math.sqrt(best); +} diff --git a/lib/library/symbol_library.dart b/lib/library/symbol_library.dart new file mode 100644 index 0000000..f89b1b8 --- /dev/null +++ b/lib/library/symbol_library.dart @@ -0,0 +1,640 @@ +/// 图元库(电气符号 / 通用图元)数据层。 +/// +/// - 内置符号:[SymbolLibrary.builtin],随安装包发布(只读,代码内定义); +/// - 用户符号:`library/symbols/*.symbol.json`(见 `app_paths.dart`), +/// 可新增 / 覆盖 / 删除,跨工程复用; +/// - 坐标约定:符号在 **100×100 归一化画布** 内绘制((0,0) 左上、(100,100) +/// 右下),引脚 [SymPin] 位于边界附近;实际绘制时按目标矩形等比换算; +/// - 单位:与画布一致(1 世界单位 = 1 mm)。 +/// +/// 供「电器原理图」等模块使用(P2:图元库先行;画布 / 布线后续接入)。 +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; +import 'dart:ui' show Offset, Path, Rect; + +import '../persistence/app_paths.dart'; + +// ===================== 模型 ===================== + +/// 符号基元类型。 +enum SymPrimKind { + /// 直线:pts = [x1, y1, x2, y2]。 + line, + + /// 折线:pts = [x1, y1, x2, y2, …]。 + polyline, + + /// 圆:pts = [cx, cy],[SymPrim.r] 为半径。 + circle, + + /// 圆弧:pts = [cx, cy],[SymPrim.r]、[SymPrim.startDeg]、[SymPrim.sweepDeg]。 + arc, + + /// 矩形:pts = [x, y, w, h]。 + rect, + + /// 文本:pts = [x, y] 为左上角锚点,[SymPrim.label] 为文字。 + text, +} + +/// 基元 JSON 名称 ↔ 枚举。 +String symPrimKindName(SymPrimKind k) => switch (k) { + SymPrimKind.line => 'line', + SymPrimKind.polyline => 'polyline', + SymPrimKind.circle => 'circle', + SymPrimKind.arc => 'arc', + SymPrimKind.rect => 'rect', + SymPrimKind.text => 'text', + }; + +SymPrimKind symPrimKindFrom(String s) => switch (s) { + 'polyline' => SymPrimKind.polyline, + 'circle' => SymPrimKind.circle, + 'arc' => SymPrimKind.arc, + 'rect' => SymPrimKind.rect, + 'text' => SymPrimKind.text, + _ => SymPrimKind.line, + }; + +/// 符号基元(几何 / 文本)。 +class SymPrim { + /// 构造。 + const SymPrim({ + required this.kind, + this.pts = const [], + this.r = 0, + this.startDeg = 0, + this.sweepDeg = 0, + this.label = '', + }); + + /// 类型。 + final SymPrimKind kind; + + /// 归一化坐标(含义随类型)。 + final List pts; + + /// 半径(circle / arc)。 + final double r; + + /// 起始角(度,arc)。 + final double startDeg; + + /// 扫掠角(度,arc)。 + final double sweepDeg; + + /// 文本内容(text)。 + final String label; + + /// 序列化。 + Map toJson() => { + 'kind': symPrimKindName(kind), + 'pts': pts, + if (r != 0) 'r': r, + if (startDeg != 0) 'start': startDeg, + if (sweepDeg != 0) 'sweep': sweepDeg, + if (label.isNotEmpty) 'label': label, + }; + + /// 反序列化。 + static SymPrim fromJson(Map j) => SymPrim( + kind: symPrimKindFrom(j['kind'] as String? ?? 'line'), + pts: ((j['pts'] as List?) ?? []) + .map((dynamic e) => (e as num).toDouble()) + .toList(), + r: (j['r'] as num?)?.toDouble() ?? 0, + startDeg: (j['start'] as num?)?.toDouble() ?? 0, + sweepDeg: (j['sweep'] as num?)?.toDouble() ?? 0, + label: j['label'] as String? ?? '', + ); +} + +/// 符号引脚(连接点;坐标同样为 100×100 归一化)。 +class SymPin { + /// 构造。 + const SymPin({ + required this.id, + this.name = '', + required this.x, + required this.y, + this.dir = 'b', + }); + + /// 引脚 id(如 `1` / `2` / `A1`)。 + final String id; + + /// 展示名(缺省用 id)。 + final String name; + + /// 归一化坐标 x。 + final double x; + + /// 归一化坐标 y。 + final double y; + + /// 出线方向(t 上 / b 下 / l 左 / r 右)。 + final String dir; + + /// 序列化。 + Map toJson() => { + 'id': id, + if (name.isNotEmpty) 'name': name, + 'x': x, + 'y': y, + 'dir': dir, + }; + + /// 反序列化。 + static SymPin fromJson(Map j) => SymPin( + id: j['id'] as String? ?? '', + name: j['name'] as String? ?? '', + x: (j['x'] as num?)?.toDouble() ?? 0, + y: (j['y'] as num?)?.toDouble() ?? 0, + dir: j['dir'] as String? ?? 'b', + ); +} + +/// 图元符号。 +class LibSymbol { + /// 构造。 + const LibSymbol({ + required this.id, + required this.name, + required this.category, + required this.prims, + required this.pins, + this.tags = const [], + }); + + /// 符号 id(稳定标识;用户符号文件名由它生成)。 + final String id; + + /// 名称(如「断路器」)。 + final String name; + + /// 分类(如「开关电器」)。 + final String category; + + /// 检索标签。 + final List tags; + + /// 基元列表。 + final List prims; + + /// 引脚列表。 + final List pins; + + /// 序列化。 + Map toJson() => { + 'id': id, + 'name': name, + 'category': category, + 'tags': tags, + 'prims': >[ + for (final SymPrim p in prims) p.toJson(), + ], + 'pins': >[ + for (final SymPin p in pins) p.toJson(), + ], + }; + + /// 反序列化。 + static LibSymbol fromJson(Map j) => LibSymbol( + id: j['id'] as String? ?? '', + name: j['name'] as String? ?? '未命名', + category: j['category'] as String? ?? '未分类', + tags: ((j['tags'] as List?) ?? []) + .map((dynamic e) => e.toString()) + .toList(), + prims: ((j['prims'] as List?) ?? []) + .map((dynamic e) => SymPrim.fromJson(e as Map)) + .toList(), + pins: ((j['pins'] as List?) ?? []) + .map((dynamic e) => SymPin.fromJson(e as Map)) + .toList(), + ); + + /// 序列化为带缩进的 JSON 文本。 + String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); +} + +// ===================== 归一化 → 画布几何 ===================== + +/// 归一化坐标(0..100)→ [box] 内的坐标。 +Offset symPt(double x, double y, Rect box) => Offset( + box.left + x / 100 * box.width, + box.top + y / 100 * box.height, + ); + +/// 单个基元的路径(文本基元不产生路径,返回 null)。 +Path? symPrimPath(SymPrim p, Rect box) { + switch (p.kind) { + case SymPrimKind.line: + case SymPrimKind.polyline: + if (p.pts.length < 4) return null; + final Path path = Path() + ..moveTo(symPt(p.pts[0], p.pts[1], box).dx, + symPt(p.pts[0], p.pts[1], box).dy); + for (int i = 2; i + 1 < p.pts.length; i += 2) { + final Offset o = symPt(p.pts[i], p.pts[i + 1], box); + path.lineTo(o.dx, o.dy); + } + return path; + case SymPrimKind.circle: + if (p.pts.length < 2) return null; + final Offset c = symPt(p.pts[0], p.pts[1], box); + final double r = p.r / 100 * ((box.width + box.height) / 2); + return Path()..addOval(Rect.fromCircle(center: c, radius: r)); + case SymPrimKind.arc: + if (p.pts.length < 2) return null; + final Offset c = symPt(p.pts[0], p.pts[1], box); + final double r = p.r / 100 * ((box.width + box.height) / 2); + return Path() + ..addArc( + Rect.fromCircle(center: c, radius: r), + p.startDeg * math.pi / 180, + p.sweepDeg * math.pi / 180, + ); + case SymPrimKind.rect: + if (p.pts.length < 4) return null; + final Offset tl = symPt(p.pts[0], p.pts[1], box); + final Rect r = Rect.fromLTWH( + tl.dx, + tl.dy, + p.pts[2] / 100 * box.width, + p.pts[3] / 100 * box.height, + ); + return Path()..addRect(r); + case SymPrimKind.text: + return null; + } +} + +/// 整个符号的几何路径(不含文本)。 +Path buildSymbolPath(LibSymbol s, Rect box) { + final Path out = Path(); + for (final SymPrim p in s.prims) { + final Path? sub = symPrimPath(p, box); + if (sub != null) out.addPath(sub, Offset.zero); + } + return out; +} + +/// 图元自然边界(100×100 归一化空间内所有基元的外接矩形;最小 20×20)。 +Rect symbolNaturalBounds(LibSymbol s) { + double? l, t, r, b; + void inc(double x, double y) { + l = (l == null || x < l!) ? x : l; + t = (t == null || y < t!) ? y : t; + r = (r == null || x > r!) ? x : r; + b = (b == null || y > b!) ? y : b; + } + + for (final SymPrim p in s.prims) { + switch (p.kind) { + case SymPrimKind.line: + case SymPrimKind.polyline: + for (int i = 0; i + 1 < p.pts.length; i += 2) { + inc(p.pts[i], p.pts[i + 1]); + } + case SymPrimKind.circle: + case SymPrimKind.arc: + if (p.pts.length >= 2) { + inc(p.pts[0] - p.r, p.pts[1] - p.r); + inc(p.pts[0] + p.r, p.pts[1] + p.r); + } + case SymPrimKind.rect: + if (p.pts.length >= 4) { + inc(p.pts[0], p.pts[1]); + inc(p.pts[0] + p.pts[2], p.pts[1] + p.pts[3]); + } + case SymPrimKind.text: + if (p.pts.length >= 2) inc(p.pts[0], p.pts[1]); + } + } + if (l == null || t == null || r == null || b == null) { + return const Rect.fromLTWH(0, 0, 100, 100); + } + // 最小尺寸保底(避免退化成线 / 点)。 + double w = r! - l!; + double h = b! - t!; + if (w < 20) { + l = l! - (20 - w) / 2; + w = 20; + } + if (h < 20) { + t = t! - (20 - h) / 2; + h = 20; + } + return Rect.fromLTWH(l!, t!, w, h).inflate(2); +} + +/// 运行时图元缓存(内置 + 用户;启动与导入 / 保存 / 删除后刷新)。 +/// +/// 绘制与手绘识别需要同步访问图元列表,故在内存中保持一份。 +class SymbolCache { + SymbolCache._(); + + static List _all = List.of(SymbolLibrary.builtin); + static Map _byId = { + for (final LibSymbol s in SymbolLibrary.builtin) s.id: s, + }; + + /// 全部图元(内置 + 用户)。 + static List get all => _all; + + /// 按 id 查找图元。 + static LibSymbol? byId(String id) => _byId[id]; + + /// 重新加载(应用启动 / 导入 / 保存 / 删除后调用)。 + static Future refresh() async { + final List list = await SymbolLibrary.all(); + _all = list; + _byId = { + for (final LibSymbol s in list) s.id: s, + }; + } +} + +// ===================== 库(内置 + 用户) ===================== + +/// 图元库:内置符号 + 用户目录加载 / 保存 / 删除。 +class SymbolLibrary { + SymbolLibrary._(); + + /// 用户符号文件名后缀。 + static const String fileSuffix = '.symbol.json'; + + /// 是否为内置符号 id(内置图元不可删除)。 + static bool isBuiltinId(String id) => + builtin.any((LibSymbol s) => s.id == id); + + // 垂直元件的通用引脚(上 / 下)。 + static const List _vpins = [ + SymPin(id: '1', x: 50, y: 0, dir: 't'), + SymPin(id: '2', x: 50, y: 100, dir: 'b'), + ]; + + /// 内置符号(电气常用图元;100×100 归一化)。 + static const List builtin = [ + LibSymbol( + id: 'qf-brk', + name: '断路器 QF', + category: '开关电器', + tags: ['断路器', '空开', 'QF', '开关'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 34]), + SymPrim(kind: SymPrimKind.line, pts: [50, 34, 66, 56]), + SymPrim(kind: SymPrimKind.circle, pts: [50, 66], r: 3.5), + SymPrim(kind: SymPrimKind.line, pts: [50, 70, 50, 100]), + SymPrim(kind: SymPrimKind.text, pts: [72, 26], label: 'QF'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'fu-fuse', + name: '熔断器 FU', + category: '保护电器', + tags: ['熔断器', '保险', 'FU'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 32]), + SymPrim(kind: SymPrimKind.rect, pts: [38, 32, 24, 36]), + SymPrim(kind: SymPrimKind.line, pts: [50, 32, 50, 68]), + SymPrim(kind: SymPrimKind.line, pts: [50, 68, 50, 100]), + SymPrim(kind: SymPrimKind.text, pts: [68, 26], label: 'FU'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'km-coil', + name: '接触器线圈 KM', + category: '开关电器', + tags: ['接触器', '线圈', 'KM'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 30]), + SymPrim(kind: SymPrimKind.rect, pts: [32, 30, 36, 40]), + SymPrim(kind: SymPrimKind.text, pts: [40, 44], label: 'KM'), + SymPrim(kind: SymPrimKind.line, pts: [50, 70, 50, 100]), + ], + pins: [ + SymPin(id: 'A1', x: 50, y: 0, dir: 't'), + SymPin(id: 'A2', x: 50, y: 100, dir: 'b'), + ], + ), + LibSymbol( + id: 'no-contact', + name: '常开触点', + category: '开关电器', + tags: ['常开', '动合', 'NO', '触点'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 40]), + SymPrim(kind: SymPrimKind.line, pts: [50, 40, 68, 60]), + SymPrim(kind: SymPrimKind.line, pts: [50, 60, 50, 100]), + ], + pins: _vpins, + ), + LibSymbol( + id: 'nc-contact', + name: '常闭触点', + category: '开关电器', + tags: ['常闭', '动断', 'NC', '触点'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 40]), + SymPrim(kind: SymPrimKind.line, pts: [50, 40, 50, 60]), + SymPrim(kind: SymPrimKind.line, pts: [50, 60, 50, 100]), + SymPrim(kind: SymPrimKind.line, pts: [40, 52, 60, 52]), + ], + pins: _vpins, + ), + LibSymbol( + id: 'sb-no', + name: '按钮(常开)SB', + category: '主令电器', + tags: ['按钮', 'SB', '启动'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [40, 26, 60, 26]), + SymPrim(kind: SymPrimKind.line, pts: [50, 26, 50, 40]), + SymPrim(kind: SymPrimKind.line, pts: [50, 40, 66, 58]), + SymPrim(kind: SymPrimKind.line, pts: [50, 58, 50, 78]), + SymPrim(kind: SymPrimKind.line, pts: [50, 78, 50, 100]), + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 26]), + SymPrim(kind: SymPrimKind.text, pts: [68, 30], label: 'SB'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'hl-lamp', + name: '指示灯 HL', + category: '指示器件', + tags: ['指示灯', '信号灯', 'HL'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 28]), + SymPrim(kind: SymPrimKind.circle, pts: [50, 50], r: 22), + SymPrim(kind: SymPrimKind.line, pts: [36, 36, 64, 64]), + SymPrim(kind: SymPrimKind.line, pts: [64, 36, 36, 64]), + SymPrim(kind: SymPrimKind.line, pts: [50, 72, 50, 100]), + SymPrim(kind: SymPrimKind.text, pts: [72, 34], label: 'HL'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'motor-m', + name: '电机 M', + category: '负载', + tags: ['电机', '马达', 'M'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 26]), + SymPrim(kind: SymPrimKind.circle, pts: [50, 50], r: 24), + SymPrim(kind: SymPrimKind.text, pts: [42, 42], label: 'M'), + SymPrim(kind: SymPrimKind.line, pts: [50, 74, 50, 100]), + ], + pins: _vpins, + ), + LibSymbol( + id: 'fr-thermal', + name: '热继电器 FR', + category: '保护电器', + tags: ['热继电器', '过载', 'FR'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 22]), + SymPrim(kind: SymPrimKind.rect, pts: [40, 22, 20, 20]), + SymPrim(kind: SymPrimKind.line, pts: [40, 42, 60, 22]), + SymPrim(kind: SymPrimKind.line, pts: [50, 42, 50, 100]), + SymPrim(kind: SymPrimKind.text, pts: [68, 24], label: 'FR'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'terminal', + name: '端子 / 接线点', + category: '连接器件', + tags: ['端子', '接线', '连接点'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 38]), + SymPrim(kind: SymPrimKind.rect, pts: [40, 38, 20, 24]), + SymPrim(kind: SymPrimKind.line, pts: [50, 62, 50, 100]), + ], + pins: _vpins, + ), + LibSymbol( + id: 'pe-ground', + name: '接地 PE', + category: '连接器件', + tags: ['接地', '地', 'PE'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 52]), + SymPrim(kind: SymPrimKind.line, pts: [30, 52, 70, 52]), + SymPrim(kind: SymPrimKind.line, pts: [38, 62, 62, 62]), + SymPrim(kind: SymPrimKind.line, pts: [45, 72, 55, 72]), + ], + pins: [SymPin(id: '1', x: 50, y: 0, dir: 't')], + ), + LibSymbol( + id: 'resistor', + name: '电阻 R', + category: '无源元件', + tags: ['电阻', 'R'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 34]), + SymPrim(kind: SymPrimKind.rect, pts: [38, 34, 24, 32]), + SymPrim(kind: SymPrimKind.line, pts: [50, 66, 50, 100]), + SymPrim(kind: SymPrimKind.text, pts: [70, 42], label: 'R'), + ], + pins: _vpins, + ), + LibSymbol( + id: 'coil-ka', + name: '继电器线圈 KA', + category: '开关电器', + tags: ['继电器', '线圈', 'KA'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 30]), + SymPrim(kind: SymPrimKind.rect, pts: [32, 30, 36, 40]), + SymPrim(kind: SymPrimKind.text, pts: [40, 44], label: 'KA'), + SymPrim(kind: SymPrimKind.line, pts: [50, 70, 50, 100]), + ], + pins: [ + SymPin(id: 'A1', x: 50, y: 0, dir: 't'), + SymPin(id: 'A2', x: 50, y: 100, dir: 'b'), + ], + ), + LibSymbol( + id: 'dc-supply', + name: '直流电源 DC', + category: '电源', + tags: ['电源', '直流', 'DC', '电池'], + prims: [ + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 40]), + SymPrim(kind: SymPrimKind.line, pts: [32, 40, 68, 40]), + SymPrim(kind: SymPrimKind.line, pts: [42, 50, 58, 50]), + SymPrim(kind: SymPrimKind.line, pts: [32, 60, 68, 60]), + SymPrim(kind: SymPrimKind.line, pts: [42, 70, 58, 70]), + SymPrim(kind: SymPrimKind.line, pts: [50, 70, 50, 100]), + ], + pins: [ + SymPin(id: '+', x: 50, y: 0, dir: 't'), + SymPin(id: '-', x: 50, y: 100, dir: 'b'), + ], + ), + ]; + + /// 文件名安全化。 + static String _safeId(String id) => + id.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_'); + + /// 用户符号目录(可注入用于测试)。 + static Future _dir(Directory? custom) async => + custom ?? await AppPaths.symbolsDir(); + + /// 读取用户符号(目录缺失 / 文件损坏时跳过,不抛异常)。 + static Future> loadUser({Directory? dir}) async { + try { + final Directory d = await _dir(dir); + if (!await d.exists()) return []; + final List out = []; + await for (final FileSystemEntity e in d.list()) { + if (e is! File || !e.path.endsWith(fileSuffix)) continue; + try { + out.add(LibSymbol.fromJson( + jsonDecode(await e.readAsString()) as Map)); + } catch (_) {} + } + return out; + } catch (_) { + return []; + } + } + + /// 全部符号:内置 + 用户(同 id 时用户覆盖内置)。 + static Future> all({Directory? dir}) async { + final List user = await loadUser(dir: dir); + final Set userIds = { + for (final LibSymbol s in user) s.id, + }; + return [ + for (final LibSymbol s in builtin) + if (!userIds.contains(s.id)) s, + ...user, + ]; + } + + /// 保存用户符号(已存在同 id 时覆盖)。 + static Future saveUser(LibSymbol s, {Directory? dir}) async { + final Directory d = await _dir(dir); + await d.create(recursive: true); + final File f = + File('${d.path}${Platform.pathSeparator}${_safeId(s.id)}$fileSuffix'); + await f.writeAsString(s.encode(), flush: true); + } + + /// 删除用户符号;不存在时静默。 + static Future deleteUser(String id, {Directory? dir}) async { + final Directory d = await _dir(dir); + final File f = + File('${d.path}${Platform.pathSeparator}${_safeId(id)}$fileSuffix'); + if (await f.exists()) await f.delete(); + } +} diff --git a/lib/main.dart b/lib/main.dart index 418a97d..78d548e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -13,7 +13,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'license/license_service.dart'; +import 'library/symbol_library.dart'; import 'model/models.dart'; +import 'modules/module_registry.dart'; +import 'persistence/app_paths.dart'; import 'persistence/storage.dart'; import 'state/app_controller.dart'; import 'theme/tokens.dart'; @@ -58,6 +61,12 @@ class _SequenceDiagramAppState extends State { void initState() { super.initState(); _controller = AppController()..start(); + // 空白启动:先进入首页,由用户选择文档类型再进入模块工作区。 + _controller.goHome(); + // 素材库目录(library/symbols|images|templates):确保存在(失败静默)。 + AppPaths.ensureLibrary(); + // 图元库缓存(内置 + library/symbols/*.symbol.json):绘制与识别共用。 + SymbolCache.refresh(); _controller.addListener(_updateWindowTitle); // 启动即校验授权(读取可执行文件同级 license/*.lic)。 LicenseService.instance.init().then((LicenseInfo info) { @@ -78,15 +87,23 @@ class _SequenceDiagramAppState extends State { /// 原生窗口标题通道(在 Windows runner 中实现 SetWindowText)。 static const MethodChannel _windowChannel = MethodChannel('seqstudio/window'); - /// 更新原生窗口标题为「时序图设计 - <文件名 | 未命名文件>」, + /// 更新原生窗口标题为「模块名 - <文件名 | 未命名文件>」, /// 有未保存修改时追加 ` *`。 void _updateWindowTitle() { - final String name = _controller.filePath == null + final String name = _controller.currentFilePath == null ? '未命名文件' - : _controller.filePath!.split(RegExp(r'[\\/]')).last; + : _controller.currentFilePath!.split(RegExp(r'[\\/]')).last; final String dirty = _controller.dirty ? ' *' : ''; + // 标题走模块注册表(首页显示品牌名,不带文件名)。 + if (_controller.appMode == AppMode.home) { + _windowChannel + .invokeMethod('setTitle', 'EDC|易得设计') + .catchError((Object _) {}); + return; + } + final String brand = appModeLabel(_controller.appMode); _windowChannel - .invokeMethod('setTitle', '时序图设计 - $name$dirty') + .invokeMethod('setTitle', '$brand - $name$dirty') .catchError((Object _) {}); } @@ -142,7 +159,9 @@ class _SequenceDiagramAppState extends State { return; } // 恢复流程:choice == 1 走 .bak 备份,否则走自动快照;解码失败时静默忽略。 + // 当前快照仅为时序图文档:恢复前先切到对应模块(避免停留在首页看不到内容)。 try { + _controller.setAppMode(AppMode.sequence); if (choice == 1 && info.bakContent != null) { _controller.loadProject(Project.decode(info.bakContent!), path: info.projectPath, dirty: true); } else { @@ -161,7 +180,7 @@ class _SequenceDiagramAppState extends State { builder: (BuildContext context, Widget? child) { final Tokens tokens = Tokens.of(_controller.brightness); return MaterialApp( - title: '时序图设计 · Sequence Diagram Studio', + title: 'EDC|易得设计 · Easy Design Collection', debugShowCheckedModeBanner: false, theme: buildTheme(tokens), // 固定文本缩放;系统栏图标随主题亮度自动切换(透明系统栏, diff --git a/lib/model/models.dart b/lib/model/models.dart index b73deda..6a7b340 100644 --- a/lib/model/models.dart +++ b/lib/model/models.dart @@ -10,6 +10,8 @@ library; import 'dart:convert'; +import '../arch/arch_models.dart'; + /// 主视图模式。 enum ViewMode { /// 条形(甘特式)节拍视图。 @@ -22,6 +24,18 @@ enum ViewMode { flow, } +/// 顶层设计模块(左上角 logo「设计合集」菜单切换的对象)。 +enum AppMode { + /// 首页(空白启动:新建 / 打开文档前的工作台)。 + home, + + /// 时序图设计(条形 / 圆周 / 流程图)。 + sequence, + + /// 架构图设计(手绘识别 / 系统架构)。 + architecture, +} + /// 时间单位。 enum TimeUnit { /// 毫秒。 @@ -106,7 +120,7 @@ String colorToHex(int argb) { return '#${rgb.toRadixString(16).padLeft(6, '0')}'; } -/// 将 `#rrggbb`(可带 `#`,大小写均可)解析为不透明的 ARGB 整数。 +/// 解析 `#rrggbb`(可带 `#`,大小写均可)为不透明的 ARGB 整数。 /// /// 参数 [hex]:十六进制颜色字符串。 /// 返回:`0xFF000000 | rgb`;解析失败时回退到默认色 `0x4CC9F0`。 @@ -116,6 +130,15 @@ int hexToColor(String hex) { return 0xFF000000 | (rgb & 0xFFFFFF); } +/// 组合颜色与可选透明度(旧文件无 `colorA` 时保持不透明)。 +/// +/// `#rrggbb` 格式本身不含透明度;当颜色的 alpha ≠ FF 时额外写 `colorA` 字段, +/// 保证保存 / 重新打开后颜色完全一致。 +int withColorAlpha(int argb, Object? alpha) { + if (alpha is! num) return argb; + return ((alpha.toInt() & 0xFF) << 24) | (argb & 0xFFFFFF); +} + /// 动作之间的时序依赖:由 [fromId] 指向 [toId],描述二者的开始/结束约束。 /// /// 依赖会被关键路径算法(见 AppController._recomputeCritical)用来计算 @@ -293,7 +316,7 @@ class Action { ); } - /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存,依赖递归序列化。 + /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存(半透明时另存 `colorA`),依赖递归序列化。 Map toJson() => { 'id': id, 'name': name, @@ -303,6 +326,7 @@ class Action { 'durationAngle': durationAngle, 'layer': layer, 'color': colorToHex(color), + if (((color >> 24) & 0xFF) != 0xFF) 'colorA': (color >> 24) & 0xFF, 'row': row, 'deps': deps.map((Dependency d) => d.toJson()).toList(), }; @@ -317,7 +341,8 @@ class Action { startAngle: (j['startAngle'] as num?)?.toDouble() ?? 0, durationAngle: (j['durationAngle'] as num?)?.toDouble() ?? 0, layer: (j['layer'] as num?)?.toInt() ?? 0, - color: hexToColor(j['color'] as String? ?? '#4cc9f0'), + color: withColorAlpha( + hexToColor(j['color'] as String? ?? '#4cc9f0'), j['colorA']), row: (j['row'] as num?)?.toInt() ?? -1, deps: ((j['deps'] as List?) ?? []) .map((dynamic e) => Dependency.fromJson(e as Map)) @@ -361,12 +386,13 @@ class Station { ); } - /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存。 + /// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存(半透明时另存 `colorA`)。 Map toJson() => { 'id': id, 'name': name, 'order': order, 'color': colorToHex(color), + if (((color >> 24) & 0xFF) != 0xFF) 'colorA': (color >> 24) & 0xFF, }; /// 从 JSON 反序列化;缺失字段使用默认值。 @@ -375,7 +401,8 @@ class Station { id: j['id'] as String? ?? 'ST1', name: j['name'] as String? ?? '工位', order: (j['order'] as num?)?.toInt() ?? 0, - color: hexToColor(j['color'] as String? ?? '#4cc9f0'), + color: withColorAlpha( + hexToColor(j['color'] as String? ?? '#4cc9f0'), j['colorA']), ); } } @@ -778,7 +805,7 @@ class Project { /// [units]:单位设置;[viewState]:视图状态。 const Project({ required this.name, - this.schema = 'seqdiagram/1.2', + this.schema = 'edc/1.3', required this.cycle, required this.stations, required this.actions, @@ -790,6 +817,7 @@ class Project { this.laneSlots = const {}, this.autoSaveEnabled = true, this.autoSaveMinutes = 10, + this.arch = ArchDoc.empty, }); /// 项目名称。 @@ -847,6 +875,12 @@ class Project { /// 仅在文档已有保存路径(手动保存过一次)后生效;自动保存会同时更新 `.bak`。 final int autoSaveMinutes; + /// 架构图文档(图形 / 墨迹 / 连线 + 视口)。 + /// + /// 与 [actions] 等时序数据同存于一个工程文件,但**暂不互通**: + /// 架构图不引用工位 / 动作,也不参与节拍与关键路径计算。 + final ArchDoc arch; + /// 按 id 查找动作;[id] 为 null 或未找到时返回 null。 Action? actionById(String? id) { if (id == null) return null; @@ -914,6 +948,7 @@ class Project { Map? laneSlots, bool? autoSaveEnabled, int? autoSaveMinutes, + ArchDoc? arch, }) { return Project( name: name ?? this.name, @@ -929,11 +964,12 @@ class Project { laneSlots: laneSlots ?? this.laneSlots, autoSaveEnabled: autoSaveEnabled ?? this.autoSaveEnabled, autoSaveMinutes: autoSaveMinutes ?? this.autoSaveMinutes, + arch: arch ?? this.arch, ); } - /// 序列化为 JSON。外层包含 `schema` 版本号,实际数据位于 `project` 子对象。 - Map toJson() => { + /// 序列化为 JSON。[includeArch] 为 false 时省略架构图部分。 + Map toJson({bool includeArch = true}) => { 'schema': schema, 'project': { 'name': name, @@ -950,11 +986,16 @@ class Project { }, 'autoSaveEnabled': autoSaveEnabled, 'autoSaveMinutes': autoSaveMinutes, + if (includeArch) 'arch': arch.toJson(), }, }; /// 序列化为带两空格缩进的 JSON 文本,便于人工阅读与 diff。 - String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); + /// + /// [includeArch] 为 false 时**不写入架构图部分**(时序图文档 `*.seq.json` + /// 只含时序内容;架构图另存为 `*.arch.json`)。 + String encode({bool includeArch = true}) => const JsonEncoder.withIndent(' ') + .convert(toJson(includeArch: includeArch)); /// 从 JSON 反序列化。 /// @@ -968,7 +1009,7 @@ class Project { final List pz = (p['phaseZones'] as List?) ?? []; return Project( name: p['name'] as String? ?? '未命名', - schema: j['schema'] as String? ?? 'seqdiagram/1.2', + schema: j['schema'] as String? ?? 'edc/1.3', cycle: Cycle.fromJson((p['cycle'] as Map?) ?? {}), stations: st.map((dynamic e) => Station.fromJson(e as Map)).toList(), actions: ac.map((dynamic e) => Action.fromJson(e as Map)).toList(), @@ -984,6 +1025,8 @@ class Project { MapEntry(int.tryParse(k) ?? 0, (v as num?)?.toInt() ?? 1)), autoSaveEnabled: p['autoSaveEnabled'] as bool? ?? true, autoSaveMinutes: (p['autoSaveMinutes'] as num?)?.toInt() ?? 10, + arch: ArchDoc.fromJson( + (p['arch'] as Map?) ?? {}), ); } diff --git a/lib/modules/module_registry.dart b/lib/modules/module_registry.dart new file mode 100644 index 0000000..a91d7ca --- /dev/null +++ b/lib/modules/module_registry.dart @@ -0,0 +1,149 @@ +/// 设计模块注册表:模块元数据的唯一事实来源。 +/// +/// 首页「新建文档」网格、品牌菜单、窗口标题、文档后缀与导出能力 +/// 全部从这里读取;新增模块只需注册一条记录(未完成的模块 +/// [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/persistence/android_docs.dart b/lib/persistence/android_docs.dart index de303d3..1165df0 100644 --- a/lib/persistence/android_docs.dart +++ b/lib/persistence/android_docs.dart @@ -6,6 +6,8 @@ /// /// 保存位置可配置:基础目录(Documents / Download / Pictures)+ 子文件夹名, /// 设置保存在应用私有目录的 `save_location.json`,跨会话生效。 +/// 默认目录为 `Documents/EDC`;旧目录 `Documents/SequenceDiagram` 在 +/// 打开对话框中一并列出(兼容读取,新文件一律写入 EDC)。 /// /// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。 library; @@ -30,6 +32,12 @@ class AndroidDocs { /// 可选的基础目录:文档 / 下载 / 图片。 static const List baseOptions = ['documents', 'downloads', 'pictures']; + /// 默认子文件夹名(品牌 EDC)。 + static const String defaultFolder = 'EDC'; + + /// 旧版子文件夹名(兼容读取;新文件一律写入 [defaultFolder])。 + static const String legacyFolder = 'SequenceDiagram'; + /// 基础目录的展示名。 static String baseLabel(String base) => switch (base) { 'downloads' => 'Download', @@ -52,12 +60,12 @@ class AndroidDocs { final Map j = jsonDecode(_settingsFile.readAsStringSync()) as Map; _settings = { 'base': j['base'] as String? ?? 'documents', - 'folder': j['folder'] as String? ?? 'SequenceDiagram', + 'folder': j['folder'] as String? ?? defaultFolder, }; } } catch (_) {} if (_settings.isEmpty) { - _settings = {'base': 'documents', 'folder': 'SequenceDiagram'}; + _settings = {'base': 'documents', 'folder': defaultFolder}; } return _settings; } @@ -66,7 +74,7 @@ class AndroidDocs { static Future saveSettings(String base, String folder) async { _settings = { 'base': baseOptions.contains(base) ? base : 'documents', - 'folder': folder.trim().isEmpty ? 'SequenceDiagram' : folder.trim(), + 'folder': folder.trim().isEmpty ? defaultFolder : folder.trim(), }; try { await _settingsFile.parent.create(recursive: true); @@ -74,10 +82,31 @@ class AndroidDocs { } catch (_) {} } - /// 当前保存位置的展示描述(如 `Documents/SequenceDiagram`)。 + /// 当前保存位置的展示描述(如 `Documents/EDC`)。 static String location() { final Map s = settings(); - return '${baseLabel(s['base'] ?? 'documents')}/${s['folder'] ?? 'SequenceDiagram'}'; + return '${baseLabel(s['base'] ?? 'documents')}/${s['folder'] ?? defaultFolder}'; + } + + /// 是否需要兼容旧目录(在默认位置下自动列出 Documents/SequenceDiagram)。 + static bool _useLegacy() { + final Map s = settings(); + return (s['base'] ?? 'documents') == 'documents' && + (s['folder'] ?? defaultFolder) == defaultFolder; + } + + /// 列出指定基础目录 + 文件夹下的文件。 + static Future>> _listOne( + String base, String folder) async { + final Object? r = + await _channel.invokeMethod('listFiles', { + 'base': base, + 'folder': folder, + }); + final List list = (r as List?) ?? const []; + return list + .map((Object? e) => Map.from(e as Map)) + .toList(); } /// 保存文件到配置的公共目录,返回展示位置。 @@ -94,19 +123,33 @@ class AndroidDocs { } /// 列出配置目录下的文件(`[{name, size}]`,新在前)。 + /// + /// 默认位置额外合并旧目录(Documents/SequenceDiagram)中的文件, + /// 同名以新目录为准(兼容旧版本保存的文档)。 static Future>> listFiles() async { final Map s = settings(); - final Object? r = await _channel.invokeMethod('listFiles', { - 'base': s['base'], - 'folder': s['folder'], - }); - final List list = (r as List?) ?? const []; - return list - .map((Object? e) => Map.from(e as Map)) - .toList(); + final List> primary = + await _listOne(s['base'] ?? 'documents', s['folder'] ?? defaultFolder); + if (!_useLegacy()) return primary; + final List> legacy = + await _listOne('documents', legacyFolder); + final Set names = { + for (final Map f in primary) (f['name'] as String?) ?? '', + }; + final List> out = >[...primary]; + for (final Map f in legacy) { + final String n = (f['name'] as String?) ?? ''; + if (n.isNotEmpty && !names.contains(n)) { + out.add(f); + names.add(n); + } + } + return out; } /// 读取配置目录下的文件内容;不存在返回 null。 + /// + /// 默认位置下依次尝试新目录与旧目录(兼容读取)。 static Future readFile(String name) async { final Map s = settings(); final Object? r = await _channel.invokeMethod('readFile', { @@ -114,8 +157,15 @@ class AndroidDocs { 'base': s['base'], 'folder': s['folder'], }); - if (r == null) return null; - return r as Uint8List; + if (r != null) return r as Uint8List; + if (!_useLegacy()) return null; + final Object? legacy = + await _channel.invokeMethod('readFile', { + 'name': name, + 'base': 'documents', + 'folder': legacyFolder, + }); + return legacy as Uint8List?; } /// 用系统浏览器打开网址(官网入口;安卓经原生 Intent)。 diff --git a/lib/persistence/app_paths.dart b/lib/persistence/app_paths.dart new file mode 100644 index 0000000..43799ed --- /dev/null +++ b/lib/persistence/app_paths.dart @@ -0,0 +1,59 @@ +/// 应用数据路径统一入口:运行时目录(由 [Storage] 管理)与素材库目录。 +/// +/// 素材库布局(桌面 `%APPDATA%/EDC/library/`;安卓为应用内部目录下的 +/// `library/`,公共目录导出见 [AndroidDocs]): +/// - `symbols/` 自定义图元(`*.symbol.json`,电气符号 / 架构图形等); +/// - `images/` 导入的图片素材; +/// - `templates/` 文档模板; +/// +/// 内置素材(随安装包发布、只读)走 Flutter assets,不占用这些目录; +/// 用户新增 / 导入的素材一律进这里。 +library; + +import 'dart:io'; + +import 'storage.dart'; + +/// 应用路径工具。 +class AppPaths { + AppPaths._(); + + /// 应用数据根目录(桌面 `%APPDATA%/EDC`;需先 [Storage.init])。 + static Future dataRoot() async { + await Storage.instance.init(); + return Storage.instance.appDir; + } + + /// 素材库根目录。 + static Future libraryDir() async { + final Directory root = await dataRoot(); + return Directory('${root.path}${Platform.pathSeparator}library'); + } + + /// 自定义图元目录(`library/symbols`)。 + static Future symbolsDir() async { + final Directory lib = await libraryDir(); + return Directory('${lib.path}${Platform.pathSeparator}symbols'); + } + + /// 图片素材目录(`library/images`)。 + static Future imagesDir() async { + final Directory lib = await libraryDir(); + return Directory('${lib.path}${Platform.pathSeparator}images'); + } + + /// 文档模板目录(`library/templates`)。 + static Future templatesDir() async { + final Directory lib = await libraryDir(); + return Directory('${lib.path}${Platform.pathSeparator}templates'); + } + + /// 确保素材库目录存在(幂等;失败静默,不阻塞启动)。 + static Future ensureLibrary() async { + try { + await (await symbolsDir()).create(recursive: true); + await (await imagesDir()).create(recursive: true); + await (await templatesDir()).create(recursive: true); + } catch (_) {} + } +} diff --git a/lib/persistence/recent_store.dart b/lib/persistence/recent_store.dart new file mode 100644 index 0000000..bb7f862 --- /dev/null +++ b/lib/persistence/recent_store.dart @@ -0,0 +1,146 @@ +/// 最近打开的文档记录(最多 [RecentStore.maxEntries] 条,按时间倒序)。 +/// +/// 存储位置:应用数据目录(桌面 `%APPDATA%/EDC/recent.json`, +/// 安卓为应用内部目录;与自动快照同根)。路径书写只读展示,不保证文件仍存在, +/// 失效条目在打开失败时自动移除。 +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'storage.dart'; + +/// 最近打开条目。 +class RecentDoc { + /// 构造。 + const RecentDoc({ + required this.path, + required this.moduleId, + required this.name, + required this.atMs, + }); + + /// 文件路径。 + final String path; + + /// 模块 id(sequence / architecture / …)。 + final String moduleId; + + /// 展示名(一般取文件名)。 + final String name; + + /// 打开时间(毫秒时间戳)。 + final int atMs; + + /// 打开时间。 + DateTime get at => DateTime.fromMillisecondsSinceEpoch(atMs); + + /// 序列化。 + Map toJson() => { + 'path': path, + 'moduleId': moduleId, + 'name': name, + 'at': atMs, + }; + + /// 反序列化(无效返回 null)。 + static RecentDoc? fromJson(dynamic raw) { + if (raw is! Map) return null; + final String path = raw['path'] as String? ?? ''; + final String moduleId = raw['moduleId'] as String? ?? ''; + if (path.isEmpty || moduleId.isEmpty) return null; + return RecentDoc( + path: path, + moduleId: moduleId, + name: raw['name'] as String? ?? path.split(RegExp(r'[\\/]')).last, + atMs: (raw['at'] as num?)?.toInt() ?? 0, + ); + } +} + +/// 最近打开存储(静态工具类)。 +class RecentStore { + RecentStore._(); + + /// 最多保留条数。 + static const int maxEntries = 15; + + static File _file(String appDir) => + File('$appDir${Platform.pathSeparator}recent.json'); + + /// 读取列表(文件缺失 / 解析失败返回空列表,不抛异常)。 + static Future> load() async { + try { + await Storage.instance.init(); + final File f = _file(Storage.instance.appDir.path); + if (!await f.exists()) return []; + final dynamic raw = jsonDecode(await f.readAsString()); + if (raw is! List) return []; + final List out = []; + for (final dynamic e in raw) { + final RecentDoc? r = RecentDoc.fromJson(e); + if (r != null) out.add(r); + } + out.sort((RecentDoc a, RecentDoc b) => b.atMs.compareTo(a.atMs)); + return out; + } catch (_) { + return []; + } + } + + /// 记录一次打开 / 保存(去重后置顶,超限裁剪)。 + static Future remember({ + required String path, + required String moduleId, + String? name, + }) async { + if (path.isEmpty || moduleId.isEmpty) return; + final List cur = await load(); + cur.removeWhere((RecentDoc r) => r.path == path); + cur.insert( + 0, + RecentDoc( + path: path, + moduleId: moduleId, + name: (name == null || name.isEmpty) + ? path.split(RegExp(r'[\\/]')).last + : name, + atMs: DateTime.now().millisecondsSinceEpoch, + ), + ); + while (cur.length > maxEntries) { + cur.removeLast(); + } + await _save(cur); + } + + /// 移除一条(打开失败时清理失效条目)。 + static Future remove(String path) async { + final List cur = await load(); + cur.removeWhere((RecentDoc r) => r.path == path); + await _save(cur); + } + + /// 清空全部记录。 + static Future clear() async { + await _save([]); + } + + static Future _save(List list) async { + try { + await Storage.instance.init(); + final File f = _file(Storage.instance.appDir.path); + if (!await f.parent.exists()) { + await f.parent.create(recursive: true); + } + await f.writeAsString( + jsonEncode(>[ + for (final RecentDoc r in list) r.toJson(), + ]), + flush: true, + ); + } catch (_) { + // 最近列表写入失败不影响主流程。 + } + } +} diff --git a/lib/persistence/storage.dart b/lib/persistence/storage.dart index 37ae2ef..f121f72 100644 --- a/lib/persistence/storage.dart +++ b/lib/persistence/storage.dart @@ -1,8 +1,11 @@ /// 持久化层:负责项目文件的读写、自动保存与崩溃恢复。 /// -/// 存储布局(位于用户 AppData/LocalAppData 下的 `SequenceDiagramStudio`): +/// 存储布局(位于用户 AppData/LocalAppData 下的 `EDC`;旧目录 +/// `SequenceDiagramStudio` 首次启动时自动复制迁移,不改写旧目录): /// - `autosave/current.seq.json`:最近一次项目快照; /// - `autosave/session.json`:会话元数据(来源路径、是否干净、更新时间); +/// - `recent.json`:最近打开列表(见 `recent_store.dart`); +/// - `library/`:用户素材库(符号 / 图片 / 模板,见 `app_paths.dart`); /// - `<项目路径>.bak`:保存前自动生成的备份。 /// /// 与上层关系:AppController 通过单例 [Storage.instance] 调用自动保存与保存; @@ -73,13 +76,29 @@ class Storage { /// 目录优先级:`APPDATA` > `LOCALAPPDATA` > 系统临时目录;随后创建 /// `autosave` 子目录。副作用:设置 [appDir]/[autosaveDir]/[currentFile]/ /// [sessionFile] 并置 [_inited]。 + /// + /// 迁移:品牌更名(EDC)后首次启动,若旧目录 `SequenceDiagramStudio` + /// 存在且新目录尚无自动快照,则**复制**旧内容(不改写旧目录)。 Future init() async { if (_inited) return; final String base = Platform.environment['APPDATA'] ?? Platform.environment['LOCALAPPDATA'] ?? Directory.systemTemp.path; - appDir = Directory('$base${Platform.pathSeparator}SequenceDiagramStudio'); + final Directory legacy = + Directory('$base${Platform.pathSeparator}SequenceDiagramStudio'); + appDir = Directory('$base${Platform.pathSeparator}EDC'); autosaveDir = Directory('${appDir.path}${Platform.pathSeparator}autosave'); + // 一次性迁移(失败不阻塞启动)。 + try { + final Directory newAuto = autosaveDir; + final Directory oldAuto = + Directory('${legacy.path}${Platform.pathSeparator}autosave'); + if (await legacy.exists() && + !await newAuto.exists() && + await oldAuto.exists()) { + await _copyDir(oldAuto, newAuto); + } + } catch (_) {} currentFile = File('${autosaveDir.path}${Platform.pathSeparator}current.seq.json'); sessionFile = File('${autosaveDir.path}${Platform.pathSeparator}session.json'); if (!await autosaveDir.exists()) { @@ -88,6 +107,23 @@ class Storage { _inited = true; } + /// 递归复制目录(迁移用;已存在的目标文件会被覆盖)。 + static Future _copyDir(Directory from, Directory to) async { + await to.create(recursive: true); + await for (final FileSystemEntity e + in from.list(recursive: true, followLinks: false)) { + final String rel = e.path.substring(from.path.length); + final String dest = '${to.path}$rel'; + if (e is File) { + final File f = File(dest); + await f.parent.create(recursive: true); + await e.copy(dest); + } else if (e is Directory) { + await Directory(dest).create(recursive: true); + } + } + } + /// 写入自动保存快照与会话元数据。 /// /// 参数 [project]:项目;[projectPath]:来源文件路径;[clean]:是否已正常 @@ -208,9 +244,13 @@ class Storage { /// 将项目保存到 [path]。 /// + /// [includeArch] 为 false 时写出**不含架构图部分**的时序图文档 + /// (`*.seq.json`);架构图单独保存为 `*.arch.json`。 + /// /// 流程:初始化 -> 备份已有文件 -> 确保父目录存在 -> 写入项目 JSON -> /// 同步写自动保存(标记为干净)。返回保存路径。 - Future saveProject(String path, Project project) async { + Future saveProject(String path, Project project, + {bool includeArch = false}) async { await init(); // 1) 覆盖前先备份,防止写坏原文件。 await backupExisting(path); @@ -221,7 +261,7 @@ class Storage { await parent.create(recursive: true); } // 3) 写入项目并 flush;随后把自动保存标记为干净。 - await target.writeAsString(project.encode(), flush: true); + await target.writeAsString(project.encode(includeArch: includeArch), flush: true); await writeAutosave(project, projectPath: path, clean: true); return path; } diff --git a/lib/sketch/sketch_models.dart b/lib/sketch/sketch_models.dart new file mode 100644 index 0000000..adb0237 --- /dev/null +++ b/lib/sketch/sketch_models.dart @@ -0,0 +1,1236 @@ +/// 参数化草图数据模型:点(自由度载体)、几何(直线 / 圆 / 弧)、 +/// 几何约束与驱动尺寸;配合 `sketch_solver.dart` 的求解器实现参数化。 +/// +/// 设计要点: +/// - 点是共享的:端点重合通过「引用同一个点」表达(天然重合,无需约束); +/// - 尺寸是驱动量(driving dimension):改数值即驱动几何重新求解; +/// - 全部可 JSON 往返,随架构图文档(`*.arch.json`)保存; +/// - 命名沿用 CAD 习惯:P 点 / E 实体 / K 约束 / D 尺寸。 +library; + +import 'dart:convert'; +import 'dart:math' as math; +import 'dart:ui' show Offset, Rect; + +// ===================== 基础模型 ===================== + +/// 草图点(求解变量 x / y;[fixed] 的点是锚点,不参与求解)。 +class SketchPoint { + /// 构造点。 + const SketchPoint({ + required this.id, + required this.x, + required this.y, + this.fixed = false, + }); + + /// 点 id(P 开头)。 + final String id; + + /// 世界坐标 x。 + final double x; + + /// 世界坐标 y。 + final double y; + + /// 是否固定(锚点)。 + final bool fixed; + + /// 位置。 + Offset get pos => Offset(x, y); + + /// 复制并覆盖字段。 + SketchPoint copyWith({double? x, double? y, bool? fixed}) => SketchPoint( + id: id, + x: x ?? this.x, + y: y ?? this.y, + fixed: fixed ?? this.fixed, + ); + + /// 序列化。 + Map toJson() => + {'id': id, 'x': x, 'y': y, 'fixed': fixed}; + + /// 反序列化。 + static SketchPoint fromJson(Map j) => SketchPoint( + id: j['id'] as String? ?? '', + x: (j['x'] as num?)?.toDouble() ?? 0, + y: (j['y'] as num?)?.toDouble() ?? 0, + fixed: j['fixed'] as bool? ?? false, + ); +} + +/// 草图几何类型。 +enum SketchKind { + /// 直线(p1 → p2)。 + line, + + /// 圆(圆心 p1、半径 r)。 + circle, + + /// 圆弧(圆心 p1、起点 p2、终点 p3、半径 r、[SketchEntity.ccw] 逆时针)。 + arc, +} + +/// 几何类型 ↔ JSON 字符串。 +String sketchKindName(SketchKind k) => switch (k) { + SketchKind.line => 'line', + SketchKind.circle => 'circle', + SketchKind.arc => 'arc', + }; + +/// JSON 字符串 → 几何类型。 +SketchKind sketchKindFrom(String s) => switch (s) { + 'circle' => SketchKind.circle, + 'arc' => SketchKind.arc, + _ => SketchKind.line, + }; + +/// 草图几何实体(全部坐标通过点 id 引用,共享点即共享位置)。 +class SketchEntity { + /// 构造实体。 + const SketchEntity({ + required this.id, + required this.kind, + this.p1 = '', + this.p2 = '', + this.p3 = '', + this.r = 0, + this.ccw = true, + }); + + /// 实体 id(E 开头)。 + final String id; + + /// 类型。 + final SketchKind kind; + + /// 直线起点 / 圆心 / 圆弧圆心。 + final String p1; + + /// 直线终点 / 圆弧起点。 + final String p2; + + /// 圆弧终点。 + final String p3; + + /// 半径(circle / arc)。 + final double r; + + /// 圆弧方向:true 逆时针。 + final bool ccw; + + /// 复制并覆盖字段。 + SketchEntity copyWith({ + String? p1, + String? p2, + String? p3, + double? r, + bool? ccw, + }) => + SketchEntity( + id: id, + kind: kind, + p1: p1 ?? this.p1, + p2: p2 ?? this.p2, + p3: p3 ?? this.p3, + r: r ?? this.r, + ccw: ccw ?? this.ccw, + ); + + /// 序列化。 + Map toJson() => { + 'id': id, + 'kind': sketchKindName(kind), + 'p1': p1, + 'p2': p2, + 'p3': p3, + 'r': r, + 'ccw': ccw, + }; + + /// 反序列化。 + static SketchEntity fromJson(Map j) => SketchEntity( + id: j['id'] as String? ?? '', + kind: sketchKindFrom(j['kind'] as String? ?? 'line'), + p1: j['p1'] as String? ?? '', + p2: j['p2'] as String? ?? '', + p3: j['p3'] as String? ?? '', + r: (j['r'] as num?)?.toDouble() ?? 0, + ccw: j['ccw'] as bool? ?? true, + ); +} + +/// 几何约束类型。 +enum SketchConsType { + /// 水平(一条直线)。 + horizontal, + + /// 竖直(一条直线)。 + vertical, + + /// 平行(两条直线)。 + parallel, + + /// 垂直(两条直线)。 + perpendicular, + + /// 相等(两条线等长 / 两个圆等半径)。 + equal, + + /// 同心(两个圆 / 弧)。 + concentric, + + /// 相切(线与圆,或两个圆)。 + tangent, + + /// 点在实体上(一个点 + 一条线 / 圆 / 弧)。 + pointOnEntity, +} + +/// 约束中文名(界面展示)。 +String sketchConsLabel(SketchConsType t) => switch (t) { + SketchConsType.horizontal => '水平', + SketchConsType.vertical => '竖直', + SketchConsType.parallel => '平行', + SketchConsType.perpendicular => '垂直', + SketchConsType.equal => '相等', + SketchConsType.concentric => '同心', + SketchConsType.tangent => '相切', + SketchConsType.pointOnEntity => '点在线上', + }; + +/// 约束 JSON 名称。 +String sketchConsName(SketchConsType t) => switch (t) { + SketchConsType.horizontal => 'horizontal', + SketchConsType.vertical => 'vertical', + SketchConsType.parallel => 'parallel', + SketchConsType.perpendicular => 'perpendicular', + SketchConsType.equal => 'equal', + SketchConsType.concentric => 'concentric', + SketchConsType.tangent => 'tangent', + SketchConsType.pointOnEntity => 'pointOnEntity', + }; + +/// 约束 JSON 名称 → 类型。 +SketchConsType sketchConsFrom(String s) => switch (s) { + 'horizontal' => SketchConsType.horizontal, + 'vertical' => SketchConsType.vertical, + 'parallel' => SketchConsType.parallel, + 'perpendicular' => SketchConsType.perpendicular, + 'equal' => SketchConsType.equal, + 'concentric' => SketchConsType.concentric, + 'tangent' => SketchConsType.tangent, + _ => SketchConsType.pointOnEntity, + }; + +/// 几何约束。 +/// +/// [a] / [b] 的含义随类型变化: +/// - horizontal / vertical:a = 直线; +/// - parallel / perpendicular / equal / concentric / tangent:a、b = 两实体; +/// - pointOnEntity:a = 点 id,b = 实体 id。 +class SketchConstraint { + /// 构造约束。 + const SketchConstraint({ + required this.id, + required this.type, + this.a = '', + this.b = '', + this.internal = false, + }); + + /// 约束 id(K 开头)。 + final String id; + + /// 类型。 + final SketchConsType type; + + /// 主引用。 + final String a; + + /// 次引用。 + final String b; + + /// 内部约束(如圆弧端点约束):不显示图标、用户不可删除。 + final bool internal; + + /// 序列化。 + Map toJson() => { + 'id': id, + 'type': sketchConsName(type), + 'a': a, + 'b': b, + 'internal': internal, + }; + + /// 反序列化。 + static SketchConstraint fromJson(Map j) => SketchConstraint( + id: j['id'] as String? ?? '', + type: sketchConsFrom(j['type'] as String? ?? 'pointOnEntity'), + a: j['a'] as String? ?? '', + b: j['b'] as String? ?? '', + internal: j['internal'] as bool? ?? false, + ); +} + +/// 驱动尺寸类型。 +enum SketchDimType { + /// 长度(一条直线)。 + length, + + /// 半径(圆 / 弧)。 + radius, + + /// 角度(两条直线,单位度)。 + angle, + + /// 距离(两个点)。 + distance, +} + +/// 尺寸中文名。 +String sketchDimLabel(SketchDimType t) => switch (t) { + SketchDimType.length => '长度', + SketchDimType.radius => '半径', + SketchDimType.angle => '角度', + SketchDimType.distance => '距离', + }; + +/// 尺寸 JSON 名称。 +String sketchDimName(SketchDimType t) => switch (t) { + SketchDimType.length => 'length', + SketchDimType.radius => 'radius', + SketchDimType.angle => 'angle', + SketchDimType.distance => 'distance', + }; + +/// 尺寸 JSON 名称 → 类型。 +SketchDimType sketchDimFrom(String s) => switch (s) { + 'radius' => SketchDimType.radius, + 'angle' => SketchDimType.angle, + 'distance' => SketchDimType.distance, + _ => SketchDimType.length, + }; + +/// 驱动尺寸(a / b 为引用的实体或点 id)。 +class SketchDim { + /// 构造尺寸。 + const SketchDim({ + required this.id, + required this.type, + required this.value, + this.a = '', + this.b = '', + }); + + /// 尺寸 id(D 开头)。 + final String id; + + /// 类型。 + final SketchDimType type; + + /// 驱动值(长度 / 半径为世界像素;角度为度)。 + final double value; + + /// 主引用(长度 = 直线 id;半径 = 圆 / 弧 id;角度 = 两条线;距离 = 两个点)。 + final String a; + + /// 次引用。 + final String b; + + /// 复制并覆盖字段。 + SketchDim copyWith({double? value, String? a, String? b}) => SketchDim( + id: id, + type: type, + value: value ?? this.value, + a: a ?? this.a, + b: b ?? this.b, + ); + + /// 序列化。 + Map toJson() => { + 'id': id, + 'type': sketchDimName(type), + 'value': value, + 'a': a, + 'b': b, + }; + + /// 反序列化。 + static SketchDim fromJson(Map j) => SketchDim( + id: j['id'] as String? ?? '', + type: sketchDimFrom(j['type'] as String? ?? 'length'), + value: (j['value'] as num?)?.toDouble() ?? 0, + a: j['a'] as String? ?? '', + b: j['b'] as String? ?? '', + ); +} + +/// 草图工具。 +enum SketchTool { + /// 选择 / 拖动(拖动触发约束求解)。 + select, + + /// 直线(点两下落线;近轴自动水平 / 竖直)。 + line, + + /// 圆(圆心 + 半径点)。 + circle, + + /// 圆弧(圆心 → 起点 → 终点)。 + arc, + + /// 矩形(对角两点;自动水平 / 竖直 + 共享角点)。 + rect, + + /// 修剪(点击线段删除该段)。 + trim, +} + +/// 工具中文名(状态栏用)。 +String sketchToolLabel(SketchTool t) => switch (t) { + SketchTool.select => '选择', + SketchTool.line => '直线', + SketchTool.circle => '圆', + SketchTool.arc => '圆弧', + SketchTool.rect => '矩形', + SketchTool.trim => '修剪', + }; + +// ===================== 文档 ===================== + +/// 参数化草图文档。 +class SketchDoc { + /// 构造文档。 + const SketchDoc({ + this.points = const [], + this.entities = const [], + this.constraints = const [], + this.dims = const [], + }); + + /// 空草图。 + static const SketchDoc empty = SketchDoc(); + + /// 点列表(自由度载体)。 + final List points; + + /// 几何实体列表。 + final List entities; + + /// 约束列表。 + final List constraints; + + /// 驱动尺寸列表。 + final List dims; + + /// 是否为空。 + bool get isEmpty => + points.isEmpty && + entities.isEmpty && + constraints.isEmpty && + dims.isEmpty; + + /// 按 id 查找点。 + SketchPoint? pointById(String? id) { + if (id == null) return null; + for (final SketchPoint p in points) { + if (p.id == id) return p; + } + return null; + } + + /// 按 id 查找实体。 + SketchEntity? entityById(String? id) { + if (id == null) return null; + for (final SketchEntity e in entities) { + if (e.id == id) return e; + } + return null; + } + + /// 按 id 查找尺寸。 + SketchDim? dimById(String? id) { + if (id == null) return null; + for (final SketchDim d in dims) { + if (d.id == id) return d; + } + return null; + } + + /// 实体引用的点 id 列表。 + List entityPointIds(SketchEntity e) => switch (e.kind) { + SketchKind.line => [e.p1, e.p2], + SketchKind.circle => [e.p1], + SketchKind.arc => [e.p1, e.p2, e.p3], + }.where((String s) => s.isNotEmpty).toList(); + + /// 全部已用 id。 + Iterable get allIds => [ + for (final SketchPoint p in points) p.id, + for (final SketchEntity e in entities) e.id, + for (final SketchConstraint k in constraints) k.id, + for (final SketchDim d in dims) d.id, + ]; + + /// 复制并覆盖字段。 + SketchDoc copyWith({ + List? points, + List? entities, + List? constraints, + List? dims, + }) => + SketchDoc( + points: points ?? this.points, + entities: entities ?? this.entities, + constraints: constraints ?? this.constraints, + dims: dims ?? this.dims, + ); + + /// 替换 / 追加点。 + SketchDoc upsertPoint(SketchPoint p) { + bool found = false; + final List next = [ + for (final SketchPoint x in points) + if (x.id == p.id) (found = true) ? p : x else x, + ]; + if (!found) next.add(p); + return copyWith(points: next); + } + + /// 替换 / 追加实体。 + SketchDoc upsertEntity(SketchEntity e) { + bool found = false; + final List next = [ + for (final SketchEntity x in entities) + if (x.id == e.id) (found = true) ? e : x else x, + ]; + if (!found) next.add(e); + return copyWith(entities: next); + } + + /// 删除实体:连带清理仅被它引用的点、引用它的约束与尺寸。 + SketchDoc removeEntities(Set ids) { + final List next = + entities.where((SketchEntity e) => !ids.contains(e.id)).toList(); + final Set used = { + for (final SketchEntity e in next) ...entityPointIds(e), + }; + final List nextCons = constraints + .where((SketchConstraint k) => + !(ids.contains(k.a) || ids.contains(k.b))) + .toList(); + final List nextDims = dims + .where((SketchDim d) => !(ids.contains(d.a) || ids.contains(d.b))) + .toList(); + return copyWith( + entities: next, + constraints: nextCons, + dims: nextDims, + points: points + .where((SketchPoint p) => + used.contains(p.id) || !_pointOnlyUsedBy(p.id, ids)) + .toList(), + ); + } + + /// 某个点是否只被 [gone] 中的实体引用。 + bool _pointOnlyUsedBy(String pointId, Set gone) { + for (final SketchEntity e in entities) { + if (gone.contains(e.id)) continue; + if (entityPointIds(e).contains(pointId)) return false; + } + return true; + } + + /// 删除指定对象(点 / 实体 / 约束 / 尺寸 id 混选)。 + SketchDoc removeAny(Set ids) { + final Set entIds = { + for (final SketchEntity e in entities) + if (ids.contains(e.id)) e.id, + }; + Set pointIds = { + for (final SketchPoint p in points) + if (ids.contains(p.id)) p.id, + }; + // 删除点 → 连带删除引用它的实体。 + for (final SketchEntity e in entities) { + if (entityPointIds(e).any(pointIds.contains)) entIds.add(e.id); + } + SketchDoc next = entIds.isEmpty ? this : removeEntities(entIds); + pointIds = pointIds + .where((String id) => next.pointById(id) != null) + .toSet(); + return next.copyWith( + points: next.points + .where((SketchPoint p) => !pointIds.contains(p.id)) + .toList(), + constraints: next.constraints + .where((SketchConstraint k) => !ids.contains(k.id)) + .toList(), + dims: next.dims.where((SketchDim d) => !ids.contains(d.id)).toList(), + ); + } + + /// 内容外接矩形(适配视图用;空草图返回 null)。 + Rect? contentBounds() { + double? l, t, r, b; + void inc(Offset p) { + l = (l == null || p.dx < l!) ? p.dx : l; + t = (t == null || p.dy < t!) ? p.dy : t; + r = (r == null || p.dx > r!) ? p.dx : r; + b = (b == null || p.dy > b!) ? p.dy : b; + } + + for (final SketchPoint p in points) { + inc(p.pos); + } + if (l == null || t == null || r == null || b == null) return null; + for (final SketchEntity e in entities) { + if (e.kind == SketchKind.circle || e.kind == SketchKind.arc) { + final SketchPoint? c = pointById(e.p1); + if (c != null) { + inc(c.pos + Offset(-e.r, -e.r)); + inc(c.pos + Offset(e.r, e.r)); + } + } + } + return Rect.fromLTRB(l!, t!, r!, b!); + } + + /// 序列化。 + Map toJson() => { + 'points': >[ + for (final SketchPoint p in points) p.toJson(), + ], + 'entities': >[ + for (final SketchEntity e in entities) e.toJson(), + ], + 'constraints': >[ + for (final SketchConstraint k in constraints) k.toJson(), + ], + 'dims': >[ + for (final SketchDim d in dims) d.toJson(), + ], + }; + + /// 序列化为带缩进的 JSON 文本。 + String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); + + /// 从文本解码。 + static SketchDoc decode(String source) => + SketchDoc.fromJson(jsonDecode(source) as Map); + + /// 反序列化(缺失字段安全默认)。 + static SketchDoc fromJson(Map j) => SketchDoc( + points: ((j['points'] as List?) ?? []) + .map((dynamic e) => SketchPoint.fromJson(e as Map)) + .toList(), + entities: ((j['entities'] as List?) ?? []) + .map((dynamic e) => SketchEntity.fromJson(e as Map)) + .toList(), + constraints: ((j['constraints'] as List?) ?? []) + .map((dynamic e) => + SketchConstraint.fromJson(e as Map)) + .toList(), + dims: ((j['dims'] as List?) ?? []) + .map((dynamic e) => SketchDim.fromJson(e as Map)) + .toList(), + ); +} + +/// 生成不冲突的新 id(P / E / K / D 前缀 + 数字,从 1 递增)。 +String sketchNewId(String prefix, Iterable existing) { + final Set used = existing.toSet(); + int n = 1; + while (used.contains('$prefix$n')) { + n++; + } + return '$prefix$n'; +} + +// ===================== 几何工具 ===================== + +/// 点到线段距离。 +double sketchDistToSegment(Offset p, Offset a, Offset b) { + final Offset ab = b - a; + final double len2 = ab.dx * ab.dx + ab.dy * ab.dy; + if (len2 < 1e-9) return (p - a).distance; + double t = ((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2; + t = t.clamp(0.0, 1.0); + return (p - (a + ab * t)).distance; +} + +/// 圆弧起止角(弧度;ccw 决定方向)。 +(double start, double sweep) sketchArcAngles( + Offset c, + Offset ps, + Offset pe, + bool ccw, +) { + final double a1 = math.atan2(ps.dy - c.dy, ps.dx - c.dx); + final double a2 = math.atan2(pe.dy - c.dy, pe.dx - c.dx); + double sweep = ccw ? (a2 - a1) : (a1 - a2); + while (sweep <= 0) { + sweep += math.pi * 2; + } + if (sweep > math.pi * 2) sweep = math.pi * 2; + return (a1, sweep); +} + +/// 角度是否落在圆弧范围内。 +bool sketchAngleInArc(Offset c, Offset p, Offset ps, Offset pe, bool ccw) { + final (double a1, double sweep) = sketchArcAngles(c, ps, pe, ccw); + double a = math.atan2(p.dy - c.dy, p.dx - c.dx); + double d = ccw ? (a - a1) : (a1 - a); + while (d < 0) { + d += math.pi * 2; + } + return d <= sweep + 1e-9; +} + +/// 实体到点的命中距离(轮廓)。 +double sketchEntityDistance(SketchDoc doc, SketchEntity e, Offset p) { + switch (e.kind) { + case SketchKind.line: + final Offset? a = doc.pointById(e.p1)?.pos; + final Offset? b = doc.pointById(e.p2)?.pos; + if (a == null || b == null) return double.infinity; + return sketchDistToSegment(p, a, b); + case SketchKind.circle: + final Offset? c = doc.pointById(e.p1)?.pos; + if (c == null) return double.infinity; + return ((p - c).distance - e.r).abs(); + case SketchKind.arc: + final Offset? c = doc.pointById(e.p1)?.pos; + final Offset? ps = doc.pointById(e.p2)?.pos; + final Offset? pe = doc.pointById(e.p3)?.pos; + if (c == null || ps == null || pe == null) return double.infinity; + if (!sketchAngleInArc(c, p, ps, pe, e.ccw)) { + // 不在弧范围内:按到两端点的最近距离算。 + return math.min((p - ps).distance, (p - pe).distance); + } + return ((p - c).distance - e.r).abs(); + } +} + +/// 命中测试结果。 +class SketchHit { + /// 构造。 + const SketchHit({this.pointId, this.entityId, this.dimId}); + + /// 命中的点 id。 + final String? pointId; + + /// 命中的实体 id。 + final String? entityId; + + /// 命中的尺寸 id。 + final String? dimId; +} + +/// 命中测试:点优先,其次尺寸标签附近,最后实体轮廓。 +SketchHit sketchHitTest( + SketchDoc doc, + Offset p, { + double pointTol = 8, + double entityTol = 6, + double dimTol = 12, +}) { + // 1) 点。 + String? bestPoint; + double bestD = pointTol; + for (final SketchPoint pt in doc.points) { + final double d = (pt.pos - p).distance; + if (d <= bestD) { + bestD = d; + bestPoint = pt.id; + } + } + if (bestPoint != null) return SketchHit(pointId: bestPoint); + // 2) 尺寸(标签锚点附近)。 + for (final SketchDim d in doc.dims) { + final Rect? r = sketchDimBounds(doc, d); + if (r != null && r.inflate(4).contains(p)) { + return SketchHit(dimId: d.id); + } + } + // 3) 实体。 + String? bestEntity; + double bestE = entityTol; + for (final SketchEntity e in doc.entities) { + final double d = sketchEntityDistance(doc, e, p); + if (d <= bestE) { + bestE = d; + bestEntity = e.id; + } + } + return SketchHit(entityId: bestEntity); +} + +// ===================== 尺寸测量与布局 ===================== + +/// 测量尺寸当前值(界面预填充与约束可用性判断用);无法测量返回 null。 +double? sketchMeasure(SketchDoc doc, SketchDimType type, String a, String b) { + switch (type) { + case SketchDimType.length: + final SketchEntity? e = doc.entityById(a); + if (e == null || e.kind != SketchKind.line) return null; + final Offset? p1 = doc.pointById(e.p1)?.pos; + final Offset? p2 = doc.pointById(e.p2)?.pos; + if (p1 == null || p2 == null) return null; + return (p2 - p1).distance; + case SketchDimType.radius: + final SketchEntity? e = doc.entityById(a); + if (e == null || e.kind == SketchKind.line) return null; + return e.r; + case SketchDimType.angle: + final SketchEntity? e1 = doc.entityById(a); + final SketchEntity? e2 = doc.entityById(b); + if (e1 == null || e2 == null || e1.kind != SketchKind.line || e2.kind != SketchKind.line) { + return null; + } + final Offset? a1 = doc.pointById(e1.p1)?.pos; + final Offset? a2 = doc.pointById(e1.p2)?.pos; + final Offset? b1 = doc.pointById(e2.p1)?.pos; + final Offset? b2 = doc.pointById(e2.p2)?.pos; + if (a1 == null || a2 == null || b1 == null || b2 == null) return null; + final Offset d1 = a2 - a1; + final Offset d2 = b2 - b1; + final double dot = d1.dx * d2.dx + d1.dy * d2.dy; + final double cross = d1.dx * d2.dy - d1.dy * d2.dx; + double ang = math.atan2(cross.abs(), dot) * 180 / math.pi; + if (ang > 90) ang = 180 - ang; // 取锐角,与 CAD 习惯一致 + return ang; + case SketchDimType.distance: + final Offset? p1 = doc.pointById(a)?.pos; + final Offset? p2 = doc.pointById(b)?.pos; + if (p1 == null || p2 == null) return null; + return (p2 - p1).distance; + } +} + +/// 尺寸标签锚点(绘制 / 命中用)。 +Offset? sketchDimAnchor(SketchDoc doc, SketchDim d) { + switch (d.type) { + case SketchDimType.length: + final SketchEntity? e = doc.entityById(d.a); + if (e == null) return null; + final Offset? p1 = doc.pointById(e.p1)?.pos; + final Offset? p2 = doc.pointById(e.p2)?.pos; + if (p1 == null || p2 == null) return null; + final Offset mid = Offset.lerp(p1, p2, 0.5)!; + final Offset dir = p2 - p1; + final double len = dir.distance; + if (len < 1e-6) return mid; + final Offset n = Offset(-dir.dy / len, dir.dx / len); + return mid + n * 22; + case SketchDimType.radius: + final SketchEntity? e = doc.entityById(d.a); + final Offset? c = doc.pointById(e?.p1)?.pos; + if (e == null || c == null) return null; + return c + Offset(e.r * 0.6, -e.r * 0.6); + case SketchDimType.angle: + final SketchEntity? e1 = doc.entityById(d.a); + final SketchEntity? e2 = doc.entityById(d.b); + if (e1 == null || e2 == null) return null; + final Offset? m1a = doc.pointById(e1.p1)?.pos; + final Offset? m1b = doc.pointById(e1.p2)?.pos; + final Offset? m2a = doc.pointById(e2.p1)?.pos; + final Offset? m2b = doc.pointById(e2.p2)?.pos; + if (m1a == null || m1b == null || m2a == null || m2b == null) { + return null; + } + return Offset.lerp(Offset.lerp(m1a, m1b, 0.5)!, Offset.lerp(m2a, m2b, 0.5)!, 0.5); + case SketchDimType.distance: + final Offset? p1 = doc.pointById(d.a)?.pos; + final Offset? p2 = doc.pointById(d.b)?.pos; + if (p1 == null || p2 == null) return null; + return Offset.lerp(p1, p2, 0.5)! + const Offset(0, -16); + } +} + +/// 尺寸标签外接矩形(命中 / 布局用)。 +Rect? sketchDimBounds(SketchDoc doc, SketchDim d) { + final Offset? a = sketchDimAnchor(doc, d); + if (a == null) return null; + final String text = sketchDimText(d); + final double w = text.length * 7.0 + 12; + return Rect.fromCenter(center: a, width: w, height: 18); +} + +/// 尺寸显示文本(如 `L120.0` / `R25.0` / `∠45.0°` / `⌀…`)。 +String sketchDimText(SketchDim d) => switch (d.type) { + SketchDimType.length => 'L${_fmt(d.value)}', + SketchDimType.radius => 'R${_fmt(d.value)}', + SketchDimType.angle => '∠${_fmt(d.value)}°', + SketchDimType.distance => 'D${_fmt(d.value)}', + }; + +String _fmt(double v) => + (v - v.roundToDouble()).abs() < 0.05 ? v.round().toString() : v.toStringAsFixed(1); + +// ===================== 捕捉与自动约束 ===================== + +/// 捕捉结果:位置 + 可选的吸附目标(点 → 重合;实体 → 点在实体上)。 +class SketchSnap { + /// 构造。 + const SketchSnap({required this.pos, this.pointId, this.entityId}); + + /// 吸附后的位置。 + final Offset pos; + + /// 命中的已有点(复用该点 = 天然重合)。 + final String? pointId; + + /// 命中的实体(生成 pointOnEntity 约束)。 + final String? entityId; +} + +/// 绘制捕捉:已有点 > 实体轮廓 > 网格。 +SketchSnap sketchSnap( + SketchDoc doc, + Offset pos, { + required bool gridSnap, + required double grid, + String? ignorePointId, + double pointTol = 10, + double entityTol = 8, +}) { + String? bestPoint; + double bestD = pointTol; + for (final SketchPoint p in doc.points) { + if (p.id == ignorePointId) continue; + final double d = (p.pos - pos).distance; + if (d <= bestD) { + bestD = d; + bestPoint = p.id; + } + } + if (bestPoint != null) { + return SketchSnap(pos: doc.pointById(bestPoint)!.pos, pointId: bestPoint); + } + String? bestEntity; + double bestE = entityTol; + for (final SketchEntity e in doc.entities) { + final double d = sketchEntityDistance(doc, e, pos); + if (d <= bestE) { + bestE = d; + bestEntity = e.id; + } + } + if (bestEntity != null) { + return SketchSnap(pos: pos, entityId: bestEntity); + } + if (gridSnap && grid > 0) { + return SketchSnap( + pos: Offset( + (pos.dx / grid).roundToDouble() * grid, + (pos.dy / grid).roundToDouble() * grid, + ), + ); + } + return SketchSnap(pos: pos); +} + +/// 新直线是否近轴(自动补水平 / 竖直约束);返回 null 表示无需约束。 +SketchConsType? sketchAutoAxis(Offset a, Offset b, {double tolDeg = 2.5}) { + final Offset d = b - a; + if (d.distance < 1e-6) return null; + final double ang = + math.atan2(d.dy.abs(), d.dx.abs()) * 180 / math.pi; // 0..90° + if (ang <= tolDeg) return SketchConsType.horizontal; + if (ang >= 90 - tolDeg) return SketchConsType.vertical; + return null; +} + +/// 选择是否可添加某类约束(面板按钮启用 / 提示用)。 +bool sketchCanConstrain( + SketchDoc doc, + SketchConsType type, + List selIds, +) { + final List es = [ + for (final String id in selIds) + if (doc.entityById(id) != null) doc.entityById(id)!, + ]; + final List ps = [ + for (final String id in selIds) + if (doc.pointById(id) != null) doc.pointById(id)!, + ]; + switch (type) { + case SketchConsType.horizontal: + case SketchConsType.vertical: + return es.length == 1 && es.first.kind == SketchKind.line; + case SketchConsType.parallel: + case SketchConsType.perpendicular: + return es.length == 2 && + es.every((SketchEntity e) => e.kind == SketchKind.line); + case SketchConsType.equal: + if (es.length != 2) return false; + final bool lines = + es.every((SketchEntity e) => e.kind == SketchKind.line); + final bool circles = + es.every((SketchEntity e) => e.kind != SketchKind.line); + return lines || circles; + case SketchConsType.concentric: + return es.length == 2 && + es.every((SketchEntity e) => e.kind != SketchKind.line); + case SketchConsType.tangent: + if (es.length != 2) return false; + final int nLines = + es.where((SketchEntity e) => e.kind == SketchKind.line).length; + return nLines <= 1; + case SketchConsType.pointOnEntity: + return ps.length == 1 && es.length == 1; + } +} + +/// 选择是否可添加某类尺寸。 +bool sketchCanDim(SketchDoc doc, SketchDimType type, List selIds) { + final List es = [ + for (final String id in selIds) + if (doc.entityById(id) != null) doc.entityById(id)!, + ]; + final List ps = [ + for (final String id in selIds) + if (doc.pointById(id) != null) doc.pointById(id)!, + ]; + switch (type) { + case SketchDimType.length: + return es.length == 1 && es.first.kind == SketchKind.line; + case SketchDimType.radius: + return es.length == 1 && es.first.kind != SketchKind.line; + case SketchDimType.angle: + return es.length == 2 && + es.every((SketchEntity e) => e.kind == SketchKind.line); + case SketchDimType.distance: + return ps.length == 2; + } +} + +/// 从选择解析尺寸引用(与 [sketchCanDim] 配合);无法解析返回 null。 +(String, String)? sketchDimRefs( + SketchDoc doc, + SketchDimType type, + List selIds, +) { + final List es = [ + for (final String id in selIds) + if (doc.entityById(id) != null) doc.entityById(id)!, + ]; + final List ps = [ + for (final String id in selIds) + if (doc.pointById(id) != null) doc.pointById(id)!, + ]; + switch (type) { + case SketchDimType.length: + case SketchDimType.radius: + if (es.length != 1) return null; + return (es.first.id, ''); + case SketchDimType.angle: + if (es.length != 2) return null; + return (es[0].id, es[1].id); + case SketchDimType.distance: + if (ps.length != 2) return null; + return (ps[0].id, ps[1].id); + } +} + +/// 从选择解析约束引用(与 [sketchCanConstrain] 配合);无法解析返回 null。 +(String, String)? sketchConsRefs( + SketchDoc doc, + SketchConsType type, + List selIds, +) { + final List es = [ + for (final String id in selIds) + if (doc.entityById(id) != null) doc.entityById(id)!, + ]; + final List ps = [ + for (final String id in selIds) + if (doc.pointById(id) != null) doc.pointById(id)!, + ]; + switch (type) { + case SketchConsType.horizontal: + case SketchConsType.vertical: + if (es.length != 1) return null; + return (es.first.id, ''); + case SketchConsType.parallel: + case SketchConsType.perpendicular: + case SketchConsType.equal: + case SketchConsType.concentric: + case SketchConsType.tangent: + if (es.length != 2) return null; + return (es[0].id, es[1].id); + case SketchConsType.pointOnEntity: + if (ps.length != 1 || es.length != 1) return null; + return (ps.first.id, es.first.id); + } +} + +// ===================== 修剪 ===================== + +/// 直线与其它实体的交点参数(0..1,沿 p1 → p2)。 +List sketchLineCuts( + SketchDoc doc, + SketchEntity line, { + double eps = 1e-4, +}) { + final SketchPoint? pa = doc.pointById(line.p1); + final SketchPoint? pb = doc.pointById(line.p2); + if (pa == null || pb == null) return []; + final Offset a = pa.pos; + final Offset b = pb.pos; + final Offset d = b - a; + final double len2 = d.dx * d.dx + d.dy * d.dy; + if (len2 < 1e-9) return []; + final List out = []; + for (final SketchEntity e in doc.entities) { + if (e.id == line.id) continue; + switch (e.kind) { + case SketchKind.line: + final Offset? qa = doc.pointById(e.p1)?.pos; + final Offset? qb = doc.pointById(e.p2)?.pos; + if (qa == null || qb == null) continue; + final Offset qd = qb - qa; + final double den = d.dx * qd.dy - d.dy * qd.dx; + if (den.abs() < 1e-9) continue; + final Offset w = qa - a; + final double t = (w.dx * qd.dy - w.dy * qd.dx) / den; + final double s = (w.dx * d.dy - w.dy * d.dx) / den; + if (t > eps && t < 1 - eps && s > -eps && s < 1 + eps) out.add(t); + case SketchKind.circle: + case SketchKind.arc: + final Offset? c = doc.pointById(e.p1)?.pos; + if (c == null) continue; + final double r = e.r; + final Offset f = a - c; + final double A = d.dx * d.dx + d.dy * d.dy; + final double B = 2 * (f.dx * d.dx + f.dy * d.dy); + final double C = f.dx * f.dx + f.dy * f.dy - r * r; + final double disc = B * B - 4 * A * C; + if (disc < 0) continue; + final double sq = math.sqrt(disc); + for (final double t in [(-B - sq) / (2 * A), (-B + sq) / (2 * A)]) { + if (t <= eps || t >= 1 - eps) continue; + if (e.kind == SketchKind.arc) { + final Offset pt = a + d * t; + final Offset? ps = doc.pointById(e.p2)?.pos; + final Offset? pe = doc.pointById(e.p3)?.pos; + if (ps == null || pe == null) continue; + if (!sketchAngleInArc(c, pt, ps, pe, e.ccw)) continue; + } + out.add(t); + } + } + } + out.sort(); + // 去重(容差 1e-4)。 + final List uniq = []; + for (final double t in out) { + if (uniq.isEmpty || t - uniq.last > 1e-4) uniq.add(t); + } + return uniq; +} + +/// 修剪一条直线:删除 [click] 所在的段(两交点之间 / 端点与交点之间)。 +/// +/// 返回修剪后的文档;直线完全被切除时返回删除后的文档; +/// 无法修剪(无交点或在交点外)返回 null。 +SketchDoc? sketchTrimLine(SketchDoc doc, String lineId, Offset click) { + final SketchEntity? line = doc.entityById(lineId); + if (line == null || line.kind != SketchKind.line) return null; + final SketchPoint? pa = doc.pointById(line.p1); + final SketchPoint? pb = doc.pointById(line.p2); + if (pa == null || pb == null) return null; + final Offset a = pa.pos; + final Offset b = pb.pos; + final Offset d = b - a; + final double len2 = d.dx * d.dx + d.dy * d.dy; + if (len2 < 1e-9) return null; + final double tc = + (((click - a).dx * d.dx + (click - a).dy * d.dy) / len2).clamp(0.0, 1.0); + final List cuts = sketchLineCuts(doc, line); + if (cuts.isEmpty) { + // 没有交点:整条删除。 + return doc.removeEntities({line.id}); + } + double left = 0; + double right = 1; + for (final double t in cuts) { + if (t <= tc) left = math.max(left, t); + if (t >= tc) right = math.min(right, t); + } + final bool keepLeft = left > 1e-3; + final bool keepRight = right < 1 - 1e-3; + SketchDoc next = doc; + // 中间段始终切除;线段可能在两端保留残余。 + final List pieces = []; + final List newPoints = []; + // 统一的新建 id 累加器,避免两段残余取到相同 id。 + final List freshIds = []; + String nextId(String prefix) { + final String id = sketchNewId(prefix, [...doc.allIds, ...freshIds]); + freshIds.add(id); + return id; + } + + if (keepLeft) { + final String nid = nextId('P'); + final SketchPoint pt = SketchPoint( + id: nid, + x: a.dx + d.dx * left, + y: a.dy + d.dy * left, + ); + newPoints.add(pt); + pieces.add(SketchEntity( + id: nextId('E'), + kind: SketchKind.line, + p1: line.p1, + p2: nid, + )); + } + if (keepRight) { + final String nid = nextId('P'); + final SketchPoint pt = SketchPoint( + id: nid, + x: a.dx + d.dx * right, + y: a.dy + d.dy * right, + ); + newPoints.add(pt); + pieces.add(SketchEntity( + id: nextId('E'), + kind: SketchKind.line, + p1: nid, + p2: line.p2, + )); + } + next = next.removeEntities({line.id}); + if (!keepLeft && !keepRight) return next; + // 修剪的残余段可能引用原端点(其点已被连带清理时需补回)。 + for (final SketchEntity e in pieces) { + for (final String pid in [e.p1, e.p2]) { + if (pid.isEmpty || next.pointById(pid) != null) continue; + if (pid == line.p1) next = next.upsertPoint(pa); + if (pid == line.p2) next = next.upsertPoint(pb); + } + } + for (final SketchPoint pt in newPoints) { + next = next.upsertPoint(pt); + } + for (final SketchEntity e in pieces) { + next = next.upsertEntity(e); + } + // 被修剪掉的中间段上原本挂接的点(无实体引用且非两端点)清理。 + final Set used = { + for (final SketchEntity e in next.entities) ...next.entityPointIds(e), + }; + return next.copyWith( + points: next.points + .where((SketchPoint p) => + used.contains(p.id) || p.id == line.p1 || p.id == line.p2) + .toList(), + ); +} diff --git a/lib/sketch/sketch_painter.dart b/lib/sketch/sketch_painter.dart new file mode 100644 index 0000000..bf5925c --- /dev/null +++ b/lib/sketch/sketch_painter.dart @@ -0,0 +1,362 @@ +/// 参数化草图绘制:几何(直线 / 圆 / 弧)、点(固定点高亮)、 +/// 约束图标(H / V / ∥ / ⊥ / = / ◎ / T)、驱动尺寸标注与预览。 +/// +/// 所有尺寸按 `1 / zoom` 逆缩放,保持屏幕像素恒定(CAD 观感)。 +library; + +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; + +import '../theme/tokens.dart'; +import 'sketch_models.dart'; + +/// 草图配色(浅 / 深色主题下都可读)。 +const int kSketchLineColor = 0xFF2F6FEB; +const int kSketchPointColor = 0xFF64748B; +const int kSketchFixedColor = 0xFFDC2626; +const int kSketchDimColor = 0xFF0F766E; +const int kSketchConsColor = 0xFF7C3AED; +const int kSketchSelColor = 0xFFF97316; +const int kSketchPreviewColor = 0xFF0EA5E9; + +/// 草图预览信息(绘制中的橡皮筋)。 +class SketchPreview { + /// 构造。 + const SketchPreview({required this.pts, this.kind = SketchKind.line, this.closed = false}); + + /// 预览点(世界坐标)。 + final List pts; + + /// 预览类型(line:折线描边;circle / arc 用第一点为圆心)。 + final SketchKind kind; + + /// 是否闭合描边。 + final bool closed; +} + +/// 绘制草图内容(调用方已完成 translate + scale)。 +void paintSketch( + Canvas canvas, + SketchDoc doc, + Tokens t, { + Set sel = const {}, + Offset? hover, + SketchPreview? preview, + Offset? snapMark, +}) { + // 逆缩放因子:通过画布变换取得真实缩放,保证线宽 / 字号恒定。 + final double scale = _canvasScale(canvas); + final double s = scale <= 0 ? 1 : 1 / scale; + + // ---- 几何 ---- + for (final SketchEntity e in doc.entities) { + final bool selected = sel.contains(e.id); + final Paint paint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = (selected ? 2.4 : 1.6) * s + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = Color(selected ? kSketchSelColor : kSketchLineColor); + switch (e.kind) { + case SketchKind.line: + final Offset? a = doc.pointById(e.p1)?.pos; + final Offset? b = doc.pointById(e.p2)?.pos; + if (a == null || b == null) break; + canvas.drawLine(a, b, paint); + case SketchKind.circle: + final Offset? c = doc.pointById(e.p1)?.pos; + if (c == null) break; + canvas.drawCircle(c, e.r, paint); + case SketchKind.arc: + final Offset? c = doc.pointById(e.p1)?.pos; + final Offset? ps = doc.pointById(e.p2)?.pos; + final Offset? pe = doc.pointById(e.p3)?.pos; + if (c == null || ps == null || pe == null) break; + final (double a1, double sweep) = + sketchArcAngles(c, ps, pe, e.ccw); + final Path path = Path() + ..addArc(Rect.fromCircle(center: c, radius: e.r), + e.ccw ? a1 : a1 - sweep, sweep); + canvas.drawPath(path, paint); + } + } + + // ---- 点 ---- + for (final SketchPoint p in doc.points) { + final bool selected = sel.contains(p.id); + final bool hovered = hover != null && (hover - p.pos).distance < 7 * s; + final double r = (hovered ? 3.6 : 2.8) * s; + canvas.drawRect( + Rect.fromCenter(center: p.pos, width: r * 2, height: r * 2), + Paint() + ..color = Color(selected + ? kSketchSelColor + : (p.fixed ? kSketchFixedColor : kSketchPointColor)), + ); + if (p.fixed) { + // 固定点:外圈提示锚定。 + canvas.drawCircle( + p.pos, + r * 2.2, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 * s + ..color = Color(kSketchFixedColor), + ); + } + } + + // ---- 约束图标 ---- + for (final SketchConstraint k in doc.constraints) { + if (k.internal) continue; + final List anchors = _consAnchors(doc, k); + for (final Offset a in anchors) { + _label(canvas, _consGlyph(k.type), a, s, + color: Color(kSketchConsColor), + bg: t.panel.withValues(alpha: 0.92)); + } + } + + // ---- 驱动尺寸 ---- + for (final SketchDim d in doc.dims) { + _dim(canvas, doc, d, t, s, sel.contains(d.id)); + } + + // ---- 预览 ---- + final SketchPreview? pv = preview; + if (pv != null && pv.pts.isNotEmpty) { + final Paint pp = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.8 * s + ..strokeCap = StrokeCap.round + ..color = Color(kSketchPreviewColor); + switch (pv.kind) { + case SketchKind.line: + if (pv.pts.length >= 2) { + final Path path = Path()..moveTo(pv.pts.first.dx, pv.pts.first.dy); + for (int i = 1; i < pv.pts.length; i++) { + path.lineTo(pv.pts[i].dx, pv.pts[i].dy); + } + if (pv.closed) path.close(); + canvas.drawPath(path, pp); + } + case SketchKind.circle: + if (pv.pts.length >= 2) { + canvas.drawCircle(pv.pts.first, + (pv.pts.last - pv.pts.first).distance, pp); + } + case SketchKind.arc: + if (pv.pts.length >= 3) { + final Offset c = pv.pts.first; + final Offset ps = pv.pts[1]; + final Offset pe = pv.pts.last; + final double r = (ps - c).distance; + final (double a1, double sweep) = sketchArcAngles(c, ps, pe, true); + canvas.drawPath( + Path() + ..addArc( + Rect.fromCircle(center: c, radius: r), a1, sweep), + pp, + ); + } + } + } + + // ---- 捕捉标记 ---- + final Offset? sm = snapMark; + if (sm != null) { + canvas.drawCircle( + sm, + 4.5 * s, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6 * s + ..color = Color(kSketchPreviewColor), + ); + } +} + +/// 取画布当前缩放的倒数(保持屏幕像素恒定的线宽 / 文字)。 +double _canvasScale(Canvas canvas) { + final Float64List m = canvas.getTransform(); + final double sx = math.sqrt(m[0] * m[0] + m[1] * m[1]); + final double sy = math.sqrt(m[4] * m[4] + m[5] * m[5]); + final double s = (sx + sy) / 2; + return s <= 0 ? 1 : s; +} + +/// 约束图标锚点(每个约束可画多处)。 +List _consAnchors(SketchDoc doc, SketchConstraint k) { + Offset? midEntity(String id) { + final SketchEntity? e = doc.entityById(id); + if (e == null) return null; + if (e.kind == SketchKind.line) { + final Offset? a = doc.pointById(e.p1)?.pos; + final Offset? b = doc.pointById(e.p2)?.pos; + if (a == null || b == null) return null; + final Offset m = Offset.lerp(a, b, 0.5)!; + final Offset d = b - a; + final double len = d.distance; + if (len < 1e-6) return m; + return m + Offset(-d.dy / len, d.dx / len) * 12; + } + final Offset? c = doc.pointById(e.p1)?.pos; + if (c == null) return null; + return c + Offset(e.r * 0.35, -e.r * 0.35); + } + + switch (k.type) { + case SketchConsType.horizontal: + case SketchConsType.vertical: + final Offset? m = midEntity(k.a); + return m == null ? [] : [m]; + case SketchConsType.pointOnEntity: + final Offset? p = doc.pointById(k.a)?.pos; + return p == null ? [] : [p + const Offset(10, -10)]; + case SketchConsType.concentric: + final Offset? c = doc.pointById(doc.entityById(k.a)?.p1)?.pos; + return c == null ? [] : [c + const Offset(14, -14)]; + default: + final List out = []; + final Offset? m1 = midEntity(k.a); + if (m1 != null) out.add(m1); + return out; + } +} + +String _consGlyph(SketchConsType t2) => switch (t2) { + SketchConsType.horizontal => 'H', + SketchConsType.vertical => 'V', + SketchConsType.parallel => '∥', + SketchConsType.perpendicular => '⊥', + SketchConsType.equal => '=', + SketchConsType.concentric => '◎', + SketchConsType.tangent => 'T', + SketchConsType.pointOnEntity => '⌐', + }; + +/// 画一条尺寸标注。 +void _dim( + Canvas canvas, + SketchDoc doc, + SketchDim d, + Tokens t, + double s, + bool selected, +) { + final Offset? anchor = sketchDimAnchor(doc, d); + if (anchor == null) return; + final Color color = Color(selected ? kSketchSelColor : kSketchDimColor); + final Paint line = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 * s + ..color = color; + + switch (d.type) { + case SketchDimType.length: + case SketchDimType.distance: + final (Offset p1, Offset p2) = d.type == SketchDimType.length + ? _entityEnds(doc, d.a) + : (doc.pointById(d.a)?.pos ?? Offset.zero, + doc.pointById(d.b)?.pos ?? Offset.zero); + final Offset dir = p2 - p1; + final double len = dir.distance; + if (len < 1e-6) return; + final Offset n = Offset(-dir.dy / len, dir.dx / len); + final double off = d.type == SketchDimType.length ? 18 : -20; + final Offset a2 = p1 + n * (off * s); + final Offset b2 = p2 + n * (off * s); + canvas.drawLine(a2, b2, line); + canvas.drawLine(p1, a2 + n * 3 * s, line); + canvas.drawLine(p2, b2 + n * 3 * s, line); + _tick(canvas, a2, n, s, color); + _tick(canvas, b2, n, s, color); + case SketchDimType.radius: + final SketchEntity? e = doc.entityById(d.a); + final Offset? c = doc.pointById(e?.p1)?.pos; + if (e == null || c == null) return; + final Offset dir = const Offset(0.7071, -0.7071); + final Offset end = c + dir * e.r; + canvas.drawLine(c, end, line); + canvas.drawLine( + c, + c + dir * (e.r * 0.45), + Paint() + ..strokeWidth = 3.2 * s + ..color = color); + case SketchDimType.angle: + final Offset? a1 = doc.pointById(doc.entityById(d.a)?.p1)?.pos; + final Offset? a2 = doc.pointById(doc.entityById(d.a)?.p2)?.pos; + if (a1 == null || a2 == null) return; + // 简化:在第一条线的中点画一个角度弧示意。 + final Offset m = Offset.lerp(a1, a2, 0.5)!; + canvas.drawCircle( + m, + 10 * s, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 * s + ..color = color, + ); + } + _label(canvas, sketchDimText(d), anchor, s, + color: color, bg: t.panel.withValues(alpha: 0.94), border: color); +} + +(Offset, Offset) _entityEnds(SketchDoc doc, String id) { + final SketchEntity? e = doc.entityById(id); + if (e == null) return (Offset.zero, Offset.zero); + return (doc.pointById(e.p1)?.pos ?? Offset.zero, + doc.pointById(e.p2)?.pos ?? Offset.zero); +} + +/// 尺寸界线端点的小斜线(CAD 风格刻度)。 +void _tick(Canvas canvas, Offset p, Offset n, double s, Color color) { + canvas.drawLine( + p + Offset(-n.dy, n.dx) * 3.5 * s, + p + Offset(n.dy, -n.dx) * 3.5 * s, + Paint() + ..strokeWidth = 1.2 * s + ..color = color, + ); +} + +/// 小圆角标签(逆缩放保持屏幕字号恒定)。 +void _label( + Canvas canvas, + String text, + Offset anchor, + double s, { + required Color color, + required Color bg, + Color? border, +}) { + final TextPainter tp = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + color: color, + fontSize: 10 * s, + fontWeight: FontWeight.w600, + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + final Rect r = Rect.fromCenter( + center: anchor, + width: tp.width + 8 * s, + height: tp.height + 3 * s, + ); + final RRect rr = RRect.fromRectAndRadius(r, Radius.circular(4 * s)); + canvas.drawRRect(rr, Paint()..color = bg); + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 * s + ..color = border ?? color.withValues(alpha: 0.45), + ); + tp.paint(canvas, r.center - Offset(tp.width / 2, tp.height / 2)); +} diff --git a/lib/sketch/sketch_solver.dart b/lib/sketch/sketch_solver.dart new file mode 100644 index 0000000..01eb160 --- /dev/null +++ b/lib/sketch/sketch_solver.dart @@ -0,0 +1,579 @@ +/// 参数化草图求解器:把「约束 + 驱动尺寸 + 拖拽目标」作为残差, +/// 用 Levenberg–Marquardt(数值雅可比)最小二乘求解点坐标与半径。 +/// +/// 权重约定(越大越硬): +/// - 几何约束 / 驱动尺寸:30(先满足); +/// - 拖拽目标:6(尽量跟随鼠标,但不破坏约束); +/// - 正则项:0.03(把无驱动变量轻微拉回原位,避免欠约束漂移)。 +library; + +import 'dart:math' as math; +import 'dart:ui' show Offset; + +import 'sketch_models.dart'; + +/// 求解结果。 +class SketchSolveResult { + /// 构造。 + const SketchSolveResult({ + required this.doc, + required this.converged, + required this.iterations, + required this.residual, + }); + + /// 求解后的文档。 + final SketchDoc doc; + + /// 是否收敛(残差平方和 < 1e-8)。 + final bool converged; + + /// 实际迭代次数。 + final int iterations; + + /// 最终残差平方和。 + final double residual; +} + +/// 求解草图:返回满足(尽量)约束与尺寸的新文档。 +/// +/// [dragPoints]:拖拽目标(点 id → 世界坐标);[dragRadii]:拖拽半径(实体 id → 半径)。 +SketchSolveResult solveSketch( + SketchDoc doc, { + Map dragPoints = const {}, + Map dragRadii = const {}, + int maxIter = 30, +}) { + final _VarSet vs = _VarSet(doc); + if (vs.n == 0) { + return SketchSolveResult( + doc: doc, converged: true, iterations: 0, residual: 0); + } + final _Access acc = _Access(doc, vs); + final List<_Res> res = <_Res>[]; + + for (final SketchConstraint k in doc.constraints) { + _addConstraint(doc, acc, k, res); + } + for (final SketchEntity e in doc.entities) { + _addArcInternal(doc, acc, e, res); + } + for (final SketchDim d in doc.dims) { + _addDim(doc, acc, d, res); + } + + // ---- 拖拽目标 ---- + dragPoints.forEach((String id, Offset t) { + if (doc.pointById(id) == null) return; + res.add(_Res(6, (List x) { + acc.x = x; + return acc.p(id).dx - t.dx; + })); + res.add(_Res(6, (List x) { + acc.x = x; + return acc.p(id).dy - t.dy; + })); + }); + dragRadii.forEach((String id, double r) { + final SketchEntity? e = doc.entityById(id); + if (e == null || e.kind == SketchKind.line) return; + res.add(_Res(6, (List x) { + acc.x = x; + return acc.r(id) - r; + })); + }); + + // ---- 正则项(soft stay) ---- + final List x0 = vs.x0(); + for (int i = 0; i < vs.n; i++) { + final int idx = i; + res.add(_Res(0.03, (List x) => x[idx] - x0[idx])); + } + + final (List x, bool conv, int iters, double err) = + _lm(res, x0, maxIter); + return SketchSolveResult( + doc: vs.apply(doc, x), + converged: conv, + iterations: iters, + residual: err, + ); +} + +/// 估算剩余自由度(变量数 − 独立约束数,粗略:约束 / 尺寸各算 1,同心算 2)。 +int sketchDofCount(SketchDoc doc) { + int vars = 0; + for (final SketchPoint p in doc.points) { + if (!p.fixed) vars += 2; + } + for (final SketchEntity e in doc.entities) { + if (e.kind != SketchKind.line) vars += 1; + } + int cons = 0; + for (final SketchConstraint k in doc.constraints) { + cons += k.type == SketchConsType.concentric ? 2 : 1; + } + cons += doc.dims.length; + for (final SketchEntity e in doc.entities) { + if (e.kind == SketchKind.arc) cons += 2; + } + final int dof = vars - cons; + return dof < 0 ? 0 : dof; +} + +// ===================== 残差构建 ===================== + +/// 几何约束残差。 +void _addConstraint( + SketchDoc doc, + _Access acc, + SketchConstraint k, + List<_Res> res, +) { + if (k.type == SketchConsType.horizontal || + k.type == SketchConsType.vertical) { + final SketchEntity? e = doc.entityById(k.a); + if (e == null || e.kind != SketchKind.line) return; + if (doc.pointById(e.p1) == null || doc.pointById(e.p2) == null) return; + final bool horiz = k.type == SketchConsType.horizontal; + res.add(_Res(30, (List x) { + acc.x = x; + return horiz + ? acc.p(e.p2).dy - acc.p(e.p1).dy + : acc.p(e.p2).dx - acc.p(e.p1).dx; + })); + return; + } + if (k.type == SketchConsType.parallel || + k.type == SketchConsType.perpendicular) { + final SketchEntity? e1 = doc.entityById(k.a); + final SketchEntity? e2 = doc.entityById(k.b); + if (e1 == null || + e2 == null || + e1.kind != SketchKind.line || + e2.kind != SketchKind.line) { + return; + } + final bool par = k.type == SketchConsType.parallel; + res.add(_Res(30, (List x) { + acc.x = x; + final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1); + final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1); + final double l1 = d1.distance; + final double l2 = d2.distance; + if (l1 < 1e-9 || l2 < 1e-9) return 0; + return par + ? (d1.dx * d2.dy - d1.dy * d2.dx) / (l1 * l2) + : (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2); + })); + return; + } + if (k.type == SketchConsType.equal) { + final SketchEntity? e1 = doc.entityById(k.a); + final SketchEntity? e2 = doc.entityById(k.b); + if (e1 == null || e2 == null) return; + res.add(_Res(30, (List x) { + acc.x = x; + if (e1.kind == SketchKind.line && e2.kind == SketchKind.line) { + return (acc.p(e1.p2) - acc.p(e1.p1)).distance - + (acc.p(e2.p2) - acc.p(e2.p1)).distance; + } + return acc.r(e1.id) - acc.r(e2.id); + })); + return; + } + if (k.type == SketchConsType.concentric) { + final SketchEntity? e1 = doc.entityById(k.a); + final SketchEntity? e2 = doc.entityById(k.b); + if (e1 == null || + e2 == null || + e1.kind == SketchKind.line || + e2.kind == SketchKind.line) { + return; + } + res.add(_Res(30, (List x) { + acc.x = x; + return acc.p(e1.p1).dx - acc.p(e2.p1).dx; + })); + res.add(_Res(30, (List x) { + acc.x = x; + return acc.p(e1.p1).dy - acc.p(e2.p1).dy; + })); + return; + } + if (k.type == SketchConsType.tangent) { + final SketchEntity? e1 = doc.entityById(k.a); + final SketchEntity? e2 = doc.entityById(k.b); + if (e1 == null || e2 == null) return; + final SketchEntity? line = e1.kind == SketchKind.line + ? e1 + : (e2.kind == SketchKind.line ? e2 : null); + final SketchEntity? circle = e1.kind != SketchKind.line + ? e1 + : (e2.kind != SketchKind.line ? e2 : null); + if (line != null && circle != null) { + res.add(_Res(30, (List x) { + acc.x = x; + final Offset a = acc.p(line.p1); + final Offset d = acc.p(line.p2) - a; + final double len = d.distance; + if (len < 1e-9) return 0; + final Offset c = acc.p(circle.p1); + final double dist = + ((c - a).dx * d.dy - (c - a).dy * d.dx).abs() / len; + return dist - acc.r(circle.id); + })); + } else if (e1.kind != SketchKind.line && e2.kind != SketchKind.line) { + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(e1.p1) - acc.p(e2.p1)).distance - + (acc.r(e1.id) + acc.r(e2.id)); + })); + } + return; + } + if (k.type == SketchConsType.pointOnEntity) { + final SketchPoint? pt = doc.pointById(k.a); + final SketchEntity? e = doc.entityById(k.b); + if (pt == null || e == null) return; + if (e.kind == SketchKind.line) { + res.add(_Res(30, (List x) { + acc.x = x; + final Offset a = acc.p(e.p1); + final Offset d = acc.p(e.p2) - a; + final double len = d.distance; + if (len < 1e-9) return 0; + final Offset pp = acc.p(pt.id); + return ((pp - a).dx * d.dy - (pp - a).dy * d.dx) / len; + })); + } else { + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(pt.id) - acc.p(e.p1)).distance - acc.r(e.id); + })); + } + } +} + +/// 圆弧内部约束:端点落在圆上。 +void _addArcInternal( + SketchDoc doc, + _Access acc, + SketchEntity e, + List<_Res> res, +) { + if (e.kind != SketchKind.arc) return; + if (doc.pointById(e.p1) == null || + doc.pointById(e.p2) == null || + doc.pointById(e.p3) == null) { + return; + } + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(e.p2) - acc.p(e.p1)).distance - acc.r(e.id); + })); + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(e.p3) - acc.p(e.p1)).distance - acc.r(e.id); + })); +} + +/// 驱动尺寸残差。 +void _addDim(SketchDoc doc, _Access acc, SketchDim d, List<_Res> res) { + if (d.type == SketchDimType.length) { + final SketchEntity? e = doc.entityById(d.a); + if (e == null || e.kind != SketchKind.line) return; + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(e.p2) - acc.p(e.p1)).distance - d.value; + })); + return; + } + if (d.type == SketchDimType.radius) { + final SketchEntity? e = doc.entityById(d.a); + if (e == null || e.kind == SketchKind.line) return; + res.add(_Res(30, (List x) { + acc.x = x; + return acc.r(e.id) - d.value; + })); + return; + } + if (d.type == SketchDimType.angle) { + final SketchEntity? e1 = doc.entityById(d.a); + final SketchEntity? e2 = doc.entityById(d.b); + if (e1 == null || + e2 == null || + e1.kind != SketchKind.line || + e2.kind != SketchKind.line) { + return; + } + final double cosTarget = + math.cos(d.value.clamp(0.01, 179.99) * math.pi / 180); + res.add(_Res(30, (List x) { + acc.x = x; + final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1); + final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1); + final double l1 = d1.distance; + final double l2 = d2.distance; + if (l1 < 1e-9 || l2 < 1e-9) return 0; + return (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2) - cosTarget; + })); + return; + } + if (d.type == SketchDimType.distance) { + if (doc.pointById(d.a) == null || doc.pointById(d.b) == null) return; + res.add(_Res(30, (List x) { + acc.x = x; + return (acc.p(d.b) - acc.p(d.a)).distance - d.value; + })); + } +} + +// ===================== 求解内部实现 ===================== + +/// 残差项:函数 + 权重。 +class _Res { + const _Res(this.weight, this.f); + + /// 权重。 + final double weight; + + /// 残差函数(输入变量向量)。 + final double Function(List x) f; +} + +/// 变量集:点坐标(未固定的点)与半径(圆 / 弧)。 +class _VarSet { + _VarSet(this.doc) { + for (final SketchPoint p in doc.points) { + if (p.fixed) continue; + _pointIndex[p.id] = _n; + _n += 2; + } + for (final SketchEntity e in doc.entities) { + if (e.kind == SketchKind.line) continue; + _radiusIndex[e.id] = _n; + _n += 1; + } + } + + /// 源文档。 + final SketchDoc doc; + + /// 变量总数。 + int _n = 0; + + /// 点 → 变量下标(x, y)。 + final Map _pointIndex = {}; + + /// 实体 → 半径变量下标。 + final Map _radiusIndex = {}; + + /// 变量总数。 + int get n => _n; + + /// 初始变量向量。 + List x0() { + final List x = List.filled(_n, 0); + for (final SketchPoint p in doc.points) { + final int? i = _pointIndex[p.id]; + if (i == null) continue; + x[i] = p.x; + x[i + 1] = p.y; + } + for (final SketchEntity e in doc.entities) { + final int? i = _radiusIndex[e.id]; + if (i == null) continue; + x[i] = e.r; + } + return x; + } + + /// 把变量向量写回文档。 + SketchDoc apply(SketchDoc source, List x) { + final List pts = [ + for (final SketchPoint p in source.points) + _pointIndex.containsKey(p.id) + ? p.copyWith( + x: x[_pointIndex[p.id]!], + y: x[_pointIndex[p.id]! + 1], + ) + : p, + ]; + final List ents = [ + for (final SketchEntity e in source.entities) + _radiusIndex.containsKey(e.id) + ? e.copyWith(r: math.max(0.5, x[_radiusIndex[e.id]!])) + : e, + ]; + return source.copyWith(points: pts, entities: ents); + } +} + +/// 访问器:把变量向量映射为点坐标 / 半径(未参与求解的取文档原值)。 +class _Access { + _Access(this.doc, this.vs); + + final SketchDoc doc; + final _VarSet vs; + + /// 当前变量向量。 + late List x; + + /// 取点坐标。 + Offset p(String id) { + final int? i = vs._pointIndex[id]; + if (i != null) return Offset(x[i], x[i + 1]); + final SketchPoint? pt = doc.pointById(id); + return pt == null ? Offset.zero : pt.pos; + } + + /// 取半径。 + double r(String id) { + final int? i = vs._radiusIndex[id]; + if (i != null) return x[i]; + return doc.entityById(id)?.r ?? 0; + } +} + +/// Levenberg–Marquardt:返回(解, 是否收敛, 迭代数, 残差平方和)。 +(List, bool, int, double) _lm( + List<_Res> res, + List x0, + int maxIter, +) { + final int n = x0.length; + final List x = List.of(x0); + + double err(List v) { + double s = 0; + for (final _Res r in res) { + final double e = r.weight * r.f(v); + s += e * e; + } + return s; + } + + double e0 = err(x); + double lambda = 1e-4; + int iters = 0; + const double convTol = 1e-10; + + for (int it = 0; it < maxIter; it++) { + if (e0 < convTol) break; + iters = it + 1; + final List rv = List.generate( + res.length, (int i) => res[i].weight * res[i].f(x)); + final List> jac = List>.generate( + res.length, + (int _) => List.filled(n, 0), + ); + for (int j = 0; j < n; j++) { + final double h = 1e-5 * (1 + x[j].abs()); + final double old = x[j]; + x[j] = old + h; + for (int i = 0; i < res.length; i++) { + jac[i][j] = (res[i].weight * res[i].f(x) - rv[i]) / h; + } + x[j] = old; + } + final List> a = + List>.generate(n, (int _) => List.filled(n, 0)); + final List g = List.filled(n, 0); + for (int i = 0; i < res.length; i++) { + final List ji = jac[i]; + final double ri = rv[i]; + for (int p = 0; p < n; p++) { + final double vp = ji[p]; + if (vp == 0) continue; + g[p] -= vp * ri; + for (int q = p; q < n; q++) { + a[p][q] += vp * ji[q]; + } + } + } + for (int p = 0; p < n; p++) { + for (int q = 0; q < p; q++) { + a[p][q] = a[q][p]; + } + } + bool accepted = false; + for (int t = 0; t < 8; t++) { + // 单位阵阻尼(标准 LM):秩缺陷方向的 diag(A) 元极小, + // 若按 diag(A) 阻尼会产生病态大跳步,这里统一按标量阻尼。 + final List> ad = List>.generate( + n, + (int p) => List.generate( + n, + (int q) => a[p][q] + (p == q ? lambda : 0.0), + ), + ); + final List? d = _solveLinear(ad, g); + if (d == null) { + lambda *= 8; + if (lambda > 1e9) break; + continue; + } + final List x2 = + List.generate(n, (int p) => x[p] + d[p]); + final double e2 = err(x2); + if (e2 < e0) { + for (int p = 0; p < n; p++) { + x[p] = x2[p]; + } + e0 = e2; + lambda = math.max(lambda / 4, 1e-9); + accepted = true; + break; + } + lambda *= 6; + if (lambda > 1e9) break; + } + if (!accepted) break; + } + return (x, e0 < 1e-8, iters, e0); +} + +/// 高斯消元(部分主元);奇异返回 null。 +List? _solveLinear(List> m, List b) { + final int n = b.length; + final List> a = >[ + for (int i = 0; i < n; i++) [...m[i], b[i]], + ]; + for (int col = 0; col < n; col++) { + int piv = col; + double best = a[col][col].abs(); + for (int r = col + 1; r < n; r++) { + final double v = a[r][col].abs(); + if (v > best) { + best = v; + piv = r; + } + } + if (best < 1e-12) return null; + if (piv != col) { + final List tmp = a[piv]; + a[piv] = a[col]; + a[col] = tmp; + } + final double d = a[col][col]; + for (int r = col + 1; r < n; r++) { + final double f = a[r][col] / d; + if (f == 0) continue; + for (int ccol = col; ccol <= n; ccol++) { + a[r][ccol] -= f * a[col][ccol]; + } + } + } + final List x = List.filled(n, 0); + for (int i = n - 1; i >= 0; i--) { + double s = a[i][n]; + for (int j = i + 1; j < n; j++) { + s -= a[i][j] * x[j]; + } + final double d = a[i][i]; + if (d.abs() < 1e-12) return null; + x[i] = s / d; + } + return x; +} diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart index 936a314..90428a3 100644 --- a/lib/state/app_controller.dart +++ b/lib/state/app_controller.dart @@ -10,12 +10,17 @@ library; import 'dart:async'; import 'dart:convert'; +import 'dart:io' show File; import 'dart:math' as math; 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'; @@ -40,6 +45,61 @@ class AppController extends ChangeNotifier { /// 当前主题亮度(默认浅色 / 白底)。 Brightness _brightness = Brightness.light; + /// 当前顶层设计模块(时序图 / 架构图);仅运行时状态,不随文件保存。 + AppMode _appMode = AppMode.sequence; + + /// 架构图当前工具。 + ArchTool _archTool = ArchTool.select; + + /// 架构图画笔颜色(新图形默认色)。 + int _archColor = kArchPalette[0]; + + /// 架构图连线默认走线方式(直线 / 正交折线)。 + ArchRoute _archRoute = ArchRoute.straight; + + /// 架构图网格吸附开关相关的运行时设置。 + /// 正交模式(F8):移动约束到水平 / 垂直主轴。 + bool _archOrtho = false; + + /// 极轴追踪(F10):移动方向吸附到设定角度的整数倍。 + bool _archPolar = false; + + /// 极轴角度(度,默认 15)。 + double _archPolarDeg = 15; + + /// 四边标尺显示开关(默认开,Adobe 风格)。 + bool _archRulers = true; + + /// 架构图当前选中元素 id 列表(运行时状态,支持多选)。 + List _archSelIds = const []; + + /// 是否处于参数化草图模式。 + bool _sketchMode = false; + + /// 草图当前工具。 + SketchTool _sketchTool = SketchTool.select; + + /// 草图选中 id(点 / 实体 / 尺寸混选)。 + List _sketchSelIds = const []; + + /// 草图待执行的约束命令(Creo 风格:先选命令,再点对象执行;null = 无)。 + SketchConsType? _sketchPendingCons; + + /// 草图待执行的尺寸命令(null = 无)。 + SketchDimType? _sketchPendingDim; + + /// 命令模式下已拾取的对象 id(点 / 实体)。 + List _sketchPendingIds = const []; + + /// 新标注尺寸后待编辑的尺寸 id(视图弹出数值编辑框用)。 + String? _sketchDimToEdit; + + /// 架构图画布视口尺寸(由画布回填,不触发通知)。 + Size _archViewport = Size.zero; + + /// 「识别演示」令牌:递增一次,架构图画布收到后播放识别动画。 + int _archPlayToken = 0; + /// 是否已获得有效授权(有效时才允许导出 SVG / PNG / drawio)。 /// /// 1.3.4 起授权校验临时冻结([kLicenseRequired] = false):始终视为已授权, @@ -59,6 +119,16 @@ class AppController extends ChangeNotifier { /// 当前项目对应的文件路径;null 表示尚未保存。 String? _filePath; + /// 架构图文档的独立文件路径(`*.arch.json`);null 表示尚未保存。 + String? _archFilePath; + + /// 当前模块对应的文件路径(标题 / 状态显示用)。 + String? get currentFilePath => + _appMode == AppMode.architecture ? _archFilePath : _filePath; + + /// 架构图文档文件路径。 + String? get archFilePath => _archFilePath; + /// 是否有未保存修改。 bool _dirty; @@ -180,9 +250,11 @@ class AppController extends ChangeNotifier { /// /// - 间隔 = [Project.autoSaveMinutes](默认 10 分钟,1–240); /// - 以 [_lastSavedAt] 为基准:任何一次手动 / 自动保存都会重置计时; - /// - 安卓写入公共 Documents,桌面写 `.seq.json` 并同步 `.bak` 备份。 + /// - 时序图写 `*.seq.json`(不含架构图部分);架构图写 `*.arch.json`; + /// 安卓写入公共 Documents,桌面写文件并同步 `.bak` 备份。 Future _autoSaveDocument() async { - final String? path = _filePath; + final String? path = + _appMode == AppMode.architecture ? _archFilePath : _filePath; if (!_project.autoSaveEnabled || !_dirty || path == null) return; final DateTime now = DateTime.now(); // 从未保存过时间戳(如刚打开文件):以“现在”为基准,等满一个间隔再自动保存。 @@ -195,10 +267,22 @@ class AppController extends ChangeNotifier { if (now.difference(_lastSavedAt!).inSeconds < minutes * 60) return; _lastSavedAt = now; try { - if (AndroidDocs.isAvailable) { + if (_appMode == AppMode.architecture) { + final String json = _project.arch.encode(); + if (AndroidDocs.isAvailable) { + await AndroidDocs.saveFile( + _baseName(path), + Uint8List.fromList(utf8.encode(json)), + mime: 'application/json', + ); + } else { + await Storage.instance.backupExisting(path); + await File(path).writeAsString(json, flush: true); + } + } else if (AndroidDocs.isAvailable) { await AndroidDocs.saveFile( _baseName(path), - Uint8List.fromList(utf8.encode(_project.encode())), + Uint8List.fromList(utf8.encode(_project.encode(includeArch: false))), mime: 'application/json', ); } else { @@ -298,6 +382,1132 @@ class AppController extends ChangeNotifier { notifyListeners(); } + /// 直接设置主题亮度(软件设置用)。 + void setTheme(Brightness b) { + if (_brightness == b) return; + _brightness = b; + notifyListeners(); + } + + // ============ 设计合集(模块切换)与架构图 ============ + + /// 当前顶层设计模块(时序图 / 架构图)。 + AppMode get appMode => _appMode; + + /// 切换顶层设计模块并刷新界面(品牌菜单 / 首页调用)。 + void setAppMode(AppMode m) { + if (_appMode == m) return; + _appMode = m; + _status = switch (m) { + AppMode.home => '首页', + AppMode.sequence => '时序图设计', + AppMode.architecture => '架构图设计 · 手绘识别', + }; + notifyListeners(); + } + + /// 返回首页(空白启动工作台):关闭当前文档视图。 + /// + /// 语义上「首页 = 没有打开的文档」:清除脏标记与文件路径 + /// (当前文档数据在进入新模块时会由新建文档替换)。 + /// 外壳在离开「有未保存修改的文档」前负责弹窗确认。 + void goHome() { + final bool changed = _appMode != AppMode.home || + _dirty || + _filePath != null || + _archFilePath != null; + _appMode = AppMode.home; + _dirty = false; + _filePath = null; + _archFilePath = null; + _status = '首页'; + if (changed) notifyListeners(); + } + + /// 架构图当前工具。 + ArchTool get archTool => _archTool; + + /// 切换架构图工具。 + void setArchTool(ArchTool tool) { + if (_archTool == tool) return; + _archTool = tool; + _status = switch (tool) { + ArchTool.select => '工具:选择', + ArchTool.pen => '工具:手绘(松手自动识别)', + ArchTool.connect => '工具:连线(拖到图形自动吸附)', + }; + notifyListeners(); + } + + // ===================== 参数化草图 ===================== + + /// 是否处于参数化草图模式。 + bool get sketchMode => _sketchMode; + + /// 草图当前工具。 + SketchTool get sketchTool => _sketchTool; + + /// 草图选中 id。 + List get sketchSelIds => _sketchSelIds; + + /// 当前草图文档。 + SketchDoc get sketch => arch.sketch; + + /// 进入 / 退出参数化草图模式。 + void setSketchMode(bool on) { + if (_sketchMode == on) return; + _sketchMode = on; + _sketchTool = SketchTool.select; + _sketchSelIds = const []; + _cancelSketchCommandInternal(); + if (on) _archSelIds = const []; + _status = on ? '参数化草图:约束 + 驱动尺寸(改尺寸即驱动几何)' : '架构图设计'; + notifyListeners(); + } + + /// 切换草图工具。 + void setSketchTool(SketchTool t) { + if (_sketchTool == t) return; + _sketchTool = t; + _sketchSelIds = const []; + _cancelSketchCommandInternal(); + _status = switch (t) { + SketchTool.select => '草图:选择 / 拖动(约束实时求解)', + SketchTool.line => '草图:直线(点两下;近轴自动水平 / 竖直)', + SketchTool.circle => '草图:圆(点圆心,再点半径点)', + SketchTool.arc => '草图:圆弧(圆心 → 起点 → 终点)', + SketchTool.rect => '草图:矩形(对角两点,自动水平 / 竖直)', + SketchTool.trim => '草图:修剪(点击线段删除该段)', + }; + notifyListeners(); + } + + /// 替换草图选择。 + void selectSketchIds(List ids) { + if (_sameIds(ids, _sketchSelIds)) return; + _sketchSelIds = List.of(ids); + notifyListeners(); + } + + /// 切换某个草图对象的选中状态(Shift 点选)。 + void toggleSketchId(String id) { + final List cur = List.of(_sketchSelIds); + if (cur.contains(id)) { + cur.remove(id); + } else { + cur.add(id); + } + _sketchSelIds = cur; + notifyListeners(); + } + + // ---- 约束 / 尺寸命令流(Creo 风格:先点命令,再点对象执行) ---- + + /// 待执行的约束命令(null = 无)。 + SketchConsType? get sketchPendingCons => _sketchPendingCons; + + /// 待执行的尺寸命令(null = 无)。 + SketchDimType? get sketchPendingDim => _sketchPendingDim; + + /// 命令模式下已拾取的对象 id。 + List get sketchPendingIds => _sketchPendingIds; + + /// 新标注尺寸后待编辑的尺寸 id(视图弹数值编辑框后调用 + /// [clearSketchDimToEdit])。 + String? get sketchDimToEdit => _sketchDimToEdit; + + /// 清除「待编辑尺寸」标记(视图完成弹窗后调用)。 + void clearSketchDimToEdit() { + _sketchDimToEdit = null; + } + + /// 进入约束命令(再次点击同一命令 = 取消)。 + void beginSketchConstraint(SketchConsType type) { + if (_sketchPendingCons == type && + _sketchPendingDim == null && + _sketchPendingIds.isEmpty) { + cancelSketchCommand(); + return; + } + _sketchPendingCons = type; + _sketchPendingDim = null; + _sketchPendingIds = const []; + _status = _consHint(type, 0); + notifyListeners(); + } + + /// 进入尺寸命令(再次点击同一命令 = 取消)。 + void beginSketchDim(SketchDimType type) { + if (_sketchPendingDim == type && + _sketchPendingCons == null && + _sketchPendingIds.isEmpty) { + cancelSketchCommand(); + return; + } + _sketchPendingDim = type; + _sketchPendingCons = null; + _sketchPendingIds = const []; + _status = _dimHint(type, 0); + notifyListeners(); + } + + /// 取消当前草图命令(Esc / 面板「取消」)。 + void cancelSketchCommand() { + if (_sketchPendingCons == null && + _sketchPendingDim == null && + _sketchPendingIds.isEmpty) { + return; + } + _cancelSketchCommandInternal(); + _status = '草图:选择 / 拖动(约束实时求解)'; + notifyListeners(); + } + + void _cancelSketchCommandInternal() { + _sketchPendingCons = null; + _sketchPendingDim = null; + _sketchPendingIds = const []; + } + + /// 命令模式点选(视图命中后调用;约束 / 尺寸命令共用)。 + void sketchCommandPick(SketchHit hit) { + final SketchDoc d = arch.sketch; + if (_sketchPendingDim != null) { + _sketchDimPick(d, _sketchPendingDim!, hit); + return; + } + if (_sketchPendingCons != null) { + _sketchConsPick(d, _sketchPendingCons!, hit); + } + } + + /// 约束命令点选:单选约束点一下;双对象约束依次点选;非法对象给出提示。 + void _sketchConsPick(SketchDoc d, SketchConsType type, SketchHit hit) { + final String? pid = hit.pointId; + final String? eid = hit.entityId; + // 单选约束:一条直线即执行。 + if (type == SketchConsType.horizontal || type == SketchConsType.vertical) { + final SketchEntity? e = d.entityById(eid); + if (e == null || e.kind != SketchKind.line) { + _status = _consHint(type, 0); + notifyListeners(); + return; + } + _applyConstraint(type, e.id, ''); + _status = '已加${sketchConsLabel(type)}约束 · ${_consHint(type, 0)}'; + notifyListeners(); + return; + } + // 点在实体上:点 / 实体任意顺序;同类再点 = 替换。 + if (type == SketchConsType.pointOnEntity) { + if (pid == null && eid == null) { + _status = _consHint(type, _sketchPendingIds.length); + notifyListeners(); + return; + } + final bool pickIsPoint = pid != null; + final List picks = [ + for (final String id in _sketchPendingIds) + if ((d.pointById(id) != null) != pickIsPoint) id, + pid ?? eid!, + ]; + String? pointId; + String? entityId; + for (final String id in picks) { + if (d.pointById(id) != null) pointId = id; + if (d.entityById(id) != null) entityId = id; + } + if (pointId != null && entityId != null) { + _applyConstraint(SketchConsType.pointOnEntity, pointId, entityId); + _sketchPendingIds = const []; + _status = '已加「点在线上」约束 · ${_consHint(type, 0)}'; + } else { + _sketchPendingIds = picks; + _status = _consHint(type, picks.length); + } + notifyListeners(); + return; + } + // 双对象约束:依次点选(再点同一对象 = 撤销该次拾取)。 + if (eid == null) { + _status = _consHint(type, _sketchPendingIds.length); + notifyListeners(); + return; + } + final List picks = List.of(_sketchPendingIds); + if (picks.contains(eid)) { + picks.remove(eid); + _sketchPendingIds = picks; + _status = _consHint(type, picks.length); + notifyListeners(); + return; + } + picks.add(eid); + if (picks.length < 2) { + _sketchPendingIds = picks; + _status = _consHint(type, 1); + notifyListeners(); + return; + } + if (!sketchCanConstrain(d, type, picks)) { + _status = '${sketchConsLabel(type)}:所选对象类型不符合'; + _sketchPendingIds = const []; + notifyListeners(); + return; + } + _applyConstraint(type, picks[0], picks[1]); + _sketchPendingIds = const []; + _status = '已加${sketchConsLabel(type)}约束 · ${_consHint(type, 0)}'; + notifyListeners(); + } + + /// 尺寸命令点选:点够对象即自动标注(当前测量值),随后可改值驱动。 + void _sketchDimPick(SketchDoc d, SketchDimType type, SketchHit hit) { + final String? pid = hit.pointId; + final String? eid = hit.entityId; + switch (type) { + case SketchDimType.length: + final SketchEntity? e = d.entityById(eid); + if (e == null || e.kind != SketchKind.line) { + _status = _dimHint(type, 0); + notifyListeners(); + return; + } + _createDim(type, e.id, ''); + case SketchDimType.radius: + final SketchEntity? e = d.entityById(eid); + if (e == null || e.kind == SketchKind.line) { + _status = _dimHint(type, 0); + notifyListeners(); + return; + } + _createDim(type, e.id, ''); + case SketchDimType.angle: + if (eid == null || d.entityById(eid)?.kind != SketchKind.line) { + _status = _dimHint(type, _sketchPendingIds.length); + notifyListeners(); + return; + } + _dimTwoEntityPick(d, type, eid); + case SketchDimType.distance: + if (pid == null) { + _status = _dimHint(type, _sketchPendingIds.length); + notifyListeners(); + return; + } + if (_sketchPendingIds.contains(pid)) { + _sketchPendingIds = + [for (final String x in _sketchPendingIds) if (x != pid) x]; + _status = _dimHint(type, _sketchPendingIds.length); + notifyListeners(); + return; + } + final List picks = [..._sketchPendingIds, pid]; + if (picks.length < 2) { + _sketchPendingIds = picks; + _status = _dimHint(type, 1); + notifyListeners(); + return; + } + _sketchPendingIds = const []; + _createDim(type, picks[0], picks[1]); + } + } + + /// 角度尺寸:两条直线依次点选。 + void _dimTwoEntityPick(SketchDoc d, SketchDimType type, String eid) { + final List picks = List.of(_sketchPendingIds); + if (picks.contains(eid)) { + picks.remove(eid); + _sketchPendingIds = picks; + _status = _dimHint(type, picks.length); + notifyListeners(); + return; + } + picks.add(eid); + if (picks.length < 2) { + _sketchPendingIds = picks; + _status = _dimHint(type, 1); + notifyListeners(); + return; + } + _sketchPendingIds = const []; + _createDim(type, picks[0], picks[1]); + } + + /// 应用约束(构建 + 求解 + 入撤销栈)。 + void _applyConstraint(SketchConsType type, String a, String b) { + final SketchDoc d = arch.sketch; + final SketchConstraint k = SketchConstraint( + id: sketchNewId('K', d.allIds), + type: type, + a: a, + b: b, + ); + final SketchSolveResult r = solveSketch( + d.copyWith(constraints: [...d.constraints, k]), + ); + changeSketch( + (_) => r.doc, + status: '添加约束:${sketchConsLabel(type)}' + '${r.converged ? '' : '(冲突:未完全满足)'}', + ); + } + + /// 创建驱动尺寸(当前测量值)并标记为「待编辑」(视图弹数值框)。 + void _createDim(SketchDimType type, String a, String b) { + final SketchDoc d = arch.sketch; + final double value = sketchMeasure(d, type, a, b) ?? 10; + final SketchDim nd = SketchDim( + id: sketchNewId('D', d.allIds), + type: type, + value: value, + a: a, + b: b, + ); + _sketchDimToEdit = nd.id; + final SketchSolveResult r = solveSketch( + d.copyWith(dims: [...d.dims, nd]), + ); + changeSketch( + (_) => r.doc, + status: '标注${sketchDimLabel(type)}:${sketchDimText(nd)}(输入数值可精确驱动)', + ); + } + + /// 约束命令的分步提示。 + String _consHint(SketchConsType type, int picked) => switch (type) { + SketchConsType.horizontal => '水平约束:点击一条直线', + SketchConsType.vertical => '竖直约束:点击一条直线', + SketchConsType.parallel => + picked == 0 ? '平行约束:点击第一条直线' : '平行约束:点击第二条直线', + SketchConsType.perpendicular => + picked == 0 ? '垂直约束:点击第一条直线' : '垂直约束:点击第二条直线', + SketchConsType.equal => + picked == 0 ? '相等约束:点击第一个对象' : '相等约束:点击第二个对象', + SketchConsType.concentric => picked == 0 + ? '同心约束:点击第一个圆 / 弧' + : '同心约束:点击第二个圆 / 弧', + SketchConsType.tangent => picked == 0 + ? '相切约束:点击第一个对象(线 / 圆)' + : '相切约束:点击第二个对象', + SketchConsType.pointOnEntity => picked == 0 + ? '点在线上:点击一个点(或先点目标线 / 圆)' + : '点在线上:再点击另一个目标(点 + 线 / 圆)', + }; + + /// 尺寸命令的分步提示。 + String _dimHint(SketchDimType type, int picked) => switch (type) { + SketchDimType.length => '长度尺寸:点击一条直线', + SketchDimType.radius => '半径尺寸:点击圆或弧', + SketchDimType.angle => + picked == 0 ? '角度尺寸:点击第一条直线' : '角度尺寸:点击第二条直线', + SketchDimType.distance => + picked == 0 ? '距离尺寸:点击第一个点' : '距离尺寸:点击第二个点', + }; + + /// 变更草图文档(统一入口:撤销 / 脏标记 / 刷新)。 + void changeSketch( + SketchDoc Function(SketchDoc doc) fn, { + String? status, + bool undo = true, + }) { + _changeArch( + arch.copyWith(sketch: fn(arch.sketch)), + status: status, + undo: undo, + ); + } + + /// 拖拽开始:压一次撤销快照(拖拽过程不再逐步入栈)。 + void beginSketchUndo() { + _undo.add(_project); + if (_undo.length > 200) _undo.removeAt(0); + _redo.clear(); + } + + /// 拖拽中的实时求解(不入撤销栈)。 + void dragSketch({ + Map points = const {}, + Map radii = const {}, + }) { + if (points.isEmpty && radii.isEmpty) return; + final SketchSolveResult r = solveSketch( + arch.sketch, + dragPoints: points, + dragRadii: radii, + ); + _project = _project.copyWith(arch: arch.copyWith(sketch: r.doc)); + _dirty = true; + notifyListeners(); + } + + /// 全选草图对象(实体 + 尺寸)。 + void selectAllSketch() { + selectSketchIds([ + for (final SketchEntity e in arch.sketch.entities) e.id, + for (final SketchDim d in arch.sketch.dims) d.id, + ]); + } + + // ---- 识别后图形的尺寸编辑(不走约束求解器:直接缩放几何) ---- + + /// 修改图形尺寸(识别后图形 / 曲线 / 图元直接改值缩放)。 + void setArchShapeDim(String id, ArchDimKind kind, double value) { + final ArchShape? s = arch.shapeById(id); + if (s == null || value <= 0) return; + updateArchShape( + archShapeApplyDim(s, kind, value), + status: '${s.text.isNotEmpty ? s.text : archShapeTypeLabel(s.type)}' + ':${archDimKindLabel(kind)} → ${value.toStringAsFixed(1)} mm', + ); + } + + /// 切换画布尺寸标注(显示 / 隐藏;双击标签可改值)。 + void toggleArchShapeDim(String id, ArchDimKind kind) { + final ArchShape? s = arch.shapeById(id); + if (s == null) return; + final Set next = Set.of(s.dims); + final bool removed = next.remove(kind); + if (!removed) next.add(kind); + updateArchShape( + s.copyWith(dims: next), + status: removed + ? '已取消${archDimKindLabel(kind)}标注' + : '已标注${archDimKindLabel(kind)}(双击标签可改值)', + ); + } + + /// 删除选中的草图对象。 + void deleteSketchSelection() { + if (_sketchSelIds.isEmpty) return; + final Set ids = _sketchSelIds.toSet(); + _sketchSelIds = const []; + changeSketch((SketchDoc d) => d.removeAny(ids), status: '删除草图对象(${ids.length})'); + } + + /// 添加几何约束(引用从当前选择解析)并立即求解。 + void addSketchConstraint(SketchConsType type) { + final SketchDoc d = arch.sketch; + if (!sketchCanConstrain(d, type, _sketchSelIds)) { + _status = '${sketchConsLabel(type)}:当前选择不满足(需选中 1–2 个对象)'; + notifyListeners(); + return; + } + final (String, String)? refs = sketchConsRefs(d, type, _sketchSelIds); + if (refs == null) return; + final SketchConstraint k = SketchConstraint( + id: sketchNewId('K', d.allIds), + type: type, + a: refs.$1, + b: refs.$2, + ); + final SketchSolveResult r = solveSketch( + d.copyWith(constraints: [...d.constraints, k]), + ); + changeSketch( + (_) => r.doc, + status: '添加约束:${sketchConsLabel(type)}' + '${r.converged ? '' : '(冲突:未完全满足)'}', + ); + } + + /// 添加驱动尺寸(引用从当前选择解析)并立即求解。 + void addSketchDim(SketchDimType type, double value) { + final SketchDoc d = arch.sketch; + if (!sketchCanDim(d, type, _sketchSelIds)) { + _status = '${sketchDimLabel(type)}尺寸:当前选择不满足'; + notifyListeners(); + return; + } + final (String, String)? refs = sketchDimRefs(d, type, _sketchSelIds); + if (refs == null) return; + final SketchDim nd = SketchDim( + id: sketchNewId('D', d.allIds), + type: type, + value: value, + a: refs.$1, + b: refs.$2, + ); + final SketchSolveResult r = solveSketch( + d.copyWith(dims: [...d.dims, nd]), + ); + changeSketch( + (_) => r.doc, + status: '驱动尺寸:${sketchDimText(nd)}' + '${r.converged ? '' : '(冲突:未完全满足)'}', + ); + } + + /// 修改驱动尺寸数值(双击尺寸标签)并求解。 + void setSketchDimValue(String id, double value) { + final SketchDim? d = arch.sketch.dimById(id); + if (d == null || value <= 0) return; + final SketchDoc next = arch.sketch.copyWith( + dims: [ + for (final SketchDim x in arch.sketch.dims) + x.id == id ? x.copyWith(value: value) : x, + ], + ); + final SketchSolveResult r = solveSketch(next); + changeSketch( + (_) => r.doc, + status: '驱动尺寸:${sketchDimText(d.copyWith(value: value))}' + '${r.converged ? '' : '(冲突:未完全满足)'}', + ); + } + + /// 架构图当前画笔颜色。 + int get archColor => _archColor; + + /// 设置架构图画笔颜色;若当前选中了图形,同时替换它们的颜色。 + void setArchColor(int color) { + _archColor = color; + final Set sel = _archSelIds.toSet(); + final List selShapes = [ + for (final ArchShape s in arch.shapes) + if (sel.contains(s.id)) s, + ]; + if (selShapes.isNotEmpty) { + ArchDoc next = arch; + for (final ArchShape s in selShapes) { + next = next.replaceShape(s.copyWith( + stroke: color, + fill: s.type == ArchShapeType.text ? 0 : archFillOf(color), + )); + } + _changeArch(next, status: '已更新颜色'); + return; + } + notifyListeners(); + } + + /// 架构图连线默认走线方式。 + ArchRoute get archRoute => _archRoute; + + /// 正交模式(F8)。 + bool get archOrtho => _archOrtho; + + /// 切换正交模式(移动约束到水平 / 垂直)。 + void setArchOrtho(bool v) { + if (_archOrtho == v) return; + _archOrtho = v; + _status = v ? '正交:开(移动约束水平 / 垂直)' : '正交:关'; + notifyListeners(); + } + + /// 极轴追踪(F10)。 + bool get archPolar => _archPolar; + + /// 切换极轴追踪。 + void setArchPolar(bool v) { + if (_archPolar == v) return; + _archPolar = v; + _status = v ? '极轴:开(${_archPolarDeg.round()}° 倍数吸附)' : '极轴:关'; + notifyListeners(); + } + + /// 极轴角度(度)。 + double get archPolarDeg => _archPolarDeg; + + /// 设置极轴角度(5–90°,常用 5 / 10 / 15 / 22.5 / 30 / 45 / 90)。 + void setArchPolarDeg(double deg) { + final double v = deg.clamp(1, 90).toDouble(); + if (v == _archPolarDeg) return; + _archPolarDeg = v; + _status = '极轴角度:${v == v.roundToDouble() ? v.round() : v}°'; + notifyListeners(); + } + + /// 四边标尺显示开关。 + bool get archRulers => _archRulers; + + /// 切换四边标尺。 + void setArchRulers(bool v) { + if (_archRulers == v) return; + _archRulers = v; + _status = v ? '标尺:显示' : '标尺:隐藏'; + notifyListeners(); + } + + /// 设置连线默认走线方式(直线 / 正交折线)。 + void setArchRoute(ArchRoute r) { + if (_archRoute == r) return; + _archRoute = r; + _status = r == ArchRoute.ortho ? '连线走线:正交折线' : '连线走线:直线'; + notifyListeners(); + } + + /// 架构图当前选中元素 id 列表。 + List get archSelIds => _archSelIds; + + /// 主选中元素 id(列表首项);空表示无选中。 + String? get archSelId => _archSelIds.isEmpty ? null : _archSelIds.first; + + /// 选中架构图元素(null 清空;[toggle] 为切换式多选)。 + void selectArch(String? id, {bool toggle = false}) { + final List cur = List.of(_archSelIds); + if (id == null) { + cur.clear(); + } else if (toggle) { + if (cur.contains(id)) { + cur.remove(id); + } else { + cur.add(id); + } + } else { + cur + ..clear() + ..add(id); + } + if (_sameIds(cur, _archSelIds)) return; + _archSelIds = cur; + notifyListeners(); + } + + /// 替换整个选中集合(框选 / 全选用)。 + void selectArchIds(List ids) { + if (_sameIds(ids, _archSelIds)) return; + _archSelIds = List.of(ids); + notifyListeners(); + } + + /// 全选当前文档的所有元素。 + void selectAllArch() { + selectArchIds([ + for (final ArchShape s in arch.shapes) s.id, + for (final ArchConnector c in arch.connectors) c.id, + for (final ArchStroke s in arch.strokes) s.id, + ]); + } + + /// 判断两个 id 列表是否相同。 + static bool _sameIds(List a, List b) { + if (identical(a, b)) return true; + if (a.length != b.length) return false; + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + + /// 「识别演示」触发令牌(画布监听它启动动画)。 + int get archPlayToken => _archPlayToken; + + /// 架构图文档。 + ArchDoc get arch => _project.arch; + + /// 架构图画布视口尺寸(测量值,不触发通知)。 + Size get archViewport => _archViewport; + + /// 由架构图画布回填视口尺寸(不通知监听者)。 + void setArchViewport(Size s) { + _archViewport = s; + } + + /// 修改架构图文档的公共入口。 + /// + /// [undo] 为 true 时记录撤销历史(单次编辑);批量演示动画传 false, + /// 由外层「载入示例」记录一次整体历史(一次 Ctrl+Z 即可整体还原)。 + void _changeArch(ArchDoc next, {String? status, bool undo = true}) { + if (undo) { + _mutate(_project.copyWith(arch: next), status: status); + return; + } + _project = _project.copyWith(arch: next); + _dirty = true; + if (status != null) _status = status; + notifyListeners(); + } + + /// 新增 / 覆盖一个架构图图形(未指定图层时归入当前活动图层)。 + void addArchShape(ArchShape s, {bool undo = true}) { + final ArchShape item = + s.layerId.isEmpty ? s.copyWith(layerId: arch.activeLayer) : s; + _changeArch( + arch.replaceShape(item), + status: '新增${archShapeTypeLabel(item.type)}', + undo: undo, + ); + } + + /// 新增一段手绘墨迹(未指定图层时归入当前活动图层)。 + void addArchStroke(ArchStroke s, {bool undo = true}) { + final ArchStroke item = + s.layerId.isEmpty ? s.copyWith(layerId: arch.activeLayer) : s; + _changeArch( + arch.copyWith(strokes: [...arch.strokes, item]), + status: '手绘墨迹(未识别)', + undo: undo, + ); + } + + /// 移除一段墨迹(识别演示转化完成后调用)。 + void removeArchStroke(String id, {bool undo = false}) { + _changeArch(arch.removeIds({id}), undo: undo); + } + + /// 新增一条连线(未指定图层时归入当前活动图层)。 + void addArchConnector(ArchConnector c, {bool undo = true}) { + final ArchConnector item = + c.layerId.isEmpty ? c.copyWith(layerId: arch.activeLayer) : c; + _changeArch( + arch.copyWith(connectors: [...arch.connectors, item]), + status: '新增连线', + undo: undo, + ); + } + + /// 更新图形(移动 / 缩放 / 文字 / 颜色)。 + void updateArchShape(ArchShape s, {String? status, bool undo = true}) { + _changeArch(arch.replaceShape(s), status: status ?? '更新图形', undo: undo); + } + + /// 提交一次「墨迹 → 标准图形」转化(动画完成时调用)。 + /// + /// [removeIds] 用于两笔合并 / 圆柱拼接等场景:完成时把被合并的旧元素 + /// 一并移除,且与新增图形合并为同一条撤销记录。 + void commitArchConversion( + ArchShape shape, { + Set removeIds = const {}, + bool undo = true, + }) { + final ArchShape item = + shape.layerId.isEmpty ? shape.copyWith(layerId: arch.activeLayer) : shape; + ArchDoc next = arch.replaceShape(item); + if (removeIds.isNotEmpty) { + next = next.removeIds(removeIds); + } + _changeArch( + next, + status: '识别为${archShapeTypeLabel(item.type)}', + undo: undo, + ); + } + + /// 删除当前选中的架构图元素(删除图形会连带删除其连线;支持多选)。 + void removeArchSelection() { + if (_archSelIds.isEmpty) return; + final Set ids = _archSelIds.toSet(); + _archSelIds = const []; + _changeArch(arch.removeIds(ids), status: '已删除 ${ids.length} 个对象'); + } + + /// 批量移动图形(多选拖拽;只记录一次撤销历史)。 + void moveArchShapes(Map deltas) { + if (deltas.isEmpty) return; + final List shapes = [ + for (final ArchShape s in arch.shapes) + deltas.containsKey(s.id) ? s.translated(deltas[s.id]!) : s, + ]; + _changeArch(arch.copyWith(shapes: shapes), status: '移动'); + } + + /// 以函数式方式变换架构图文档(多步编辑合并为一次撤销记录)。 + void transformArch( + ArchDoc Function(ArchDoc) fn, { + String? status, + bool undo = true, + }) { + _changeArch(fn(arch), status: status, undo: undo); + } + + /// 更新一条连线(走线方式 / 颜色 / 标签)。 + void updateArchConnector(ArchConnector c, {String? status}) { + final List next = [ + for (final ArchConnector x in arch.connectors) x.id == c.id ? c : x, + ]; + _changeArch(arch.copyWith(connectors: next), status: status ?? '更新连线'); + } + + /// 设置网格(吸附开关 / 粒度;文档设置,不记录撤销)。 + void setArchGrid({bool? snap, double? size}) { + final ArchDoc a = arch; + final bool s = snap ?? a.gridSnap; + final double g = (size ?? a.gridSize).clamp(4, 200).toDouble(); + if (s == a.gridSnap && g == a.gridSize) return; + _changeArch( + a.copyWith(gridSnap: s, gridSize: g), + status: s ? '网格吸附:开(${g.round()} px)' : '网格吸附:关', + undo: false, + ); + } + + // ===================== 架构图图层(AutoCAD 风格) ===================== + + /// 设置当前活动图层(新建图形 / 墨迹 / 连线的归属;同时切换画笔色为该图层色)。 + void setArchActiveLayer(String id) { + final ArchLayer l = arch.layerById(id); + if (arch.activeLayer == l.id) return; + _archColor = l.color; + _changeArch( + arch.copyWith(activeLayerId: l.id), + status: '活动图层:${l.name}', + undo: false, + ); + } + + /// 新建图层并设为活动图层。 + void addArchLayer() { + int n = arch.layers.length + 1; + String id = 'LY$n'; + final Set used = arch.layers.map((ArchLayer l) => l.id).toSet(); + while (used.contains(id)) { + n++; + id = 'LY$n'; + } + final int color = kArchPalette[arch.layers.length % kArchPalette.length]; + final ArchLayer l = ArchLayer(id: id, name: '图层 $n', color: color); + _archColor = color; + _changeArch( + arch.copyWith( + layers: [...arch.layers, l], + activeLayerId: id, + ), + status: '新建图层「${l.name}」', + ); + } + + /// 更新图层(名称 / 颜色 / 可见 / 锁定)。 + void updateArchLayer(ArchLayer l, {String? status}) { + final List next = [ + for (final ArchLayer x in arch.layers) x.id == l.id ? l : x, + ]; + _changeArch(arch.copyWith(layers: next), status: status ?? '图层已更新'); + } + + /// 切换图层可见性(隐藏的图层不绘制、不可选、不可吸附)。 + void toggleArchLayerVisible(String id) { + final ArchLayer l = arch.layerById(id); + updateArchLayer(l.copyWith(visible: !l.visible), + status: l.visible ? '图层「${l.name}」已隐藏' : '图层「${l.name}」已显示'); + } + + /// 切换图层锁定(锁定后可见但不可选 / 不可移动)。 + void toggleArchLayerLocked(String id) { + final ArchLayer l = arch.layerById(id); + updateArchLayer(l.copyWith(locked: !l.locked), + status: l.locked ? '图层「${l.name}」已解锁' : '图层「${l.name}」已锁定'); + } + + // ===================== 对齐 / 均布(PPT 风格) ===================== + + /// 对齐 / 均布选中的图形(以选中范围为参照;均布至少 3 个)。 + void alignArchSelection(ArchAlign mode) { + final List sel = [ + for (final String id in _archSelIds) + if (arch.shapeById(id) != null) arch.shapeById(id)!, + ]; + final bool distribute = + mode == ArchAlign.distributeH || mode == ArchAlign.distributeV; + if (sel.length < (distribute ? 3 : 2)) { + setStatus(distribute ? '均布至少需要选中 3 个图形' : '对齐至少需要选中 2 个图形'); + return; + } + // 参照范围 = 选中图形并集(线性图形按 bounds 参与)。 + Rect u = sel.first.bounds; + for (final ArchShape s in sel) { + u = u.expandToInclude(s.bounds); + } + ArchShape applyTo(ArchShape s, Rect target) { + if (s.isLinear) { + return s.translated(target.topLeft - s.bounds.topLeft); + } + return s.copyWith(rect: target); + } + + final Map next = {}; + if (!distribute) { + for (final ArchShape s in sel) { + final Rect b = s.bounds; + final Rect r = switch (mode) { + ArchAlign.left => + Rect.fromLTWH(u.left, b.top, b.width, b.height), + ArchAlign.hCenter => Rect.fromLTWH( + u.center.dx - b.width / 2, b.top, b.width, b.height), + ArchAlign.right => + Rect.fromLTWH(u.right - b.width, b.top, b.width, b.height), + ArchAlign.top => + Rect.fromLTWH(b.left, u.top, b.width, b.height), + ArchAlign.vCenter => Rect.fromLTWH( + b.left, u.center.dy - b.height / 2, b.width, b.height), + ArchAlign.bottom => + Rect.fromLTWH(b.left, u.bottom - b.height, b.width, b.height), + _ => b, + }; + next[s.id] = applyTo(s, r); + } + } else { + final bool horiz = mode == ArchAlign.distributeH; + final List sorted = List.of(sel) + ..sort((ArchShape a, ArchShape b) => horiz + ? a.bounds.center.dx.compareTo(b.bounds.center.dx) + : a.bounds.center.dy.compareTo(b.bounds.center.dy)); + final double firstC = horiz + ? sorted.first.bounds.center.dx + : sorted.first.bounds.center.dy; + final double lastC = horiz + ? sorted.last.bounds.center.dx + : sorted.last.bounds.center.dy; + final double stepC = (lastC - firstC) / (sorted.length - 1); + for (int i = 0; i < sorted.length; i++) { + final ArchShape s = sorted[i]; + final double c = firstC + stepC * i; + final Rect b = s.bounds; + final Rect r = horiz + ? Rect.fromLTWH(c - b.width / 2, b.top, b.width, b.height) + : Rect.fromLTWH(b.left, c - b.height / 2, b.width, b.height); + next[s.id] = applyTo(s, r); + } + } + final String label = switch (mode) { + ArchAlign.left => '左对齐', + ArchAlign.hCenter => '横向居中', + ArchAlign.right => '右对齐', + ArchAlign.top => '顶对齐', + ArchAlign.vCenter => '纵向居中', + ArchAlign.bottom => '底对齐', + ArchAlign.distributeH => '横向均布', + ArchAlign.distributeV => '纵向均布', + }; + _changeArch( + arch.copyWith(shapes: [ + for (final ArchShape s in arch.shapes) next[s.id] ?? s, + ]), + status: '$label(${sel.length} 个图形)', + ); + } + + /// 删除图层(该图层对象移入第一个图层;仅剩一个图层时不允许删除)。 + void removeArchLayer(String id) { if (arch.layers.length <= 1) { + setStatus('至少保留一个图层,无法删除'); + return; + } + final List next = + arch.layers.where((ArchLayer l) => l.id != id).toList(); + final String fallback = next.first.id; + final List shapes = [ + for (final ArchShape s in arch.shapes) + s.layerId == id ? s.copyWith(layerId: fallback) : s, + ]; + final List strokes = [ + for (final ArchStroke s in arch.strokes) + s.layerId == id ? s.copyWith(layerId: fallback) : s, + ]; + final List conns = [ + for (final ArchConnector c in arch.connectors) + c.layerId == id ? c.copyWith(layerId: fallback) : c, + ]; + _changeArch( + arch.copyWith( + layers: next, + shapes: shapes, + strokes: strokes, + connectors: conns, + activeLayerId: arch.activeLayer == id ? fallback : arch.activeLayerId, + ), + status: '已删除图层(对象移入首个图层)', + ); + } + + /// 调整图形层级([delta] > 0 上移一层)。 + void moveArchZ(ArchShape s, int delta) { + final List list = List.of(arch.shapes); + final int i = list.indexWhere((ArchShape x) => x.id == s.id); + if (i < 0) return; + final int j = (i + delta).clamp(0, list.length - 1); + if (i == j) return; + final ArchShape x = list.removeAt(i); + list.insert(j, x); + _changeArch(arch.copyWith(shapes: list), status: '调整层级'); + } + + /// 载入示例场景(手绘稿 / 完成图),并适配视图。 + void archLoadDemo(ArchDemoKind kind) { + final bool ink = kind == ArchDemoKind.ink; + _archSelIds = const []; + _changeArch( + ink ? archDemoInkScene() : archDemoDoneScene(), + status: ink ? '已载入示例:手绘稿(点「识别演示」逐笔识别)' : '已载入示例:完成图', + ); + archFit(); + } + + /// 载入手绘稿并触发「识别演示」(逐笔播放转化动画)。 + void archPlayDemo() { + _archSelIds = const []; + _archPlayToken++; + _changeArch(archDemoInkScene(), status: '识别演示:逐笔识别中…'); + archFit(); + } + + /// 清空架构图。 + void archClear() { + _archSelIds = const []; + _changeArch(ArchDoc.empty, status: '已清空架构图'); + _archSetViewDirect(zoom: 1, panX: 0, panY: 0); + } + + /// 写入架构图视口(视图操作:不置脏、不记录历史)。 + void archSetView({double? zoom, double? panX, double? panY}) { + _archSetViewDirect(zoom: zoom, panX: panX, panY: panY); + } + + /// 视口写入实现。 + void _archSetViewDirect({double? zoom, double? panX, double? panY}) { + final ArchDoc a = _project.arch; + _project = _project.copyWith( + arch: a.copyWith( + zoom: (zoom ?? a.zoom).clamp(0.15, 4.0).toDouble(), + panX: panX ?? a.panX, + panY: panY ?? a.panY, + ), + ); + notifyListeners(); + } + + /// 以 [focal](屏幕坐标)为锚点缩放架构图。 + void archZoomAt(double factor, Offset focal) { + final ArchDoc a = _project.arch; + final double nz = (a.zoom * factor).clamp(0.15, 4.0).toDouble(); + if ((nz - a.zoom).abs() < 0.0001) return; + final double k = nz / a.zoom; + _archSetViewDirect( + zoom: nz, + panX: focal.dx - (focal.dx - a.panX) * k, + panY: focal.dy - (focal.dy - a.panY) * k, + ); + } + + /// 缩放架构图(工具栏 ± 按钮,以视口中心为锚点)。 + void archZoomBy(double factor) { + final Size vp = _archViewport; + final Offset focal = + vp.isEmpty ? const Offset(400, 300) : Offset(vp.width / 2, vp.height / 2); + archZoomAt(factor, focal); + } + + /// 架构图「适应窗口」:按内容范围适配缩放并居中。 + void archFit() { + final Size vp = _archViewport; + final Rect b = _project.arch.contentBounds(); + final double bw = math.max(b.width, 80); + final double bh = math.max(b.height, 80); + if (vp.width <= 10 || vp.height <= 10) { + _archSetViewDirect(zoom: 1, panX: 0, panY: 0); + return; + } + final double z = math + .min(vp.width / (bw + 80), vp.height / (bh + 80)) + .clamp(0.15, 2.5) + .toDouble(); + _archSetViewDirect( + zoom: z, + panX: vp.width / 2 - b.center.dx * z, + panY: vp.height / 2 - b.center.dy * z, + ); + } + /// 新建项目:清空历史,构造一个含两个工位、两个动作(动作 1 / 动作 2)的初始项目。 /// /// 副作用:重置文件路径、置脏、更新状态并重算关键路径。 @@ -305,7 +1515,7 @@ class AppController extends ChangeNotifier { _undo.clear(); _redo.clear(); _project = Project( - name: '未命名节拍', + name: '未命名设计', cycle: const Cycle(durationMs: 2400), stations: const [ Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0), @@ -385,6 +1595,72 @@ class AppController extends ChangeNotifier { /// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。 static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last; + /// 保存架构图文档到 [path](`*.arch.json`;桌面同步 `.bak` 备份)。 + Future saveArchAs(String path) async { + final String json = _project.arch.encode(); + await Storage.instance.backupExisting(path); + final File target = File(path); + if (!await target.parent.exists()) { + await target.parent.create(recursive: true); + } + await target.writeAsString(json, flush: true); + _archFilePath = path; + _dirty = false; + _lastSavedAt = DateTime.now(); + _status = '已保存 ${_baseName(path)}(含 .bak 备份)'; + await Storage.instance.writeAutosave(_project, projectPath: _archFilePath, clean: true); + notifyListeners(); + } + + /// 通过外部通道(安卓公共 Documents)保存架构图成功后标记为已保存。 + Future markArchSaved(String displayPath) async { + _archFilePath = displayPath; + _dirty = false; + _lastSavedAt = DateTime.now(); + _status = '已保存 ${_baseName(displayPath)}'; + await Storage.instance.writeAutosave(_project, projectPath: null, clean: true); + notifyListeners(); + } + + /// 载入架构图文档(`*.arch.json`):只替换架构图部分,时序图保持不变。 + void loadArchDoc(ArchDoc doc, {String? path, bool dirty = false}) { + _undo.clear(); + _redo.clear(); + _archSelIds = const []; + _project = _project.copyWith(arch: doc); + _archFilePath = path; + _dirty = dirty; + _status = path == null ? '已载入架构图' : '已打开 ${_baseName(path)}'; + notifyListeners(); + } + + /// 新建架构图文档(空画布 + 默认图层)。 + void newArchProject() { + _undo.clear(); + _redo.clear(); + _archSelIds = const []; + _project = _project.copyWith(arch: ArchDoc.empty); + _archFilePath = null; + _dirty = true; + _status = '新建架构图'; + // 默认图纸 A0(1189×841 mm):按视口适配缩放并居中;视口未知时用稳妥默认值。 + final Size vp = _archViewport; + if (vp.width > 10 && vp.height > 10) { + final double z = math + .min((vp.width - 90) / kArchPageSize.width, + (vp.height - 90) / kArchPageSize.height) + .clamp(0.15, 4.0) + .toDouble(); + _archSetViewDirect( + zoom: z, + panX: (vp.width - kArchPageSize.width * z) / 2, + panY: (vp.height - kArchPageSize.height * z) / 2, + ); + } else { + _archSetViewDirect(zoom: 0.62, panX: 40, panY: 40); + } + } + /// 切换视图模式(条形 / 圆周 / 流程图)并更新状态栏文本。 /// /// 三种视图共用同一套缩放 / 平移状态,切换后自动适配一次视图 diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart index 7075e5b..082377b 100644 --- a/lib/ui/app_shell.dart +++ b/lib/ui/app_shell.dart @@ -15,6 +15,13 @@ 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'; @@ -27,10 +34,13 @@ import '../theme/tokens.dart'; import '../update/update_service.dart'; import '../version.dart'; import 'ai_dialog.dart'; -import 'app_logo.dart'; +import 'arch_panel.dart'; +import 'arch_view.dart'; +import 'brand_menu.dart'; import 'canvas_overlays.dart'; import 'canvas_view.dart'; import 'dialogs.dart'; +import 'home_view.dart'; import 'update_dialog.dart'; import 'update_icon.dart'; @@ -148,35 +158,112 @@ class _AppShellState extends State { // ===================== 文件与导出流程 ===================== - /// 新建项目:若当前有未保存修改,先弹窗确认是否放弃。 - Future _newProject() async { - if (c.dirty) { - final bool? ok = await showDialog( + /// 当前有未保存修改时弹窗确认是否放弃;返回 true 表示可以继续。 + Future _confirmDiscardIfDirty() async { + if (!c.dirty) return true; + final bool? ok = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('放弃未保存的修改?'), + content: const Text('当前项目有未保存的修改,继续将丢失这些修改。'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), + FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('继续')), + ], + ), + ); + return ok == true; + } + + /// 记录「最近打开」(异步写盘,失败静默)。 + void _rememberRecent(String path, String moduleId) { + RecentStore.remember(path: path, moduleId: moduleId); + } + + /// 从首页 / 品牌菜单进入某模块并**新建**该类型文档(未保存修改先确认)。 + Future _startModule(EdcModule m) async { + if (!m.available) return; + if (moduleOf(c.appMode)?.id == m.id) return; // 已在该模块 + if (!await _confirmDiscardIfDirty()) return; + switch (m.id) { + case 'sequence': + c.newProject(); + c.setAppMode(AppMode.sequence); + case 'architecture': + c.newArchProject(); + c.setAppMode(AppMode.architecture); + default: + c.setStatus('${m.name}:文档类型尚未开放'); + } + } + + /// 返回首页(未保存修改先确认)。 + Future _goHome() async { + if (c.appMode == AppMode.home) return; + if (!await _confirmDiscardIfDirty()) return; + c.goHome(); + } + + /// 品牌菜单命令路由(`_home` / `_settings` / 模块 id)。 + Future _handleBrandCommand(String cmd) async { + if (!mounted) return; + if (cmd == '_home') { + await _goHome(); + return; + } + if (cmd == '_settings') { + await showDialog( context: context, - builder: (BuildContext ctx) => AlertDialog( - title: const Text('放弃未保存的修改?'), - content: const Text('当前项目有未保存的修改,继续将丢失这些修改。'), - actions: [ - TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), - FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('继续')), - ], - ), + builder: (_) => SoftwareSettingsDialog(controller: c), ); - if (ok != true) return; + return; + } + final EdcModule? m = moduleById(cmd); + if (m != null) await _startModule(m); + } + + /// 新建项目:当前模块内新建(未保存修改先确认)。 + Future _newProject() async { + if (!await _confirmDiscardIfDirty()) return; + // 架构图模块:新建独立的架构图文档(空画布 + 默认图层)。 + if (c.appMode == AppMode.architecture) { + c.newArchProject(); + return; } c.newProject(); } - /// 打开项目:选择 .seq.json 文件并解码加载。 + /// 打开文档(工具栏 / Ctrl+O):模块内直接打开;首页时先选择文档类型。 Future _open() async { - // 安卓版:从公共 Documents/SequenceDiagram 打开。 + final EdcModule? m = moduleOf(c.appMode); + if (m == null) { + await _openDocumentChooser(); + return; + } + await _openDocumentOfModule(m); + } + + /// 「打开文档…」:先选文档类型,再走对应类型的打开流程。 + Future _openDocumentChooser() async { + final EdcModule? m = await showDocumentTypeDialog(context); + if (m == null) return; + await _openDocumentOfModule(m); + } + + /// 打开某模块的文档:时序图 → `*.seq.json`;架构图 → `*.arch.json`。 + Future _openDocumentOfModule(EdcModule m) async { + if (!await _confirmDiscardIfDirty()) return; + if (!mounted) return; + final bool arch = m.id == 'architecture'; + final String suffix = m.suffix; + // 安卓版:从公共目录打开(兼容旧目录)。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, - builder: (_) => const AndroidFileDialog( + builder: (_) => AndroidFileDialog( saveMode: false, defaultName: '', - suffix: '.seq.json', + suffix: suffix, ), ); if (name == null) return; @@ -186,50 +273,122 @@ class _AppShellState extends State { if (mounted) await showMessage(context, '打开失败', '未找到文件 $name'); return; } - c.loadProject(Project.decode(utf8.decode(bytes)), path: null); + final String content = utf8.decode(bytes); + if (arch) { + c.setAppMode(AppMode.architecture); + c.loadArchDoc(ArchDoc.decode(content), path: null); + } else { + c.setAppMode(AppMode.sequence); + c.loadProject(Project.decode(content), path: null); + } c.setStatus('已打开 ${AndroidDocs.location()}/$name'); } catch (e) { if (mounted) await showMessage(context, '打开失败', '$e'); } return; } - final String? path = await pickFile(context, save: false, initialPath: c.filePath); + final String? path = await pickFile( + context, + save: false, + initialPath: c.currentFilePath, + suffix: suffix, + ); if (path == null) return; try { - final String src = await File(path).readAsString(); - c.loadProject(Project.decode(src), path: path); + await _openDocumentAt(m, path); } catch (e) { - if (mounted) await showMessage(context, '打开失败', '$e'); + if (mounted) await showMessage(context, '打开失败', '不是有效的${m.name}文档:$e'); } } - /// 保存项目:已有路径则直接保存,否则转入“另存为”。 + /// 直接打开给定路径的文档(最近打开 / 文件选择共用;桌面与安卓一致)。 + Future _openDocumentAt(EdcModule m, String path) async { + String src; + if (AndroidDocs.isAvailable) { + final String name = path.split(RegExp(r'[\\/]')).last; + final Uint8List? bytes = await AndroidDocs.readFile(name); + if (bytes == null) throw Exception('未找到文件 $name'); + src = utf8.decode(bytes); + } else { + src = await File(path).readAsString(); + } + if (m.id == 'architecture') { + c.setAppMode(AppMode.architecture); + c.loadArchDoc(ArchDoc.decode(src), path: AndroidDocs.isAvailable ? null : path); + } else { + c.setAppMode(AppMode.sequence); + c.loadProject(Project.decode(src), path: AndroidDocs.isAvailable ? null : path); + } + _rememberRecent(path, m.id); + } + + /// 打开最近文件(失败时移除失效条目并提示)。 + Future _openRecent(EdcModule m, RecentDoc doc) async { + if (!await _confirmDiscardIfDirty()) return; + try { + await _openDocumentAt(m, doc.path); + } catch (e) { + await RecentStore.remove(doc.path); + if (mounted) { + await showMessage(context, '打开失败', '文件可能已被移动或删除:\n$e'); + } + } + } + + /// 保存:已有路径则直接保存,否则转入“另存为”。 + /// + /// 时序图与架构图分别保存为 `*.seq.json` 与 `*.arch.json` 两个独立文件 + /// (内容互不包含;时序图中不含架构数据)。 Future _save() async { // 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。 - if (AndroidDocs.isAvailable || c.filePath == null) { + if (AndroidDocs.isAvailable || c.currentFilePath == null) { await _saveAs(); return; } - await c.save(); + 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'); + } } - /// 另存为:选择目标路径后写入文件(同时生成 .bak 备份)。 + /// 另存为:按当前模块选择目标路径(`*.seq.json` / `*.arch.json`),写入并生成 `.bak` 备份。 Future _saveAs() async { - // 安卓版:写入公共 Documents/SequenceDiagram(MediaStore 通道)。 + final bool arch = c.appMode == AppMode.architecture; + final String suffix = arch ? '.arch.json' : '.seq.json'; + // 安卓版:写入公共 Documents(MediaStore 通道)。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, builder: (_) => AndroidFileDialog( saveMode: true, - defaultName: '${c.project.name}.seq.json', - suffix: '.seq.json', + defaultName: '${c.project.name}$suffix', + suffix: suffix, ), ); if (name == null) return; try { - final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode())); - await AndroidDocs.saveFile(name, data, mime: 'application/json'); - await c.markSaved('${AndroidDocs.location()}/$name'); + if (arch) { + await AndroidDocs.saveFile( + name, Uint8List.fromList(utf8.encode(c.arch.encode())), + mime: 'application/json'); + await c.markArchSaved('${AndroidDocs.location()}/$name'); + _rememberRecent('${AndroidDocs.location()}/$name', 'architecture'); + } else { + final Uint8List data = Uint8List.fromList( + utf8.encode(c.project.encode(includeArch: false))); + await AndroidDocs.saveFile(name, data, mime: 'application/json'); + await c.markSaved('${AndroidDocs.location()}/$name'); + _rememberRecent('${AndroidDocs.location()}/$name', 'sequence'); + } } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } @@ -238,14 +397,22 @@ class _AppShellState extends State { final String? path = await pickFile( context, save: true, - initialPath: c.filePath, - defaultName: c.filePath == null ? '${c.project.name}.seq.json' : null, - suffix: '.seq.json', + initialPath: c.currentFilePath, + defaultName: c.currentFilePath == null ? '${c.project.name}$suffix' : null, + suffix: suffix, ); if (path == null) return; try { - await c.saveAs(path); - if (mounted) c.setStatus('已保存 ${path.split(RegExp(r'[\\/]')).last}(含 .bak 备份)'); + if (arch) { + await c.saveArchAs(path); + _rememberRecent(path, 'architecture'); + } else { + await c.saveAs(path); + _rememberRecent(path, 'sequence'); + if (mounted) { + c.setStatus('已保存 ${path.split(RegExp(r'[\\/]')).last}(含 .bak 备份)'); + } + } } catch (e) { if (mounted) await showMessage(context, '保存失败', '$e'); } @@ -259,7 +426,7 @@ class _AppShellState extends State { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); return; } - // 安卓版:写入公共 Documents/SequenceDiagram。 + // 安卓版:写入公共 Documents/EDC。 if (AndroidDocs.isAvailable) { final String? name = await showDialog( context: context, @@ -358,6 +525,145 @@ class _AppShellState extends State { } } + /// 导出架构图 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。 /// /// 条形 / 圆周视图调用时给出明确提示(不做静默失败)。 @@ -409,13 +715,35 @@ class _AppShellState extends State { // ===================== 主界面构建 ===================== + /// 首页(空白启动工作台):新建文档网格 / 打开 / 最近打开。 + Widget _buildHome(Tokens t) { + return Scaffold( + backgroundColor: t.bg, + body: HomeView( + controller: c, + onNewModule: _startModule, + onOpenDocument: _openDocumentChooser, + onOpenRecent: _openRecent, + onOpenSettings: () => _handleBrandCommand('_settings'), + onOpenHelp: () => + showDialog(context: context, builder: (_) => const HelpDialog()), + ), + ); + } + /// 构建主界面:绑定全局快捷键,按“工具栏 / 中部(侧栏 + 画布) / 状态栏” /// 三段式纵向布局组织界面。 @override Widget build(BuildContext context) { final Tokens t = context.tok; + // 首页(空白启动工作台):不渲染工作区工具栏 / 画布 / 状态栏。 + if (c.appMode == AppMode.home) { + return _buildHome(t); + } + // 顶层模块:架构图模式下画布、工具栏与侧栏切换为架构图工具。 + final bool arch = c.appMode == AppMode.architecture; // 流程图视图只读:撤销 / 重做 / 删除等编辑操作统一停用(与置灰按钮一致)。 - final bool flow = c.project.viewState.mode == ViewMode.flow; + final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; // 全局快捷键绑定:编辑、文件、帮助、主题等。 return CallbackShortcuts( bindings: { @@ -428,14 +756,39 @@ class _AppShellState extends State { 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 (!flow && c.selectedId != null) c.deleteAction(c.selectedId!); + if (c.appMode == AppMode.architecture) { + if (c.sketchMode) { + c.deleteSketchSelection(); + } else { + c.removeArchSelection(); + } + } else if (!flow && c.selectedId != null) { + c.deleteAction(c.selectedId!); + } }, const SingleActivator(LogicalKeyboardKey.f1): () => showDialog(context: context, builder: (_) => const HelpDialog()), const SingleActivator(LogicalKeyboardKey.f2): () => showDialog(context: context, builder: (_) => SettingsDialog(controller: c)), const SingleActivator(LogicalKeyboardKey.f3): c.toggleTheme, + const SingleActivator(LogicalKeyboardKey.escape): () { + // 草图命令进行中:Esc 取消命令(其余场景 Esc 不拦截)。 + if (c.appMode == AppMode.architecture && + c.sketchMode && + (c.sketchPendingCons != null || c.sketchPendingDim != null)) { + c.cancelSketchCommand(); + } + }, }, child: Focus( autofocus: true, @@ -461,18 +814,28 @@ class _AppShellState extends State { // 画布舞台:可绘制区域,叠加画布视图与浮层。 child: Stack( children: [ - // 底层:可交互的画布。 - Positioned.fill( - child: Container(color: t.canvas2, child: CanvasView(controller: c)), - ), - // 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。 - Positioned.fill( - child: CanvasOverlays( - controller: c, - leftInset: _leftRail ? 22 : 0, - rightInset: _rightRail ? 22 : 0, + if (arch) + // 架构图:独立画布(手绘识别 / 连线 / 属性编辑)。 + Positioned.fill( + child: Container( + color: t.canvas2, + child: ArchView(controller: c), + ), + ) + else ...[ + // 底层:可交互的画布。 + Positioned.fill( + child: Container(color: t.canvas2, child: CanvasView(controller: c)), ), - ), + // 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。 + Positioned.fill( + child: CanvasOverlays( + controller: c, + leftInset: _leftRail ? 22 : 0, + rightInset: _rightRail ? 22 : 0, + ), + ), + ], // 收起状态:贴边轨道(悬停可展开为悬浮面板)。 if (_leftRail) Positioned(left: 0, top: 0, bottom: 0, child: _rail(t, true)), @@ -576,7 +939,8 @@ class _AppShellState extends State { /// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。 Widget _toolbar(Tokens t) { final double s = _toolScale; - final bool flow = c.project.viewState.mode == ViewMode.flow; + final bool arch = c.appMode == AppMode.architecture; + final bool flow = !arch && c.project.viewState.mode == ViewMode.flow; return Container( height: 54 * s, padding: EdgeInsets.symmetric(horizontal: 6 * s), @@ -618,22 +982,8 @@ class _AppShellState extends State { if (!compact) { // 完整布局:文件 / 编辑操作图标化 + 分段视图切换。 left = [ - AppLogo(size: 32 * s), - SizedBox(width: 10 * s), - Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('时序图', - style: TextStyle( - color: t.text, - fontSize: _toolFont(14), - fontWeight: FontWeight.w700, - letterSpacing: 1 * s)), - Text('Sequence Diagram Studio', style: TextStyle(color: t.dim, fontSize: _toolFont(10))), - ], - ), - SizedBox(width: 18 * s), + 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'), @@ -644,20 +994,20 @@ class _AppShellState extends State { _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 6 * s), - _aiBtn(t), - SizedBox(width: 12 * s), - _segmented(t), + if (!arch) _aiBtn(t), + if (!arch) SizedBox(width: 12 * s), + if (arch) _archTools(t, false) else _segmented(t), ]; right = [ - // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。 + // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 _exportMenu(t), SizedBox(width: 6 * s), _zoomBox(t), SizedBox(width: 6 * s), - _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), - SizedBox(width: 8 * s), - _unitDropdown(t), - SizedBox(width: 8 * 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, () => @@ -668,15 +1018,8 @@ class _AppShellState extends State { } else { // 紧凑布局:图标化 + 导出合并为菜单,尽量压缩宽度。 left = [ - AppLogo(size: 28 * s), - SizedBox(width: 8 * s), - Text('时序图', - style: TextStyle( - color: t.text, - fontSize: _toolFont(13), - fontWeight: FontWeight.w700, - letterSpacing: 0.5 * s)), - SizedBox(width: 8 * s), + 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'), @@ -688,17 +1031,17 @@ class _AppShellState extends State { tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 4 * s), // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 - _aiBtn(t), - SizedBox(width: 8 * s), - _segmented(t, compact: true), + if (!arch) _aiBtn(t), + if (!arch) SizedBox(width: 8 * s), + if (arch) _archTools(t, true) else _segmented(t, compact: true), ]; right = [ - // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。 + // 导出合并为下拉菜单:时序三视图 / 架构图各自可用;drawio 仅流程图提供。 _exportMenu(t), SizedBox(width: 4 * s), _zoomBox(t), - _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), - _unitDropdown(t), + _iconBtn(t, Icons.crop_free, arch ? c.archFit : c.fitView, tooltip: '适应视图'), + if (!arch) _unitDropdown(t), sideToggleLeft, sideToggleRight, _iconBtn(t, Icons.help_outline, () => @@ -769,9 +1112,115 @@ class _AppShellState extends State { ); } - /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮。 + /// 架构图工具分段控件:选择 / 手绘 / 连线(草图模式显示草图状态条)。 + 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, '按住拖动绘制,松手自动识别为标准图形'), + seg('连线', Icons.arrow_right_alt, ArchTool.connect, '从图形拖到另一个图形'), + ], + ), + ), + ], + ); + } + + /// 缩放控件:显示当前百分比并提供缩小 / 放大按钮(时序图 / 架构图通用)。 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), @@ -782,13 +1231,13 @@ class _AppShellState extends State { ), child: Row( children: [ - _miniIcon(t, Icons.remove, () => c.zoomBy(0.9)), + _miniIcon(t, Icons.remove, () => arch ? c.archZoomBy(0.9) : c.zoomBy(0.9)), SizedBox( width: 52 * s, - child: Text('${(c.project.viewState.zoom * 100).round()}%', + child: Text(pct, textAlign: TextAlign.center, style: TextStyle(color: t.text, fontSize: _toolFont(11))), ), - _miniIcon(t, Icons.add, () => c.zoomBy(1.1)), + _miniIcon(t, Icons.add, () => arch ? c.archZoomBy(1.1) : c.zoomBy(1.1)), ], ), ); @@ -886,25 +1335,51 @@ class _AppShellState extends State { /// - 未授权时各项置灰(桌面无 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: '导出(SVG / PNG${flow ? ' / drawio' : ''})', + tooltip: arch + ? '导出(SVG / PNG / DXF)· 架构图' + : '导出(SVG / PNG${flow ? ' / drawio' : ''})', color: t.panel2, position: PopupMenuPosition.under, onSelected: (String v) { - if (v == 'svg') _exportSvg(); - if (v == 'png') _exportPng(); + 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', '矢量图:无损缩放 / 打印 / 二次编辑', licensed), + _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 (flow) + if (!arch && flow) _exportItem(t, 'drawio', Icons.account_tree_outlined, '导出 drawio', 'diagrams.net 可编辑工程', licensed), ], @@ -1159,9 +1634,78 @@ class _AppShellState extends State { // ===================== 左侧栏内容 ===================== + /// 架构图左侧栏容器(手绘识别 / 图形库 / 颜色 / 示例场景)。 + Widget _archLeftPanel(Tokens t, {bool floating = false}) { + return Container( + width: _leftPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))] + : null, + ), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _sectionLabel(t, '架构图 · 设计工具'), + const Spacer(), + _panelControls(t, true), + ], + ), + const SizedBox(height: 10), + ArchLeftBody(controller: c), + ], + ), + ), + ); + } + + /// 架构图右侧栏容器(选中对象属性)。 + Widget _archRightPanel(Tokens t, {bool floating = false}) { + return Container( + width: _rightPanelWidth, + decoration: BoxDecoration( + color: t.panel, + border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)), + boxShadow: floating + ? [BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))] + : null, + ), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 10, 0), + child: Row( + children: [ + _sectionLabel(t, '属性 · 架构图'), + const Spacer(), + _panelControls(t, false), + ], + ), + ), + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 16), + child: ArchRightBody(controller: c), + ), + ), + ], + ), + ); + } + /// 构建左侧栏:项目概览、动作/工位列表、视图模式、显示选项、 /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 Widget _leftPanel(Tokens t, {bool floating = false}) { + // 架构图模块使用独立的左侧栏(图形库 / 识别开关 / 示例)。 + if (c.appMode == AppMode.architecture) { + return _archLeftPanel(t, floating: floating); + } final bool bar = c.project.viewState.mode == ViewMode.bar; final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( @@ -1827,6 +2371,10 @@ class _AppShellState extends State { /// 构建右侧栏:选中动作的属性、角度编辑、工艺单位、编辑操作、 /// 依赖关系与导出入口。[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; @@ -2230,6 +2778,8 @@ class _AppShellState extends State { /// 底部状态栏:横向滚动展示循环周期、动作/依赖数、单位换算与 /// 当前状态消息,右侧提示未保存状态与常用快捷键。 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; @@ -2279,4 +2829,67 @@ class _AppShellState extends State { ), ); } + + /// 架构图状态栏:元素统计 / 当前工具 / 缩放 / 状态消息。 + Widget _archStatusBar(Tokens t) { + final ArchDoc doc = c.arch; + final String toolLabel = c.sketchMode + ? '草图·${sketchToolLabel(c.sketchTool)}' + : switch (c.archTool) { + ArchTool.select => '选择', + ArchTool.pen => '手绘识别', + ArchTool.connect => '连线', + }; + 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/arch_panel.dart b/lib/ui/arch_panel.dart new file mode 100644 index 0000000..9fe885c --- /dev/null +++ b/lib/ui/arch_panel.dart @@ -0,0 +1,1586 @@ +/// 架构图模块侧栏内容: +/// - 左侧(工具):手绘识别、绘图辅助(F8 / F10)、网格吸附与粒度、 +/// 参数化草图、连线走线方式、图形库、颜色、示例场景、操作提示; +/// - 右侧(属性):选中对象(支持多选)信息与操作。 +/// +/// 外层容器(宽度 / 边框 / 标题栏)由 `app_shell.dart` 负责,本文件只提供主体。 +library; + +import 'dart:convert'; +import 'dart:io' show File; +import 'dart:math' as math; +import 'dart:typed_data'; +import 'dart:ui' show PathMetric, Tangent; + +import 'package:flutter/material.dart'; + +import '../arch/arch_models.dart'; +import '../arch/arch_painter.dart'; +import '../arch/arch_samples.dart'; +import '../library/symbol_library.dart'; +import '../persistence/android_docs.dart'; +import '../sketch/sketch_models.dart'; +import '../sketch/sketch_solver.dart'; +import '../state/app_controller.dart'; +import '../theme/tokens.dart'; +import 'dialogs.dart'; + +/// 尺寸改值对话框(识别后图形 / 曲线 / 图元;右栏与画布标签共用逻辑)。 +Future _editShapeDim( + BuildContext context, + AppController c, + ArchShape s, + ArchDimKind k, +) async { + final double cur = archShapeDimValue(s, k); + final String? input = await showTextEditDialog( + context, + title: '编辑${archDimKindLabel(k)}(当前 ${cur.toStringAsFixed(1)} mm)', + initial: cur.toStringAsFixed(1), + ); + if (input == null) return; + final double? v = double.tryParse(input.trim()); + if (v == null || v <= 0) { + c.setStatus('数值无效:请输入正数'); + return; + } + c.setArchShapeDim(s.id, k, v); +} + +/// 图元预览画笔(100×100 归一化盒 → 控件尺寸;跳过文字保证小尺寸清晰)。 +class _SymPreviewPainter extends CustomPainter { + /// 构造。 + _SymPreviewPainter(this.symbol, this.color); + + final LibSymbol symbol; + final Color color; + + /// 绘制。 + @override + void paint(Canvas canvas, Size size) { + if (size.width <= 0 || size.height <= 0) return; + canvas.save(); + canvas.scale(size.width / 100, size.height / 100); + const Rect box = Rect.fromLTWH(0, 0, 100, 100); + final Paint stroke = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 100 / size.width * 0.9 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = color; + for (final SymPrim p in symbol.prims) { + if (p.kind == SymPrimKind.text) continue; + final Path? path = symPrimPath(p, box); + if (path == null) continue; + canvas.drawPath(path, stroke); + } + canvas.restore(); + } + + /// 是否需要重绘。 + @override + bool shouldRepaint(covariant _SymPreviewPainter old) => + old.symbol.id != symbol.id || old.color != color; +} + +/// 小节标题。 +Widget _sec(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, + ), + ); + +/// 架构图左侧栏主体。 +class ArchLeftBody extends StatelessWidget { + /// 构造左侧栏主体。 + const ArchLeftBody({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 构建:手绘模式 → 网格 → 连线 → 图形库 → 颜色 → 示例 → 提示。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final AppController c = controller; + final ArchDoc doc = c.arch; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sec(t, '手绘识别'), + const SizedBox(height: 8), + Text( + '松手自动把笔迹扶正为标准图形(矩形 / 圆 / 箭头 / 折线 / 曲线):' + '支持两笔组合(如两笔试画一个矩形)与圆柱(顶盖 + 柱体);' + '识别不了的笔迹会保留为墨迹。文字请双击图形 / 空白处直接输入。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5), + ), + const SizedBox(height: 14), + _sec(t, '绘图辅助(F8 / F10)'), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.fromLTRB(10, 6, 6, 8), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.straighten, size: 15, color: t.accent), + const SizedBox(width: 6), + Expanded( + child: Text('正交移动(F8)', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w600, + )), + ), + Switch( + value: c.archOrtho, + onChanged: c.setArchOrtho, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + Row( + children: [ + Icon(Icons.polyline_outlined, size: 15, color: t.accent), + const SizedBox(width: 6), + Expanded( + child: Text('极轴追踪(F10)', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w600, + )), + ), + Switch( + value: c.archPolar, + onChanged: c.setArchPolar, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + if (c.archPolar) + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Wrap( + spacing: 6, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text('极轴角度', style: TextStyle(color: t.sub, fontSize: 10.5)), + for (final double a in [5, 10, 15, 22.5, 30, 45]) + _chip( + t, + '${a == a.roundToDouble() ? a.round() : a}°', + c.archPolarDeg == a, + () => c.setArchPolarDeg(a), + ), + ], + ), + ), + Row( + children: [ + Icon(Icons.square_foot, size: 15, color: t.dim), + const SizedBox(width: 6), + Expanded( + child: Text('四边标尺', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w600, + )), + ), + Switch( + value: c.archRulers, + onChanged: c.setArchRulers, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + Text('正交:移动只走水平 / 垂直;极轴:移动方向吸附到角度倍数;' + '标尺上的滑动虚线指示鼠标位置。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5)), + ], + ), + ), + const SizedBox(height: 14), + _sec(t, '网格'), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.fromLTRB(10, 6, 6, 8), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.grid_4x4, size: 15, color: t.accent), + const SizedBox(width: 6), + Expanded( + child: Text('吸附网格', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w600, + )), + ), + Switch( + value: doc.gridSnap, + onChanged: (bool v) => c.setArchGrid(snap: v), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + Row( + children: [ + Text('粒度', + style: TextStyle(color: t.sub, fontSize: 10.5)), + const SizedBox(width: 8), + for (final double g in [10, 20, 40, 80]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: _chip( + t, + '${g.round()}', + doc.gridSize == g, + () => c.setArchGrid(size: g), + ), + ), + ], + ), + Text('识别、移动与缩放时会优先对位到网格。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5)), + ], + ), + ), + const SizedBox(height: 14), + _sec(t, '连线'), + const SizedBox(height: 6), + Text('按住左键画出路径 → 松手自动识别为直线 / 折线(近轴段扶正);' + '端点自动吸附图元边框;选中后可拖动折点继续编辑。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5)), + const SizedBox(height: 14), + _sec(t, '图形库'), + const SizedBox(height: 8), + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + _libBtn(t, Icons.crop_square, '矩形', ArchShapeType.rect), + _libBtn(t, Icons.rounded_corner, '圆角矩形', ArchShapeType.roundRect), + _libBtn(t, Icons.panorama_fish_eye, '椭圆', ArchShapeType.ellipse), + _libBtn(t, Icons.circle_outlined, '圆形', ArchShapeType.circle), + _libBtn(t, Icons.change_history, '三角形', ArchShapeType.triangle), + _libBtn(t, Icons.diamond_outlined, '菱形', ArchShapeType.diamond), + _libBtn(t, Icons.hexagon_outlined, '六边形', ArchShapeType.hexagon), + _libBtn(t, Icons.storage, '圆柱', ArchShapeType.cylinder), + _libBtn(t, Icons.cloud_outlined, '云', ArchShapeType.cloud), + _libBtn(t, Icons.text_fields, '文本', ArchShapeType.text), + ], + ), + const SizedBox(height: 10), + Text('IT / 系统设计', + style: TextStyle(color: t.dim, fontSize: 10)), + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + _libBtn(t, Icons.dns_outlined, '服务器', ArchShapeType.server), + _libBtn(t, Icons.desktop_windows_outlined, '客户端', + ArchShapeType.client), + _libBtn(t, Icons.smartphone, '移动端', ArchShapeType.mobile), + _libBtn(t, Icons.security, '防火墙', ArchShapeType.firewall), + _libBtn(t, Icons.lan_outlined, '交换机', ArchShapeType.netSwitch), + _libBtn(t, Icons.view_stream_outlined, '消息队列', + ArchShapeType.queue), + ], + ), + const SizedBox(height: 10), + _SymbolLibPanel(controller: c), + const SizedBox(height: 14), + _sec(t, '颜色'), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final int col in kArchPalette) _colorDot(t, c, col), + ], + ), + Text('影响新绘制的图形;选中图形后点色块可直接换色(支持多选)。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5)), + const SizedBox(height: 14), + _sec(t, '示例场景'), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => c.archLoadDemo(ArchDemoKind.ink), + style: _btnStyle(), + child: const Text('手绘稿'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: FilledButton( + onPressed: c.archPlayDemo, + style: FilledButton.styleFrom( + visualDensity: VisualDensity.compact, + textStyle: const TextStyle( + fontSize: 11.5, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ), + child: const Text('识别演示 ▶'), + ), + ), + ], + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => c.archLoadDemo(ArchDemoKind.done), + style: _btnStyle(), + child: const Text('完成图'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: TextButton( + onPressed: c.archClear, + style: TextButton.styleFrom( + foregroundColor: t.danger, + visualDensity: VisualDensity.compact, + textStyle: const TextStyle( + fontSize: 11.5, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ), + child: const Text('清空画布'), + ), + ), + ], + ), + const SizedBox(height: 14), + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('操作提示', + style: TextStyle( + color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), + const SizedBox(height: 6), + Text('手绘:按住拖动 → 松手自动识别', + style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('空白处左键拖拽 = 框选;中键 / 右键拖拽 = 平移', + style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('触屏:单指平移 · 长按框选 · 双指捏合缩放', + style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('双击图形 / 连线编辑文字 · Del 删除选中 · Ctrl+A 全选', + style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ], + ), + ), + ], + ); + } + + /// 粒度小圆片。 + Widget _chip(Tokens t, String label, bool active, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(7), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 4), + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.16) : t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: active ? t.accent : t.line), + ), + child: Text( + label, + style: TextStyle( + color: active ? t.accent : t.sub, + fontSize: 10.5, + fontWeight: active ? FontWeight.w700 : FontWeight.w500, + ), + ), + ), + ); + } + + /// 图形库按钮:点击后在视口中心插入一个标准图形。 + Widget _libBtn(Tokens t, IconData icon, String label, ArchShapeType type) { + return InkWell( + onTap: () => _insert(type), + borderRadius: BorderRadius.circular(9), + child: Container( + width: 82, + height: 56, + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: t.line), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 18, color: t.sub), + const SizedBox(height: 3), + Text(label, style: TextStyle(color: t.sub, fontSize: 10.5)), + ], + ), + ), + ); + } + + /// 在视口中心插入标准图形(位置按网格吸附)。 + void _insert(ArchShapeType type) { + final AppController c = controller; + final ArchDoc doc = c.arch; + final Size vp = c.archViewport; + final Size d = archDefaultSize(type); + final Offset center = vp.width < 10 || vp.height < 10 + ? const Offset(400, 300) + : Offset( + (vp.width / 2 - doc.panX) / doc.zoom, + (vp.height / 2 - doc.panY) / doc.zoom, + ); + Rect r = Rect.fromCenter(center: center, width: d.width, height: d.height); + if (doc.gridSnap && doc.gridSize > 1) { + final Offset tl = archSnapPoint(doc, r.topLeft); + r = Rect.fromLTWH(tl.dx, tl.dy, r.width, r.height); + } + final int color = c.archColor; + final ArchShape s = ArchShape( + id: archNewId('S', doc.allIds), + type: type, + rect: r, + radius: type == ArchShapeType.roundRect ? 16 : 0, + fill: type == ArchShapeType.text ? 0 : archFillOf(color), + stroke: color, + sw: 1.8, + text: type == ArchShapeType.text ? '文本' : '', + ); + c.addArchShape(s); + c.selectArch(s.id); + } + + /// 颜色圆点。 + Widget _colorDot(Tokens t, AppController c, int col) { + final bool active = c.archColor == col; + return InkWell( + onTap: () => c.setArchColor(col), + borderRadius: BorderRadius.circular(16), + child: Container( + width: 26, + height: 26, + decoration: BoxDecoration( + color: Color(col), + shape: BoxShape.circle, + border: Border.all( + color: active ? t.accent : t.line, + width: active ? 2.5 : 1, + ), + ), + ), + ); + } + + /// 小尺寸描边按钮样式。 + ButtonStyle _btnStyle() => OutlinedButton.styleFrom( + visualDensity: VisualDensity.compact, + textStyle: const TextStyle( + fontSize: 11.5, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ); +} + +/// 架构图右侧栏主体:选中对象属性(支持多选)。 +class ArchRightBody extends StatelessWidget { + /// 构造右侧栏主体。 + const ArchRightBody({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 构建:草图模式 → 草图面板;否则选中对象卡片 + 统计。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final AppController c = controller; + if (c.sketchMode) return _sketchBody(context, c); + final ArchDoc doc = c.arch; + final List sel = c.archSelIds; + final ArchShape? s = sel.length == 1 ? doc.shapeById(sel.first) : null; + final ArchConnector? cn = + sel.length == 1 ? doc.connectorById(sel.first) : null; + final ArchStroke? st = sel.length == 1 ? doc.strokeById(sel.first) : null; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sec(t, '选中对象'), + const SizedBox(height: 8), + if (sel.length > 1) + _card(t, [ + Text( + '已选中 ${sel.length} 个对象', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + Text('拖动任一选中图形可整体移动;改色作用于选中的图形。', + style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5)), + const SizedBox(height: 8), + Row( + children: [ + _mini(t, '全选', c.selectAllArch), + const SizedBox(width: 6), + _mini(t, '取消选择', () => c.selectArch(null)), + ], + ), + const SizedBox(height: 8), + Text('对齐 / 均布(以选中范围为参照;均布需 ≥3 个)', + style: TextStyle(color: t.dim, fontSize: 10.5)), + const SizedBox(height: 6), + Wrap( + spacing: 4, + runSpacing: 4, + children: [ + _alignBtn(t, Icons.align_horizontal_left, '左对齐', ArchAlign.left, c), + _alignBtn(t, Icons.align_horizontal_center, '横向居中', ArchAlign.hCenter, c), + _alignBtn(t, Icons.align_horizontal_right, '右对齐', ArchAlign.right, c), + _alignBtn(t, Icons.align_vertical_top, '顶对齐', ArchAlign.top, c), + _alignBtn(t, Icons.align_vertical_center, '纵向居中', ArchAlign.vCenter, c), + _alignBtn(t, Icons.align_vertical_bottom, '底对齐', ArchAlign.bottom, c), + _alignBtn(t, Icons.horizontal_distribute, '横向均布', ArchAlign.distributeH, c), + _alignBtn(t, Icons.vertical_distribute, '纵向均布', ArchAlign.distributeV, c), + ], + ), + const SizedBox(height: 6), + _mini(t, '删除(Del)', c.removeArchSelection, danger: true), + ]) + else if (s != null) + _card(t, [ + Row( + children: [ + Icon(_iconOf(s.type), size: 15, color: Color(s.stroke)), + const SizedBox(width: 6), + Expanded( + child: Text( + '${archShapeTypeLabel(s.type)} · ${s.id}', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ), + if (!s.isLinear) + Text( + '尺寸 ${s.rect.width.round()} × ${s.rect.height.round()} px', + style: TextStyle(color: t.dim, fontSize: 10.5), + ), + if (s.isLinear) + Text( + '${s.type == ArchShapeType.line && s.a != null ? 2 : s.pts.length} 个折点' + '${s.arrow ? ' · 箭头' : ''}', + style: TextStyle(color: t.dim, fontSize: 10.5), + ), + if (s.text.isNotEmpty) + Text( + '文字:${s.text.replaceAll('\n', ' / ')}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 11), + ), + const SizedBox(height: 8), + Row( + children: [ + _mini(t, '编辑文字', () => _editText(context, c, s)), + const SizedBox(width: 6), + _mini(t, '上移一层', () => c.moveArchZ(s, 1)), + const SizedBox(width: 6), + _mini(t, '下移一层', () => c.moveArchZ(s, -1)), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + if (s.type == ArchShapeType.polyline || + s.type == ArchShapeType.curve) ...[ + _mini( + t, + s.type == ArchShapeType.polyline ? '平滑为曲线' : '折线化', + () => _togglePolyCurve(c, s), + ), + const SizedBox(width: 6), + ], + _mini(t, '删除(Del)', c.removeArchSelection, danger: true), + ], + ), + const SizedBox(height: 10), + Text('尺寸(点数值修改 · 右键图标在画布上标注)', + style: TextStyle(color: t.dim, fontSize: 10)), + const SizedBox(height: 4), + for (final ArchDimKind k in archShapeDimKinds(s)) + Padding( + padding: const EdgeInsets.only(bottom: 3), + child: Row( + children: [ + SizedBox( + width: 34, + child: Text(archDimKindLabel(k), + style: TextStyle(color: t.dim, fontSize: 11)), + ), + InkWell( + onTap: () => _editShapeDim(context, c, s, k), + borderRadius: BorderRadius.circular(5), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(5), + border: Border.all(color: t.line), + ), + child: Text( + '${archShapeDimValue(s, k).toStringAsFixed(1)} mm', + style: TextStyle( + color: t.accent2, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + const Spacer(), + InkWell( + onTap: () => c.toggleArchShapeDim(s.id, k), + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: const EdgeInsets.all(3), + child: Icon( + s.dims.contains(k) + ? Icons.label + : Icons.label_outline, + size: 14, + color: s.dims.contains(k) ? t.accent : t.dim, + ), + ), + ), + ], + ), + ), + ]) + else if (cn != null) + _card(t, [ + Text( + '连线 · ${cn.id}', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + Text( + cn.label.isEmpty ? '(无标签)' : '标签:${cn.label}', + style: TextStyle(color: t.sub, fontSize: 11), + ), + const SizedBox(height: 8), + Row( + children: [ + _mini( + t, + '直线', + () => c.updateArchConnector( + cn.copyWith(route: ArchRoute.straight), status: '走线:直线'), + active: cn.route == ArchRoute.straight, + ), + const SizedBox(width: 6), + _mini( + t, + '正交折线', + () => c.updateArchConnector( + cn.copyWith(route: ArchRoute.ortho), status: '走线:正交折线'), + active: cn.route == ArchRoute.ortho, + ), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + _mini(t, '编辑标签', () => _editConnLabel(context, c, cn)), + const SizedBox(width: 6), + _mini(t, '删除(Del)', c.removeArchSelection, danger: true), + ], + ), + ]) + else if (st != null) + _card(t, [ + Text( + '手绘墨迹 · ${st.id}', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + Text( + '${st.pts.length} 个采样点(识别不了的笔迹保留为墨迹)', + style: TextStyle(color: t.sub, fontSize: 11), + ), + const SizedBox(height: 8), + Row( + children: [ + _mini(t, '删除(Del)', c.removeArchSelection, danger: true), + ], + ), + ]) + else + _card(t, [ + Text( + '未选中任何对象', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + Text( + '点选图形 / 连线 / 墨迹查看属性;空白拖拽框选,双击图形编辑文字。', + style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5), + ), + const SizedBox(height: 8), + _mini(t, '全选(Ctrl+A)', c.selectAllArch), + ]), + const SizedBox(height: 14), + Row( + children: [ + _sec(t, '图层'), + const Spacer(), + InkWell( + onTap: c.addArchLayer, + borderRadius: BorderRadius.circular(7), + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.add, size: 13, color: t.sub), + const SizedBox(width: 3), + Text('新建', style: TextStyle(color: t.sub, fontSize: 10.5)), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 8), + for (final ArchLayer ly in doc.layers) _layerRow(context, t, c, ly), + const SizedBox(height: 14), + _sec(t, '统计'), + const SizedBox(height: 6), + Text( + '元件 ${doc.shapes.length} · 连线 ${doc.connectors.length} · 墨迹 ${doc.strokes.length}', + style: TextStyle(color: t.sub, fontSize: 11), + ), + const SizedBox(height: 4), + Text( + '架构图保存为独立文件(*.arch.json),不与时序图互通。', + style: TextStyle(color: t.dim, fontSize: 10, height: 1.5), + ), + ], + ); + } + + /// 弹窗编辑图形文字(画布内也可双击图形直接编辑)。 + Future _editText( + BuildContext context, + AppController c, + ArchShape s, + ) async { + final String? r = + await showTextEditDialog(context, title: '编辑图形文字', initial: s.text); + if (r != null && r != s.text) { + c.updateArchShape(s.copyWith(text: r), status: '编辑文字'); + } + } + + /// 弹窗编辑连线标签(画布内也可双击连线直接编辑)。 + Future _editConnLabel( + BuildContext context, + AppController c, + ArchConnector cn, + ) async { + final String? r = + await showTextEditDialog(context, title: '编辑连线标签', initial: cn.label); + if (r != null && r != cn.label) { + c.updateArchConnector(cn.copyWith(label: r), status: '编辑连线标签'); + } + } + + /// 折线 ⇄ 曲线互转(同一组通过点)。 + void _togglePolyCurve(AppController c, ArchShape s) { + if (s.type == ArchShapeType.polyline) { + c.updateArchShape(s.copyWith(type: ArchShapeType.curve), + status: '已平滑为曲线'); + } else if (s.type == ArchShapeType.curve) { + c.updateArchShape(s.copyWith(type: ArchShapeType.polyline), + status: '已折线化'); + } + } + + /// 图层条目:可见 / 锁定 / 颜色 / 名称(单击设为活动、双击改名)/ 删除。 + Widget _layerRow( + BuildContext context, + Tokens t, + AppController c, + ArchLayer ly, + ) { + final ArchDoc doc = c.arch; + final bool active = doc.activeLayer == ly.id; + return Container( + margin: const EdgeInsets.only(bottom: 4), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.12) : t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: active ? t.accent : t.line), + ), + child: Row( + children: [ + _layerMiniIcon( + t, + ly.visible ? Icons.visibility_outlined : Icons.visibility_off_outlined, + ly.visible ? t.sub : t.dim, + () => c.toggleArchLayerVisible(ly.id), + ly.visible ? '隐藏图层' : '显示图层', + ), + _layerMiniIcon( + t, + ly.locked ? Icons.lock_outline : Icons.lock_open_outlined, + ly.locked ? t.warn : t.sub, + () => c.toggleArchLayerLocked(ly.id), + ly.locked ? '解锁图层' : '锁定图层', + ), + InkWell( + onTap: () => _pickLayerColor(context, c, ly), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.all(3), + child: Container( + width: 15, + height: 15, + decoration: BoxDecoration( + color: Color(ly.color), + shape: BoxShape.circle, + border: Border.all(color: t.line), + ), + ), + ), + ), + const SizedBox(width: 4), + Expanded( + child: GestureDetector( + onTap: () => c.setArchActiveLayer(ly.id), + onDoubleTap: () => _renameLayer(context, c, ly), + child: Text( + ly.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: active ? t.accent : t.text, + fontSize: 11.5, + fontWeight: active ? FontWeight.w700 : FontWeight.w500, + ), + ), + ), + ), + if (doc.layers.length > 1) + _layerMiniIcon( + t, + Icons.close, + t.dim, + () => c.removeArchLayer(ly.id), + '删除图层(对象移入首层)', + ), + ], + ), + ); + } + + /// 图层行内小图标按钮。 + Widget _layerMiniIcon( + Tokens t, + IconData icon, + Color color, + VoidCallback onTap, + String tip, + ) { + return Tooltip( + message: tip, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon(icon, size: 14, color: color), + ), + ), + ); + } + + /// 重命名图层(弹窗)。 + Future _renameLayer( + BuildContext context, + AppController c, + ArchLayer ly, + ) async { + final String? r = + await showTextEditDialog(context, title: '重命名图层', initial: ly.name); + if (r != null && r.trim().isNotEmpty && r != ly.name) { + c.updateArchLayer(ly.copyWith(name: r.trim()), status: '图层已重命名'); + } + } + + /// 选择图层颜色(调色板弹窗)。 + Future _pickLayerColor( + BuildContext context, + AppController c, + ArchLayer ly, + ) async { + final int? picked = await showDialog( + context: context, + builder: (BuildContext ctx) { + final Tokens tt = ctx.tok; + return AlertDialog( + backgroundColor: tt.dialog, + title: Text('图层颜色', + style: TextStyle( + color: tt.text, fontSize: 15, fontWeight: FontWeight.w700)), + content: Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final int col in kArchPalette) + InkWell( + onTap: () => Navigator.of(ctx).pop(col), + borderRadius: BorderRadius.circular(18), + child: Container( + width: 30, + height: 30, + decoration: BoxDecoration( + color: Color(col), + shape: BoxShape.circle, + border: Border.all( + color: col == ly.color ? tt.accent : tt.line, + width: col == ly.color ? 2.5 : 1, + ), + ), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), + child: const Text('取消')), + ], + ); + }, + ); + if (picked != null) { + c.updateArchLayer(ly.copyWith(color: picked), status: '图层颜色已更新'); + } + } + + /// 卡片容器。 + /// 草图模式的右侧栏:选中对象 / 统计 / 提示。 + Widget _sketchBody(BuildContext context, AppController c) { + final Tokens t = context.tok; + final SketchDoc d = c.sketch; + final List sel = c.sketchSelIds; + final int consCount = + d.constraints.where((SketchConstraint k) => !k.internal).length; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sec(t, '草图 · 选中对象'), + const SizedBox(height: 8), + _card(t, [ + Text( + sel.isEmpty ? '未选中任何草图对象' : '已选中 ${sel.length} 个对象', + style: TextStyle( + color: t.text, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + Text( + '点 / 实体 / 尺寸都可选中;拖动点或图形会按约束实时求解,' + '双击尺寸标签可直接改值。', + style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5), + ), + const SizedBox(height: 8), + Row( + children: [ + _mini(t, '全选', c.selectAllSketch), + const SizedBox(width: 6), + _mini(t, '取消选择', () => c.selectSketchIds(const [])), + const SizedBox(width: 6), + _mini(t, '删除(Del)', c.deleteSketchSelection, danger: true), + ], + ), + ]), + const SizedBox(height: 14), + _sec(t, '草图统计'), + const SizedBox(height: 8), + _card(t, [ + Text('点 ${d.points.length} · 实体 ${d.entities.length}', + style: TextStyle(color: t.sub, fontSize: 11.5)), + Text('约束 $consCount · 尺寸 ${d.dims.length}', + style: TextStyle(color: t.sub, fontSize: 11.5)), + Text('剩余自由度 ${sketchDofCount(d)}', + style: TextStyle(color: t.sub, fontSize: 11.5)), + const SizedBox(height: 4), + Text( + sketchDofCount(d) == 0 + ? '已全约束:几何被尺寸 / 约束完全驱动。' + : '欠约束:可继续添加约束 / 尺寸,或直接拖动试解。', + style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.5), + ), + ]), + ], + ); + } + + /// 属性卡片容器。 + Widget _card(Tokens t, List children) { + return Container( + width: double.infinity, + 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: children, + ), + ); + } + + /// 小按钮。 + Widget _mini( + Tokens t, + String label, + VoidCallback onTap, { + bool danger = false, + bool active = false, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: danger + ? t.danger.withValues(alpha: 0.12) + : (active ? t.accent.withValues(alpha: 0.16) : t.panel), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: danger + ? t.danger.withValues(alpha: 0.45) + : (active ? t.accent : t.line), + ), + ), + child: Text( + label, + style: TextStyle( + color: danger ? t.danger : (active ? t.accent : t.sub), + fontSize: 11, + ), + ), + ), + ); + } + + /// 对齐 / 均布小按钮(图标 + 悬浮提示)。 + Widget _alignBtn( + Tokens t, + IconData icon, + String tip, + ArchAlign mode, + AppController c, + ) { + return Tooltip( + message: tip, + child: InkWell( + onTap: () => c.alignArchSelection(mode), + borderRadius: BorderRadius.circular(7), + child: Container( + width: 30, + height: 28, + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line), + ), + child: Icon(icon, size: 15, color: t.sub), + ), + ), + ); + } + + /// 图形类型对应的小图标。 + IconData _iconOf(ArchShapeType type) { + switch (type) { + case ArchShapeType.rect: + return Icons.crop_square; + case ArchShapeType.roundRect: + return Icons.rounded_corner; + case ArchShapeType.ellipse: + return Icons.panorama_fish_eye; + case ArchShapeType.circle: + return Icons.circle_outlined; + case ArchShapeType.triangle: + return Icons.change_history; + case ArchShapeType.diamond: + return Icons.diamond_outlined; + case ArchShapeType.cylinder: + return Icons.storage; + case ArchShapeType.cloud: + return Icons.cloud_outlined; + case ArchShapeType.hexagon: + return Icons.hexagon_outlined; + case ArchShapeType.text: + return Icons.text_fields; + case ArchShapeType.line: + return Icons.trending_flat; + case ArchShapeType.polyline: + return Icons.polyline; + case ArchShapeType.curve: + return Icons.gesture; + case ArchShapeType.server: + return Icons.dns_outlined; + case ArchShapeType.client: + return Icons.desktop_windows_outlined; + case ArchShapeType.mobile: + return Icons.smartphone; + case ArchShapeType.firewall: + return Icons.security; + case ArchShapeType.netSwitch: + return Icons.lan_outlined; + case ArchShapeType.queue: + return Icons.view_stream_outlined; + case ArchShapeType.symbol: + return Icons.extension_outlined; + } + } +} + +// ===================== 图元库面板(可折叠 · Visio 式) ===================== + +/// 图元库面板:按分类折叠展示(默认全部收起,只展开选中的库), +/// 点图元即插入画布;用户图元可删除;支持导入与「从选中图形存为图元」。 +class _SymbolLibPanel extends StatefulWidget { + /// 构造。 + const _SymbolLibPanel({required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 创建状态。 + @override + State<_SymbolLibPanel> createState() => _SymbolLibPanelState(); +} + +/// 面板状态:记录当前展开的分类(同时只允许一个)。 +class _SymbolLibPanelState extends State<_SymbolLibPanel> { + String? _openCategory; + + /// 构建。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final AppController c = widget.controller; + final Map> groups = >{}; + for (final LibSymbol s in SymbolCache.all) { + groups.putIfAbsent(s.category, () => []).add(s); + } + final List cats = groups.keys.toList(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text('图元库(可扩展)', + style: TextStyle(color: t.dim, fontSize: 10)), + const Spacer(), + InkWell( + onTap: () => _symImport(context, c), + borderRadius: BorderRadius.circular(6), + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Text('导入图元…', + style: TextStyle( + color: t.accent, + fontSize: 10.5, + fontWeight: FontWeight.w600)), + ), + ), + ], + ), + const SizedBox(height: 4), + for (final String cat in cats) ...[ + InkWell( + onTap: () => setState(() => + _openCategory = _openCategory == cat ? null : cat), + borderRadius: BorderRadius.circular(7), + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 5), + margin: const EdgeInsets.only(bottom: 3), + decoration: BoxDecoration( + color: _openCategory == cat + ? t.accent.withValues(alpha: 0.10) + : t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all( + color: _openCategory == cat + ? t.accent.withValues(alpha: 0.5) + : t.line, + ), + ), + child: Row( + children: [ + Icon( + _openCategory == cat + ? Icons.expand_less + : Icons.expand_more, + size: 15, + color: _openCategory == cat ? t.accent : t.sub, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + '$cat(${groups[cat]!.length})', + style: TextStyle( + color: _openCategory == cat ? t.accent : t.sub, + fontSize: 11, + fontWeight: _openCategory == cat + ? FontWeight.w700 + : FontWeight.w500, + ), + ), + ), + ], + ), + ), + ), + if (_openCategory == cat) + Padding( + padding: const EdgeInsets.only(left: 6, right: 2, bottom: 4), + child: Wrap( + spacing: 6, + runSpacing: 6, + children: [ + for (final LibSymbol sym in groups[cat]!) _symCard(t, c, sym), + ], + ), + ), + ], + const SizedBox(height: 4), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: + c.archSelIds.isEmpty ? null : () => _symFromSelection(context, c), + icon: const Icon(Icons.add_box_outlined, size: 15), + label: const Text('从选中图形存为图元'), + style: OutlinedButton.styleFrom( + visualDensity: VisualDensity.compact, + textStyle: const TextStyle( + fontSize: 11.5, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + ), + ), + ), + ], + ); + } +} + +/// 图元卡片(预览 + 名称;用户图元带删除角标)。 +Widget _symCard(Tokens t, AppController c, LibSymbol sym) { + final bool user = !SymbolLibrary.isBuiltinId(sym.id); + return InkWell( + onTap: () => _insertSymbolShape(c, sym), + borderRadius: BorderRadius.circular(9), + child: Container( + width: 82, + height: 64, + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(9), + border: Border.all(color: t.line), + ), + child: Stack( + children: [ + Positioned.fill( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 34, + height: 30, + child: CustomPaint( + painter: _SymPreviewPainter(sym, t.sub), + ), + ), + const SizedBox(height: 2), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 3), + child: Text( + sym.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.sub, fontSize: 9.5), + ), + ), + ], + ), + ), + if (user) + Positioned( + right: 0, + top: 0, + child: InkWell( + onTap: () => _symDelete(c, sym), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.all(3), + child: Icon(Icons.close, size: 12, color: t.dim), + ), + ), + ), + ], + ), + ), + ); +} + +/// 插入图元库符号(保持图元纵横比,位置在视口中心、可吸附网格)。 +void _insertSymbolShape(AppController c, LibSymbol sym) { + final ArchDoc doc = c.arch; + final Size vp = c.archViewport; + final Offset center = vp.width < 10 || vp.height < 10 + ? const Offset(400, 300) + : Offset( + (vp.width / 2 - doc.panX) / doc.zoom, + (vp.height / 2 - doc.panY) / doc.zoom, + ); + final Rect nat = symbolNaturalBounds(sym); + final double scale = 140 / math.max(nat.width, nat.height); + Rect r = Rect.fromCenter( + center: center, + width: nat.width * scale, + height: nat.height * scale, + ); + if (doc.gridSnap && doc.gridSize > 1) { + final Offset tl = archSnapPoint(doc, r.topLeft); + r = Rect.fromLTWH(tl.dx, tl.dy, r.width, r.height); + } + final int color = c.archColor; + final ArchShape s = ArchShape( + id: archNewId('S', doc.allIds), + type: ArchShapeType.symbol, + symbolId: sym.id, + rect: r, + fill: archFillOf(color), + stroke: color, + sw: 1.8, + ); + c.addArchShape(s); + c.selectArch(s.id); +} + +/// 删除用户图元(内置图元不可删)。 +Future _symDelete(AppController c, LibSymbol sym) async { + await SymbolLibrary.deleteUser(sym.id); + await SymbolCache.refresh(); + c.setStatus('已删除图元「${sym.name}」'); +} + +/// 导入图元文件(`*.symbol.json`;桌面文件浏览器 / 安卓公共目录)。 +Future _symImport(BuildContext context, AppController c) async { + try { + String content; + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => const AndroidFileDialog( + saveMode: false, + defaultName: '', + suffix: '.symbol.json', + ), + ); + if (name == null) return; + final Uint8List? bytes = await AndroidDocs.readFile(name); + if (bytes == null) { + c.setStatus('导入失败:未找到文件 $name'); + return; + } + content = utf8.decode(bytes); + } else { + final String? path = await pickFile( + context, + save: false, + suffix: '.symbol.json', + ); + if (path == null) return; + content = await File(path).readAsString(); + } + final LibSymbol sym = + LibSymbol.fromJson(jsonDecode(content) as Map); + if (sym.id.isEmpty || sym.prims.isEmpty) { + c.setStatus('导入失败:不是有效的图元文件'); + return; + } + await SymbolLibrary.saveUser(sym); + await SymbolCache.refresh(); + c.setStatus('已导入图元「${sym.name}」(${sym.category})'); + } catch (e) { + c.setStatus('导入失败:$e'); + } +} + +/// 把当前选中的图形保存为图元(可多选;几何按选中范围归一化到 100×100)。 +Future _symFromSelection(BuildContext context, AppController c) async { + final List sel = [ + for (final String id in c.archSelIds) + if (c.arch.shapeById(id) != null) c.arch.shapeById(id)!, + ]; + if (sel.isEmpty) { + c.setStatus('先选中要保存为图元的图形(可多选)'); + return; + } + final String? name = await showTextEditDialog( + context, + title: '保存为图元(名称)', + initial: '自定义图元', + ); + if (name == null || name.trim().isEmpty) return; + final LibSymbol sym = _symbolFromShapes(sel, name.trim()); + await SymbolLibrary.saveUser(sym); + await SymbolCache.refresh(); + c.setStatus('已保存图元「${sym.name}」到图元库(可点击插入 / 手绘识别)'); +} + +/// 由图形集合生成图元(采样轮廓为折线 + 文本)。 +LibSymbol _symbolFromShapes(List shapes, String name) { + Rect union = shapes.first.bounds; + for (final ArchShape s in shapes) { + union = union.expandToInclude(s.bounds); + } + final double scale = 100 / math.max(union.width, union.height); + final Offset c0 = union.center; + Offset norm(Offset p) => + Offset((p.dx - c0.dx) * scale + 50, (p.dy - c0.dy) * scale + 50); + final List prims = []; + for (final ArchShape s in shapes) { + final Path path = archShapePath(s); + for (final PathMetric m in path.computeMetrics()) { + final int count = + math.max(6, (m.length * scale / 5).ceil()).clamp(6, 160); + final List flat = []; + for (int i = 0; i <= count; i++) { + final Tangent? t = m.getTangentForOffset(m.length * i / count); + if (t == null) continue; + final Offset n2 = norm(t.position); + flat.add(n2.dx); + flat.add(n2.dy); + } + if (flat.length >= 4) { + prims.add(SymPrim(kind: SymPrimKind.polyline, pts: flat)); + } + } + if (s.text.isNotEmpty) { + final Offset n2 = norm(s.rect.center); + prims.add(SymPrim( + kind: SymPrimKind.text, + pts: [n2.dx - s.text.length * 2.5, n2.dy - 5], + label: s.text, + )); + } + } + return LibSymbol( + id: 'user-${DateTime.now().millisecondsSinceEpoch}', + name: name, + category: '自定义', + prims: prims, + pins: const [], + ); +} diff --git a/lib/ui/arch_view.dart b/lib/ui/arch_view.dart new file mode 100644 index 0000000..2d2cd23 --- /dev/null +++ b/lib/ui/arch_view.dart @@ -0,0 +1,1899 @@ +/// 架构图画布:手绘识别(笔迹一律识别为标准图形)、选择与框选多选、 +/// 批量移动 / 缩放、网格吸附、连线(直线 / 正交 / 极轴)、文字编辑与 +/// 「墨迹 → 标准图形」转化动画。 +/// +/// 与 `CanvasView`(时序图画布)并列:只服务架构图模块;手势走原始指针事件 +/// (鼠标 / 触屏 / 手写笔一致),双指捏合缩放平移,触屏长按进入框选。 +library; + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +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'; + +/// 架构图画布组件。 +class ArchView extends StatefulWidget { + /// 构造画布;[controller] 为全局应用控制器。 + const ArchView({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 创建状态对象。 + @override + State createState() => _ArchViewState(); +} + +/// 画布状态:指针跟踪、草稿、选择操作、转化动画与识别演示。 +class _ArchViewState extends State + with SingleTickerProviderStateMixin { + /// 控制器快捷访问。 + AppController get c => widget.controller; + + // ---- 指针跟踪(支持双指捏合) ---- + final Map _pointers = {}; + int? _primaryPointer; + Offset _downScreen = Offset.zero; + + // ---- 手绘草稿 ---- + List? _draft; + + // ---- 连线草稿(按住左键画路径) ---- + String? _connFromId; + + // ---- 连线折点拖动 ---- + ArchConnector? _connVertexOrigin; + int _connVertexIndex = 0; + List _connVertexPts = []; + ArchConnector? _connVertexUpdated; + + /// 端点拖拽中的候选吸附目标(松手时生效;null = 脱离为自由端点)。 + String? _connDragTargetId; + + // ---- 平移 ---- + bool _panning = false; + Offset _panStartScreen = Offset.zero; + Offset _panStartPan = Offset.zero; + + // ---- 触屏长按框选 ---- + bool _touchEmpty = false; + DateTime _touchDownAt = DateTime.now(); + Offset _touchDownPos = Offset.zero; + + // ---- 框选 ---- + bool _marquee = false; + Offset? _mqStart; + Offset? _mqEnd; + + // ---- 双指捏合 ---- + bool _pinching = false; + double _pinchStartDist = 1; + double _pinchStartZoom = 1; + Offset _pinchStartFocal = Offset.zero; + Offset _pinchStartPan = Offset.zero; + + // ---- 移动 / 缩放(支持多选批量) ---- + List _moveIds = []; + Map? _moveDeltas; + Offset _moveStartWorld = Offset.zero; + List _guideXs = const []; + List _guideYs = const []; + int? _resizeHandle; + Rect? _resizeRect; + ArchShape? _resizeOrigin; + + // ---- 折点拖动(折线 / 曲线 / 直线端点) ---- + int _vertexIndex = 0; + List? _vertexPts; + ArchShape? _vertexOrigin; + + // ---- 鼠标位置(四边标尺滑动虚线用) ---- + Offset? _cursorWorld; + + // ---- 点击 / 双击 ---- + int _lastClickMs = 0; + Offset _lastClickPos = Offset.zero; + + // ---- 文字编辑 ---- + String? _editId; + TextEditingController? _editCtrl; + FocusNode? _editFocus; + + // ---- 转化动画 ---- + final List _conversions = []; + late final Ticker _ticker; + double _nowMs = 0; + + // ---- 识别演示 ---- + int _seenPlayToken = 0; + bool _playing = false; + + // ---- 转化回溯(图元库多笔组合) ---- + String? _lastConvId; + List _lastConvPts = const []; + DateTime? _lastConvAt; + + // ---- 组合识别缓存(两笔绘图 / 圆柱拼接) ---- + String? _lastInkId; + DateTime? _lastInkAt; + String? _lastPartId; + ArchRecognition? _lastPartRec; + DateTime? _lastPartAt; + + // ---- 参数化草图交互 ---- + SketchSnap? _skLiveSnap; + final List _skClicks = []; + String? _skDragPointId; + String? _skDragEntityId; + Offset _skDragStartWorld = Offset.zero; + final Map _skDragOrigPts = {}; + String? _skDragRadiusId; + + /// 已弹出过数值编辑框的尺寸 id(防止监听重复弹窗)。 + String? _seenDimEdit; + + /// 初始化:创建动画 Ticker,监听控制器的「识别演示」触发信号。 + @override + void initState() { + super.initState(); + _ticker = createTicker(_onTick); + c.addListener(_onController); + _seenPlayToken = c.archPlayToken; + } + + /// 释放资源。 + @override + void dispose() { + c.removeListener(_onController); + _ticker.dispose(); + _editCtrl?.dispose(); + _editFocus?.dispose(); + super.dispose(); + } + + /// 控制器变化:识别演示令牌变化时启动演示;新标注尺寸弹出数值编辑框。 + void _onController() { + if (c.archPlayToken != _seenPlayToken) { + _seenPlayToken = c.archPlayToken; + _startPlay(); + } + final String? dimId = c.sketchDimToEdit; + if (dimId != null && dimId != _seenDimEdit) { + _seenDimEdit = dimId; + final SketchDim? dd = c.sketch.dimById(dimId); + c.clearSketchDimToEdit(); + if (dd != null) _editSketchDim(dd); + } + } + + // ===================== 转化动画 ===================== + + /// 动画帧:推进转化进度,完成的写入文档。 + void _onTick(Duration _) { + _nowMs = DateTime.now().millisecondsSinceEpoch.toDouble(); + final List done = []; + for (final ArchConversion cv in _conversions) { + if (cv.progress(_nowMs) >= 1) done.add(cv); + } + for (final ArchConversion cv in done) { + _conversions.remove(cv); + c.commitArchConversion( + cv.shape, + removeIds: cv.removeIds, + undo: cv.undo, + ); + } + if (mounted) setState(() {}); + if (_conversions.isEmpty) _ticker.stop(); + } + + /// 启动一次「墨迹 → 图形」的转化动画。 + void _startConversion( + List pts, + ArchShape shape, { + Set removeIds = const {}, + bool undo = true, + }) { + // 记录本次转化:2.5 秒内新笔迹可与之组合成「图元库符号」 + //(如 圆 先被识别成圆,紧接着画的叉会合并成「指示灯」)。 + _lastConvId = shape.id; + _lastConvPts = List.of(pts); + _lastConvAt = DateTime.now(); + _conversions.add(ArchConversion( + pts: pts, + shape: shape, + startMs: DateTime.now().millisecondsSinceEpoch.toDouble(), + undo: undo, + removeIds: removeIds, + )); + if (!_ticker.isActive) _ticker.start(); + setState(() {}); + } + + /// 播放「识别演示」:把当前墨迹逐条识别,串行播放转化动画。 + Future _startPlay() async { + if (_playing) return; + _playing = true; + final int token = _seenPlayToken; + final List ids = [ + for (final ArchStroke s in c.arch.strokes) s.id, + ]; + for (final String id in ids) { + if (!mounted || !_playing || _seenPlayToken != token) break; + final ArchStroke? st = c.arch.strokeById(id); + if (st == null) continue; + final ArchRecognition? r = recognizeArchStroke(st.pts); + if (r != null) { + final ArchShape shape = archShapeFromRecognition( + r, + id: archNewId('S', c.arch.allIds), + color: c.archColor, + ); + _conversions.add(ArchConversion( + pts: st.pts, + shape: shape, + startMs: DateTime.now().millisecondsSinceEpoch.toDouble(), + undo: false, + removeIds: {id}, + )); + if (!_ticker.isActive) _ticker.start(); + setState(() {}); + } + await Future.delayed(const Duration(milliseconds: 230)); + } + _playing = false; + } + + // ===================== 坐标与命中 ===================== + + /// 屏幕坐标 → 世界坐标。 + Offset _toWorld(Offset screen) => Offset( + (screen.dx - c.arch.panX) / c.arch.zoom, + (screen.dy - c.arch.panY) / c.arch.zoom, + ); + + /// 命中测试:返回 (id, 图形?)。优先图形 → 连线 → 墨迹(后者在上层); + /// 隐藏图层与锁定图层的对象不可选中。 + (String?, ArchShape?) _hitTest(Offset world) { + final ArchDoc doc = c.arch; + for (int i = doc.shapes.length - 1; i >= 0; i--) { + final ArchShape s = doc.shapes[i]; + if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) { + continue; + } + if (s.hitTest(world)) return (s.id, s); + } + final double tol = 8 / c.arch.zoom + 4; + for (int i = doc.connectors.length - 1; i >= 0; i--) { + final ArchConnector cn = doc.connectors[i]; + if (!doc.isLayerVisible(cn.layerId) || doc.isLayerLocked(cn.layerId)) { + continue; + } + final ArchConnGeometry g = archConnectorGeometry(doc, cn); + for (int k = 0; k < g.pts.length - 1; k++) { + if (archDistToSegment(world, g.pts[k], g.pts[k + 1]) <= tol) { + return (cn.id, null); + } + } + } + for (int i = doc.strokes.length - 1; i >= 0; i--) { + final ArchStroke s = doc.strokes[i]; + if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) { + continue; + } + if (s.hitTest(world)) return (s.id, null); + } + return (null, null); + } + + /// 命中的图形(宽容 6px,用于手绘箭头端点与连线自动吸附; + /// 锁定图层仍可作为吸附参照,隐藏图层不可)。 + ArchShape? _shapeAt(Offset world) { + final ArchDoc doc = c.arch; + for (int i = doc.shapes.length - 1; i >= 0; i--) { + if (!doc.isLayerVisible(doc.shapes[i].layerId)) continue; + if (doc.shapes[i].hitTest(world, pad: 6)) return doc.shapes[i]; + } + return null; + } + + // ===================== 参数化草图:交互 ===================== + + /// 草图按下:选择 / 拖拽(约束求解)/ 绘制 / 修剪。 + void _sketchDown(Offset world, PointerDownEvent e) { + final SketchDoc d = c.sketch; + final double z = c.arch.zoom <= 0 ? 1 : c.arch.zoom; + + if (c.sketchTool == SketchTool.select) { + final SketchHit hit = sketchHitTest( + d, + world, + pointTol: 9 / z, + entityTol: 6 / z, + dimTol: 10 / z, + ); + // 命令模式(约束 / 尺寸命令):点选优先交给命令状态机消费。 + if (c.sketchPendingCons != null || c.sketchPendingDim != null) { + c.sketchCommandPick(hit); + setState(() {}); + return; + } + if (hit.dimId != null) { + final int now = DateTime.now().millisecondsSinceEpoch; + final bool dbl = now - _lastClickMs < 400 && + (e.localPosition - _lastClickPos).distance < 28; + c.selectSketchIds([hit.dimId!]); + if (dbl) { + _lastClickMs = 0; + _editSketchDim(d.dimById(hit.dimId!)!); + } + setState(() {}); + return; + } + if (hit.pointId != null) { + c.selectSketchIds([hit.pointId!]); + _skDragPointId = hit.pointId; + c.beginSketchUndo(); + c.dragSketch(points: {hit.pointId!: world}); + setState(() {}); + return; + } + if (hit.entityId != null) { + final bool shift = HardwareKeyboard.instance.isShiftPressed; + if (shift) { + c.toggleSketchId(hit.entityId!); + } else if (!c.sketchSelIds.contains(hit.entityId)) { + c.selectSketchIds([hit.entityId!]); + } + final SketchEntity en = d.entityById(hit.entityId!)!; + final Offset? center = d.pointById(en.p1)?.pos; + final bool nearCenter = + center != null && (world - center).distance <= 9 / z; + if (en.kind != SketchKind.line && !nearCenter && center != null) { + final bool hasRDim = d.dims.any((SketchDim dd) => + dd.type == SketchDimType.radius && dd.a == en.id); + if (!hasRDim) { + // 拖动圆 / 弧轮廓 → 调整半径(有半径尺寸时改为平移)。 + _skDragRadiusId = en.id; + c.beginSketchUndo(); + c.dragSketch(radii: { + en.id: (world - center).distance, + }); + setState(() {}); + return; + } + } + // 平移:所有引用点同步位移(圆弧端点随行,保持刚性)。 + _skDragEntityId = en.id; + _skDragStartWorld = world; + _skDragOrigPts.clear(); + final List pts = + en.kind == SketchKind.line ? [en.p1, en.p2] : d.entityPointIds(en); + for (final String pid in pts) { + _skDragOrigPts[pid] = d.pointById(pid)?.pos ?? world; + } + c.beginSketchUndo(); + setState(() {}); + return; + } + // 空白:框选(复用画布框选状态)。 + c.selectSketchIds(const []); + _marquee = true; + _mqStart = world; + _mqEnd = world; + setState(() {}); + return; + } + + // 绘制工具 / 修剪:逐个点击落点(自动捕捉)。 + final SketchSnap snap = sketchSnap( + d, + world, + gridSnap: c.arch.gridSnap, + grid: c.arch.gridSize, + pointTol: 11 / z, + entityTol: 8 / z, + ); + if (c.sketchTool == SketchTool.trim) { + final SketchHit hit = + sketchHitTest(d, world, pointTol: 2, entityTol: 7 / z, dimTol: 2); + final String? eid = hit.entityId; + if (eid == null) { + c.setStatus('修剪:请点击要删除的线段'); + return; + } + final SketchDoc? out = sketchTrimLine(d, eid, world); + if (out == null) { + c.setStatus('修剪:仅支持直线(无交点时整条删除)'); + return; + } + c.changeSketch((_) => out, status: '修剪直线'); + return; + } + + _skClicks.add(snap); + _skLiveSnap = snap; + if (c.sketchTool == SketchTool.line && _skClicks.length >= 2) { + final List cl = List.of(_skClicks); + _skClicks.clear(); + _commitSketchLine(cl[0], cl[1]); + } else if (c.sketchTool == SketchTool.circle && _skClicks.length >= 2) { + final List cl = List.of(_skClicks); + _skClicks.clear(); + _commitSketchCircle(cl[0], cl[1]); + } else if (c.sketchTool == SketchTool.arc && _skClicks.length >= 3) { + final List cl = List.of(_skClicks); + _skClicks.clear(); + _commitSketchArc(cl[0], cl[1], cl[2]); + } else if (c.sketchTool == SketchTool.rect && _skClicks.length >= 2) { + final List cl = List.of(_skClicks); + _skClicks.clear(); + _commitSketchRect(cl[0], cl[1]); + } + setState(() {}); + } + + /// 草图拖动:拖点 / 拖实体 / 改半径 → 实时约束求解;绘制中更新捕捉与预览。 + void _sketchMove(Offset world) { + if (_skDragPointId != null) { + c.dragSketch(points: {_skDragPointId!: world}); + return; + } + if (_skDragEntityId != null && _skDragOrigPts.isNotEmpty) { + final Offset delta = world - _skDragStartWorld; + c.dragSketch(points: { + for (final MapEntry e in _skDragOrigPts.entries) + e.key: e.value + delta, + }); + return; + } + if (_skDragRadiusId != null) { + final Offset? center = + c.sketch.pointById(c.sketch.entityById(_skDragRadiusId!)?.p1)?.pos; + if (center != null) { + c.dragSketch(radii: { + _skDragRadiusId!: (world - center).distance, + }); + } + return; + } + if (_marquee) { + _mqEnd = world; + setState(() {}); + return; + } + final double z = c.arch.zoom <= 0 ? 1 : c.arch.zoom; + final SketchSnap snap = sketchSnap( + c.sketch, + world, + gridSnap: c.arch.gridSnap, + grid: c.arch.gridSize, + pointTol: 11 / z, + entityTol: 8 / z, + ); + _skLiveSnap = snap; + setState(() {}); + } + + /// 草图抬起:结束拖拽 / 提交框选。 + void _sketchUp(Offset world, bool moved) { + if (_skDragPointId != null || + _skDragEntityId != null || + _skDragRadiusId != null) { + _skDragPointId = null; + _skDragEntityId = null; + _skDragRadiusId = null; + _skDragOrigPts.clear(); + return; + } + if (_marquee) { + final Rect r = Rect.fromPoints(_mqStart ?? world, _mqEnd ?? world); + _marquee = false; + if (r.width < 3 && r.height < 3) { + setState(() {}); + return; + } + final List ids = []; + for (final SketchPoint p in c.sketch.points) { + if (r.contains(p.pos)) ids.add(p.id); + } + for (final SketchEntity en in c.sketch.entities) { + final List pts = c.sketch.entityPointIds(en); + if (pts.isNotEmpty && + pts.every( + (String pid) => r.contains(c.sketch.pointById(pid)!.pos))) { + ids.add(en.id); + } + } + c.selectSketchIds(ids); + setState(() {}); + } + } + + /// 绘制预览(橡皮筋)。 + SketchPreview? _skPreview() { + if (!c.sketchMode || _skClicks.isEmpty) return null; + final Offset first = _skClicks.first.pos; + final Offset last = _skLiveSnap?.pos ?? first; + if (c.sketchTool == SketchTool.line) { + return SketchPreview(pts: [first, last]); + } + if (c.sketchTool == SketchTool.circle) { + return SketchPreview( + pts: [first, last], kind: SketchKind.circle); + } + if (c.sketchTool == SketchTool.arc) { + if (_skClicks.length == 1) { + return SketchPreview( + pts: [first, last], kind: SketchKind.circle); + } + return SketchPreview( + pts: [first, _skClicks[1].pos, last], + kind: SketchKind.arc, + ); + } + if (c.sketchTool == SketchTool.rect) { + return SketchPreview( + pts: [ + first, + Offset(last.dx, first.dy), + last, + Offset(first.dx, last.dy), + ], + closed: true, + ); + } + return null; + } + + /// 新建点(若捕捉到已有点则复用)。 + SketchPoint _skPoint(SketchSnap snap, List fresh) { + final String id = sketchNewId('P', [...c.sketch.allIds, ...fresh]); + return SketchPoint(id: id, x: snap.pos.dx, y: snap.pos.dy); + } + + /// 提交直线(两端捕捉:已有 → 复用;实体上 → pointOnEntity;近轴 → 自动约束)。 + void _commitSketchLine(SketchSnap a, SketchSnap b) { + SketchDoc d = c.sketch; + final List addPts = []; + final List fresh = []; + final List extra = []; + String idFor(SketchSnap snap, List into, List pts, + List cons) { + if (snap.pointId != null) return snap.pointId!; + final SketchPoint p = _skPoint(snap, [...fresh, ...into]); + into.add(p.id); + pts.add(p); + if (snap.entityId != null) { + cons.add(SketchConstraint( + id: sketchNewId('K', [ + ...d.allIds, + ...fresh, + ...cons.map((SketchConstraint x) => x.id), + ]), + type: SketchConsType.pointOnEntity, + a: p.id, + b: snap.entityId!, + )); + } + return p.id; + } + + final List ids = []; + final String p1 = idFor(a, ids, addPts, extra); + final String p2 = idFor(b, ids, addPts, extra); + if (p1 == p2) return; + for (final SketchPoint p in addPts) { + d = d.upsertPoint(p); + } + final String eid = sketchNewId('E', [...d.allIds, ...ids]); + d = d.upsertEntity( + SketchEntity(id: eid, kind: SketchKind.line, p1: p1, p2: p2)); + final Offset pa = d.pointById(p1)!.pos; + final Offset pb = d.pointById(p2)!.pos; + final SketchConsType? axis = sketchAutoAxis(pa, pb); + if (axis != null) { + extra.add(SketchConstraint( + id: sketchNewId('K', [ + ...d.allIds, + ...extra.map((SketchConstraint x) => x.id), + ]), + type: axis, + a: eid, + )); + } + d = d.copyWith(constraints: [...d.constraints, ...extra]); + final SketchSolveResult r = solveSketch(d); + c.changeSketch( + (_) => r.doc, + status: '草图:直线' + '${axis != null ? '(自动${sketchConsLabel(axis)})' : ''}', + ); + } + + /// 提交圆(圆心捕捉;第二点定半径)。 + void _commitSketchCircle(SketchSnap a, SketchSnap b) { + SketchDoc d = c.sketch; + String center = a.pointId ?? ''; + if (center.isEmpty) { + final SketchPoint p = _skPoint(a, const []); + d = d.upsertPoint(p); + center = p.id; + if (a.entityId != null) { + d = d.copyWith(constraints: [ + ...d.constraints, + SketchConstraint( + id: sketchNewId('K', d.allIds), + type: SketchConsType.pointOnEntity, + a: center, + b: a.entityId!, + ), + ]); + } + } + final double r = (b.pos - d.pointById(center)!.pos).distance; + if (r < 2) return; + final String eid = sketchNewId('E', d.allIds); + d = d.upsertEntity( + SketchEntity(id: eid, kind: SketchKind.circle, p1: center, r: r)); + c.changeSketch((_) => d, status: '草图:圆 R${r.round()}'); + } + + /// 提交圆弧(圆心 → 起点 → 终点;端点自动落在圆上)。 + void _commitSketchArc(SketchSnap a, SketchSnap b, SketchSnap cc) { + SketchDoc d = c.sketch; + String center = a.pointId ?? ''; + if (center.isEmpty) { + final SketchPoint p = _skPoint(a, const []); + d = d.upsertPoint(p); + center = p.id; + } + String ps = b.pointId ?? ''; + if (ps.isEmpty) { + final SketchPoint p = _skPoint(b, [center]); + d = d.upsertPoint(p); + ps = p.id; + } + String pe = cc.pointId ?? ''; + if (pe.isEmpty) { + final SketchPoint p = _skPoint(cc, [center, ps]); + d = d.upsertPoint(p); + pe = p.id; + } + final double r = (d.pointById(ps)!.pos - d.pointById(center)!.pos).distance; + if (r < 2 || ps == pe) return; + final String eid = sketchNewId('E', d.allIds); + d = d.upsertEntity(SketchEntity( + id: eid, + kind: SketchKind.arc, + p1: center, + p2: ps, + p3: pe, + r: r, + )); + final SketchSolveResult res = solveSketch(d); + c.changeSketch((_) => res.doc, status: '草图:圆弧 R${r.round()}'); + } + + /// 提交矩形(对角两点;四边自动水平 / 竖直,共享角点)。 + void _commitSketchRect(SketchSnap a, SketchSnap b) { + SketchDoc d = c.sketch; + final Offset tl = a.pos; + final Offset br = b.pos; + if ((br - tl).distance < 4) return; + final List fresh = []; + String pt(SketchSnap? snap, Offset pos) { + if (snap?.pointId != null) return snap!.pointId!; + final String id = sketchNewId('P', [...d.allIds, ...fresh]); + fresh.add(id); + d = d.upsertPoint(SketchPoint(id: id, x: pos.dx, y: pos.dy)); + return id; + } + + final String p1 = pt(a, tl); + final String p2 = pt(null, Offset(br.dx, tl.dy)); + final String p3 = pt(b, br); + final String p4 = pt(null, Offset(tl.dx, br.dy)); + final String e1 = sketchNewId('E', [...d.allIds, ...fresh]); + final String e2 = sketchNewId('E', [...d.allIds, ...fresh, e1]); + final String e3 = sketchNewId('E', [...d.allIds, ...fresh, e1, e2]); + final String e4 = + sketchNewId('E', [...d.allIds, ...fresh, e1, e2, e3]); + d = d + .upsertEntity(SketchEntity(id: e1, kind: SketchKind.line, p1: p1, p2: p2)) + .upsertEntity(SketchEntity(id: e2, kind: SketchKind.line, p1: p2, p2: p3)) + .upsertEntity(SketchEntity(id: e3, kind: SketchKind.line, p1: p3, p2: p4)) + .upsertEntity( + SketchEntity(id: e4, kind: SketchKind.line, p1: p4, p2: p1)); + final List cons = []; + for (final (SketchConsType typ, String eid2) in <(SketchConsType, String)>[ + (SketchConsType.horizontal, e1), + (SketchConsType.vertical, e2), + (SketchConsType.horizontal, e3), + (SketchConsType.vertical, e4), + ]) { + cons.add(SketchConstraint( + id: sketchNewId('K', [ + ...d.allIds, + ...cons.map((SketchConstraint x) => x.id), + ]), + type: typ, + a: eid2, + )); + } + d = d.copyWith(constraints: [...d.constraints, ...cons]); + final SketchSolveResult r = solveSketch(d); + c.changeSketch((_) => r.doc, status: '草图:矩形(自动水平 / 竖直)'); + } + + /// 编辑驱动尺寸(双击尺寸标签)。 + Future _editSketchDim(SketchDim d) async { + final String? input = await showTextEditDialog( + context, + title: '编辑${sketchDimLabel(d.type)}' + '(${d.type == SketchDimType.angle ? '度' : '像素'})', + initial: d.value.toStringAsFixed(1), + ); + if (input == null || !mounted) return; + final double? v = double.tryParse(input.trim()); + if (v == null || v <= 0) { + c.setStatus('数值无效:请输入正数'); + return; + } + c.setSketchDimValue(d.id, v); + } + + // ===================== 指针事件 ===================== + + /// 按下:进入捏合 / 平移 / 框选 / 手绘 / 连线 / 选择移动。 + void _onPointerDown(PointerDownEvent e, Size size) { + _pointers[e.pointer] = e.localPosition; + if (_pointers.length >= 2) { + _cancelDrafts(); + final List ps = _pointers.values.toList(); + _pinching = true; + _pinchStartDist = math.max(1, (ps[0] - ps[1]).distance); + _pinchStartZoom = c.arch.zoom; + _pinchStartFocal = (ps[0] + ps[1]) / 2; + _pinchStartPan = Offset(c.arch.panX, c.arch.panY); + _primaryPointer = null; + return; + } + _primaryPointer = e.pointer; + _downScreen = e.localPosition; + _touchDownAt = DateTime.now(); + _touchDownPos = e.localPosition; + _touchEmpty = false; + final Offset world = _toWorld(e.localPosition); + final ArchTool tool = c.archTool; + final bool middle = (e.buttons & kMiddleMouseButton) != 0; + final bool secondary = (e.buttons & kSecondaryMouseButton) != 0; + final bool touch = + e.kind == PointerDeviceKind.touch || e.kind == PointerDeviceKind.stylus; + if (middle || secondary) { + _panning = true; + _panStartScreen = e.localPosition; + _panStartPan = Offset(c.arch.panX, c.arch.panY); + return; + } + + if (c.sketchMode) { + _sketchDown(world, e); + return; + } + + if (tool == ArchTool.pen) { + _draft = [world]; + setState(() {}); + return; + } + if (tool == ArchTool.connect) { + // 按住左键画路径:松手后识别为直线 / 折线并吸附到图形边框。 + _connFromId = _shapeAt(world)?.id; + _draft = [world]; + setState(() {}); + return; + } + + // 选择工具:手柄 → 图形 → 空白(鼠标框选 / 触屏平移)。 + final bool ctrl = HardwareKeyboard.instance.isControlPressed; + final ArchShape? soleSel = + c.archSelIds.length == 1 ? c.arch.shapeById(c.archSelId) : null; + if (soleSel != null && !soleSel.isLinear) { + final List hs = archHandleRects(soleSel.rect, c.arch.zoom); + for (int i = 0; i < hs.length; i++) { + if (hs[i].inflate(4 / c.arch.zoom).contains(world)) { + _resizeHandle = i; + _resizeOrigin = soleSel; + _resizeRect = soleSel.rect; + _moveStartWorld = world; + return; + } + } + } + if (soleSel != null && soleSel.isLinear) { + // 折线 / 曲线 / 直线:允许拖动折点(先于整体命中,手柄优先)。 + final List vs = soleSel.type == ArchShapeType.line && + soleSel.a != null && + soleSel.b != null + ? [soleSel.a!, soleSel.b!] + : soleSel.pts; + final double tol = 10 / c.arch.zoom; + for (int i = 0; i < vs.length; i++) { + if ((vs[i] - world).distance <= tol) { + _vertexIndex = i; + _vertexOrigin = soleSel; + _vertexPts = List.of(vs); + setState(() {}); + return; + } + } + } + // 连线折点拖动:所有折点可拖;端点拖到别的图形会重新吸附(松手生效)。 + final ArchConnector? soleConn = c.archSelIds.length == 1 + ? c.arch.connectorById(c.archSelId) + : null; + if (soleConn != null) { + final ArchConnGeometry g = archConnectorGeometry(c.arch, soleConn); + final double tol = 10 / c.arch.zoom; + for (int i = 0; i < g.pts.length; i++) { + if ((g.pts[i] - world).distance <= tol) { + _connVertexOrigin = soleConn; + _connVertexIndex = i; + _connVertexPts = List.of(g.pts); + _connDragTargetId = null; + setState(() {}); + return; + } + } + } + // 尺寸标签:双击进入改值(识别后图形 / 曲线 / 图元可直接编辑尺寸)。 + final (ArchShape, ArchDimKind)? dimHit = + archShapeDimHitAt(c.arch, world, c.arch.zoom); + if (dimHit != null) { + final int now = DateTime.now().millisecondsSinceEpoch; + final bool dbl = now - _lastClickMs < 400 && + (e.localPosition - _lastClickPos).distance < 28; + if (dbl) { + _lastClickMs = 0; + _editDimLabel(dimHit.$1, dimHit.$2); + return; + } + } + final (String?, ArchShape?) hit = _hitTest(world); + final String? id = hit.$1; + final ArchShape? shape = hit.$2; + if (id != null) { + final int now = DateTime.now().millisecondsSinceEpoch; + final bool dbl = now - _lastClickMs < 400 && + (e.localPosition - _lastClickPos).distance < 28; + if (dbl) { + // 双击图形 / 折线曲线 / 连线:进入文字编辑(连线编辑标签)。 + if (shape != null) { + _beginTextEdit(shape); + return; + } + final ArchConnector? cn = c.arch.connectorById(id); + if (cn != null) { + _beginConnLabelEdit(cn); + return; + } + } + if (!c.archSelIds.contains(id)) { + c.selectArch(id, toggle: ctrl); + } else if (ctrl) { + c.selectArch(id, toggle: true); + } + // 拖动已选中的图形 → 批量移动(只移动其中“可移动”的图形)。 + final List movables = [ + for (final String sid in c.archSelIds) + if (c.arch.shapeById(sid) != null) sid, + ]; + if (movables.isNotEmpty) { + _moveIds = movables; + _moveDeltas = null; + _moveStartWorld = world; + } + setState(() {}); + return; + } + // 空白处双击 → 直接新建文本并进入输入(最直白的文字入口)。 + { + final int now = DateTime.now().millisecondsSinceEpoch; + final bool dbl = now - _lastClickMs < 400 && + (e.localPosition - _lastClickPos).distance < 28; + if (dbl) { + _lastClickMs = 0; + final ArchShape textShape = ArchShape( + id: archNewId('T', c.arch.allIds), + type: ArchShapeType.text, + rect: Rect.fromCenter(center: world, width: 180, height: 44), + fill: 0, + stroke: c.archColor, + sw: 0, + text: '', + ); + c.addArchShape(textShape); + _beginTextEdit(textShape); + return; + } + } + // 空白处:鼠标 → 框选;触屏 → 平移(长按转框选)。 + if (!touch) { + _marquee = true; + _mqStart = world; + _mqEnd = world; + setState(() {}); + } else { + _panning = true; + _touchEmpty = true; + _panStartScreen = e.localPosition; + _panStartPan = Offset(c.arch.panX, c.arch.panY); + } + } + + /// 移动:捏合 / 手绘 / 连线 / 移动 / 缩放 / 平移 / 框选。 + void _onPointerMove(PointerMoveEvent e, Size size) { + if (!_pointers.containsKey(e.pointer)) return; + _pointers[e.pointer] = e.localPosition; + + if (_pinching && _pointers.length >= 2) { + final List ps = _pointers.values.toList(); + final double dist = math.max(1, (ps[0] - ps[1]).distance); + final Offset focal = (ps[0] + ps[1]) / 2; + final double nz = + (_pinchStartZoom * dist / _pinchStartDist).clamp(0.15, 4.0).toDouble(); + final Offset worldAtFocal = + (_pinchStartFocal - _pinchStartPan) / _pinchStartZoom; + c.archSetView( + zoom: nz, + panX: focal.dx - worldAtFocal.dx * nz, + panY: focal.dy - worldAtFocal.dy * nz, + ); + return; + } + if (e.pointer != _primaryPointer) return; + final Offset world = _toWorld(e.localPosition); + + if (c.sketchMode) { + _sketchMove(world); + return; + } + + // 触屏长按(原地停顿)转为框选。 + if (_panning && _touchEmpty && !_marquee) { + final bool still = (e.localPosition - _touchDownPos).distance < 10; + final bool held = DateTime.now().difference(_touchDownAt).inMilliseconds > 360; + if (still && held) { + _panning = false; + _marquee = true; + _mqStart = _toWorld(_touchDownPos); + _mqEnd = world; + setState(() {}); + return; + } + } + + if (_draft != null) { + if ((world - _draft!.last).distance > 1.1) { + _draft!.add(world); + setState(() {}); + } + return; + } + if (_connVertexOrigin != null) { + final int last = _connVertexPts.length - 1; + final bool isEndpoint = + _connVertexIndex == 0 || _connVertexIndex == last; + Offset p = world; + if (isEndpoint) { + // 端点:优先吸附到鼠标下的图形边框(可换目标重新吸附),无则脱离。 + final ArchShape? target = _shapeAt(world); + if (target != null) { + p = archNearestBorderPoint(target, world); + _connDragTargetId = target.id; + } else { + _connDragTargetId = null; + if (c.arch.gridSnap) p = archSnapPoint(c.arch, world); + } + } else if (c.arch.gridSnap) { + p = archSnapPoint(c.arch, world); + } + _connVertexPts[_connVertexIndex] = p; + _connVertexUpdated = + _applyConnVertices(_connVertexOrigin!, _connVertexIndex, _connVertexPts); + setState(() {}); + return; + } + if (_resizeHandle != null && _resizeOrigin != null) { + _resizeRect = _resizeFrom(_resizeOrigin!, _resizeHandle!, world); + setState(() {}); + return; + } + if (_vertexPts != null && _vertexOrigin != null) { + _vertexPts![_vertexIndex] = + c.arch.gridSnap ? archSnapPoint(c.arch, world) : world; + setState(() {}); + return; + } + if (_moveIds.isNotEmpty) { + Offset raw = world - _moveStartWorld; + // 正交 / 极轴:先把位移约束到主轴(正交)或极轴角度倍数(极轴)。 + if (c.archOrtho || c.archPolar) { + raw = archConstrainDelta( + raw: raw, + ortho: c.archOrtho, + polar: c.archPolar, + polarDeg: c.archPolarDeg, + ); + Offset delta = raw; + // 正交允许沿活动轴吸附网格;极轴保持角度不做二次吸附。 + if (c.archOrtho && c.arch.gridSnap) { + final ArchShape? primary = c.arch.shapeById(_moveIds.first); + if (primary != null) { + final Offset snapped = + archSnapPoint(c.arch, primary.rect.topLeft + raw); + final Offset sd = snapped - primary.rect.topLeft; + delta = raw.dy == 0 ? Offset(sd.dx, 0) : Offset(0, sd.dy); + } + } + _guideXs = const []; + _guideYs = const []; + final Map deltas = { + for (final String id in _moveIds) id: delta, + }; + _moveDeltas = deltas; + setState(() {}); + return; + } + // 自由模式:磁力对齐线 + 网格回退。 + Rect? union; + for (final String id in _moveIds) { + final ArchShape? sh = c.arch.shapeById(id); + if (sh == null) continue; + final Rect rr = sh.bounds.shift(raw); + union = union == null ? rr : union.expandToInclude(rr); + } + Offset delta = raw; + double? gx; + double? gy; + if (union != null) { + final ArchMoveSnap snap = archSnapMoveDelta( + doc: c.arch, + movingIds: _moveIds.toSet(), + union: union, + rawDelta: raw, + tol: 6 / c.arch.zoom, + gridSnap: c.arch.gridSnap, + ); + delta = snap.delta; + gx = snap.guideX; + gy = snap.guideY; + } + _guideXs = gx == null ? const [] : [gx]; + _guideYs = gy == null ? const [] : [gy]; + final Map deltas = {}; + for (final String id in _moveIds) { + deltas[id] = delta; + } + _moveDeltas = deltas; + setState(() {}); + return; + } + if (_marquee) { + _mqEnd = world; + setState(() {}); + return; + } + if (_panning) { + final Offset d = e.localPosition - _panStartScreen; + c.archSetView(panX: _panStartPan.dx + d.dx, panY: _panStartPan.dy + d.dy); + } + } + + /// 抬起:提交草稿 / 移动 / 缩放 / 框选 / 点击。 + void _onPointerUp(PointerEvent e, Size size) { + final Offset? upPos = _pointers.remove(e.pointer); + if (_pinching) { + if (_pointers.length < 2) _pinching = false; + return; + } + if (e.pointer != _primaryPointer) return; + _primaryPointer = null; + final Offset up = upPos ?? e.localPosition; + final bool moved = (up - _downScreen).distance > 6; + final Offset world = _toWorld(up); + // 干净点击(未拖动)时记录位置:供双击编辑文字 / 标签检测使用。 + if (!moved) { + _lastClickMs = DateTime.now().millisecondsSinceEpoch; + _lastClickPos = up; + } + + if (c.sketchMode) { + _sketchUp(world, moved); + return; + } + + if (_draft != null) { + final List pts = _draft!; + _draft = null; + if (c.archTool == ArchTool.connect) { + _commitConnectorTrajectory(pts); + } else { + _commitInk(pts); + } + setState(() {}); + return; + } + if (_connVertexOrigin != null) { + final int index = _connVertexIndex; + final int last = _connVertexPts.length - 1; + final bool isEndpoint = index == 0 || index == last; + ArchConnector? done = _connVertexUpdated; + final String? targetId = _connDragTargetId; + _connVertexOrigin = null; + _connVertexPts = []; + _connVertexUpdated = null; + _connDragTargetId = null; + if (done != null && isEndpoint) { + // 端点松手:吸附到新图形(更新归属);空白处则脱离为自由端点。 + done = index == 0 + ? done.copyWith(fromId: targetId) + : done.copyWith(toId: targetId); + } + if (done != null) { + final String st = !isEndpoint + ? '编辑连线折点' + : (targetId == null ? '连线端点:已脱离(自由端点)' : '连线端点:已吸附到图形'); + c.updateArchConnector(done, status: st); + } + setState(() {}); + return; + } + if (_resizeHandle != null && _resizeOrigin != null) { + final ArchShape origin = _resizeOrigin!; + final Rect? rect = _resizeRect; + _resizeHandle = null; + _resizeRect = null; + _resizeOrigin = null; + if (rect != null && rect != origin.rect) { + c.updateArchShape(origin.copyWith(rect: rect), status: '调整大小'); + } + setState(() {}); + return; + } + if (_vertexPts != null && _vertexOrigin != null) { + final ArchShape origin = _vertexOrigin!; + final List pts = List.of(_vertexPts!); + _vertexIndex = 0; + _vertexOrigin = null; + _vertexPts = null; + final ArchShape updated = origin.type == ArchShapeType.line + ? origin.copyWith( + a: pts[0], + b: pts[1], + rect: Rect.fromPoints(pts[0], pts[1]), + ) + : origin.copyWith(pts: pts, rect: _ptsBounds(pts)); + c.updateArchShape(updated, status: '编辑折点'); + setState(() {}); + return; + } + if (_moveIds.isNotEmpty) { + final Map? deltas = _moveDeltas; + _moveIds = []; + _moveDeltas = null; + _guideXs = const []; + _guideYs = const []; + if (moved && deltas != null && deltas.isNotEmpty) { + c.moveArchShapes(deltas); + } else { + _lastClickMs = DateTime.now().millisecondsSinceEpoch; + _lastClickPos = up; + } + setState(() {}); + return; + } + if (_marquee) { + final Offset? a = _mqStart; + _marquee = false; + _mqStart = null; + _mqEnd = null; + if (moved && a != null) { + _applyMarquee(Rect.fromPoints(a, world)); + } else { + c.selectArch(null); + _lastClickMs = DateTime.now().millisecondsSinceEpoch; + _lastClickPos = up; + } + setState(() {}); + return; + } + if (_panning) { + _panning = false; + _touchEmpty = false; + if (!moved && !_touchEmpty) { + c.selectArch(null); + _lastClickMs = DateTime.now().millisecondsSinceEpoch; + _lastClickPos = up; + } + } + } + + /// 滚轮:以光标为锚缩放。 + void _onScroll(PointerScrollEvent e, Size size) { + final double factor = math.exp(-e.scrollDelta.dy / 420); + c.archZoomAt(factor, e.localPosition); + } + + /// 框选:选中与矩形相交的图形 / 连线 / 墨迹(隐藏 / 锁定图层跳过)。 + void _applyMarquee(Rect r) { + final List ids = []; + for (final ArchShape s in c.arch.shapes) { + if (!c.arch.isLayerVisible(s.layerId) || c.arch.isLayerLocked(s.layerId)) { + continue; + } + if (s.bounds.overlaps(r)) ids.add(s.id); + } + for (final ArchConnector cn in c.arch.connectors) { + if (!c.arch.isLayerVisible(cn.layerId) || + c.arch.isLayerLocked(cn.layerId)) { + continue; + } + final ArchConnGeometry g = archConnectorGeometry(c.arch, cn); + if (_ptsBounds(g.pts).overlaps(r)) ids.add(cn.id); + } + for (final ArchStroke s in c.arch.strokes) { + if (!c.arch.isLayerVisible(s.layerId) || c.arch.isLayerLocked(s.layerId)) { + continue; + } + if (s.bounds.overlaps(r)) ids.add(s.id); + } + c.selectArchIds(ids); + } + + /// 点集外接矩形。 + Rect _ptsBounds(List pts) { + double l = pts.first.dx, r = l, t = pts.first.dy, b = t; + for (final Offset p in pts) { + if (p.dx < l) l = p.dx; + if (p.dx > r) r = p.dx; + if (p.dy < t) t = p.dy; + if (p.dy > b) b = p.dy; + } + return Rect.fromLTRB(l, t, r, b); + } + + /// 取消所有进行中的草稿(进入捏合 / Esc)。 + void _cancelDrafts() { + _draft = null; + _connFromId = null; + _connVertexOrigin = null; + _connVertexPts = []; + _connVertexUpdated = null; + _moveIds = []; + _moveDeltas = null; + _guideXs = const []; + _guideYs = const []; + _resizeHandle = null; + _resizeRect = null; + _resizeOrigin = null; + _vertexOrigin = null; + _vertexPts = null; + _panning = false; + _touchEmpty = false; + _marquee = false; + _mqStart = null; + _mqEnd = null; + setState(() {}); + } + + /// 键盘:Del 删除选中;Esc 取消;F8 正交;F10 极轴。 + KeyEventResult _onKey(FocusNode node, KeyEvent e) { + if (e is! KeyDownEvent) return KeyEventResult.ignored; + if (e.logicalKey == LogicalKeyboardKey.f8) { + c.setArchOrtho(!c.archOrtho); + return KeyEventResult.handled; + } + if (e.logicalKey == LogicalKeyboardKey.f10) { + c.setArchPolar(!c.archPolar); + return KeyEventResult.handled; + } + if (e.logicalKey == LogicalKeyboardKey.delete || + e.logicalKey == LogicalKeyboardKey.backspace) { + if (c.archSelIds.isNotEmpty && _editId == null) { + c.removeArchSelection(); + return KeyEventResult.handled; + } + } + if (e.logicalKey == LogicalKeyboardKey.escape) { + _cancelDrafts(); + if (_editId == null) c.selectArch(null); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + // ===================== 编辑操作 ===================== + + /// 提交手画连线轨迹:识别为直线 / 折线,端点吸附图形边框。 + void _commitConnectorTrajectory(List pts) { + if (pts.length < 2) return; + double len = 0; + for (int i = 1; i < pts.length; i++) { + len += (pts[i] - pts[i - 1]).distance; + } + if (len < 12) return; + // 优先用图形识别(直线 / 折线带近轴扶正);否则把轨迹简化为折线。 + final ArchRecognition? r = recognizeArchStroke(pts); + List v; + if (r != null && r.type == ArchShapeType.line) { + v = [r.a ?? pts.first, r.b ?? pts.last]; + } else if (r != null && + r.type == ArchShapeType.polyline && + (r.pts?.length ?? 0) >= 2) { + v = List.of(r.pts!); + } else { + v = simplifyArchPolyline(pts); + } + if (v.length < 2) return; + final Offset p0 = v.first; + final Offset p1 = v.last; + final List mids = + v.length > 2 ? v.sublist(1, v.length - 1) : const []; + // 端点吸附:起点优先用按下时命中的图形;终点按松手位置命中。 + final ArchShape? sf = c.arch.shapeById(_connFromId) ?? _shapeAt(p0); + final ArchShape? st = _shapeAt(p1); + final bool snap = c.arch.gridSnap; + final Offset from = sf != null + ? archNearestBorderPoint(sf, p0) + : (snap ? archSnapPoint(c.arch, p0) : p0); + final Offset to = st != null + ? archNearestBorderPoint(st, p1) + : (snap ? archSnapPoint(c.arch, p1) : p1); + _connFromId = null; + if ((to - from).distance < 12) return; + c.addArchConnector(ArchConnector( + id: archNewId('C', c.arch.allIds), + fromId: sf?.id, + from: from, + toId: st?.id, + to: to, + mids: mids, + )); + } + + /// 把折点拖拽结果写回连线(中间折点 / 自由端点)。 + ArchConnector _applyConnVertices( + ArchConnector origin, + int index, + List pts, + ) { + final int last = pts.length - 1; + final List mids = List.of(origin.mids); + Offset from = origin.from; + Offset to = origin.to; + if (index == 0) { + from = pts.first; + } else if (index == last) { + to = pts.last; + } else { + final int mi = index - 1; + if (mi >= 0 && mi < mids.length) mids[mi] = pts[index]; + } + return origin.copyWith(from: from, to: to, mids: mids); + } + + /// 按目标外接框生成图元图形(保持图元自然纵横比)。 + ArchShape _symbolShapeFor(LibSymbol sym, Rect b) { + final Rect nat = symbolNaturalBounds(sym); + double w = math.max(b.width, 24); + double h = nat.width <= 0 ? w : w * nat.height / nat.width; + if (b.height > h) { + h = b.height; + w = nat.height <= 0 ? w : h * nat.width / nat.height; + } + return ArchShape( + id: archNewId('S', c.arch.allIds), + type: ArchShapeType.symbol, + symbolId: sym.id, + rect: Rect.fromCenter(center: b.center, width: w, height: h), + fill: archFillOf(c.archColor), + stroke: c.archColor, + sw: 1.8, + ); + } + + /// 图元库识别命中:按笔迹外接框生成图元图形并播放转化动画。 + void _commitSymbolConversion( + List pts, + LibSymbol sym, { + required Set removeIds, + }) { + final Rect b = _ptsBounds(pts); + _startConversion(pts, _symbolShapeFor(sym, b), removeIds: removeIds); + } + + /// 双击尺寸标签:输入数值直接缩放图形(识别后图形 / 曲线 / 图元)。 + Future _editDimLabel(ArchShape s, ArchDimKind k) async { + final double cur = archShapeDimValue(s, k); + final String? input = await showTextEditDialog( + context, + title: '编辑${archDimKindLabel(k)}(当前 ${cur.toStringAsFixed(1)} mm)', + initial: cur.toStringAsFixed(1), + ); + if (input == null || !mounted) return; + final double? v = double.tryParse(input.trim()); + if (v == null || v <= 0) { + c.setStatus('数值无效:请输入正数'); + return; + } + c.setArchShapeDim(s.id, k, v); + } + + /// 提交手绘:统一按图形识别处理(识别失败保留墨迹),并尝试两笔组合识别。 + void _commitInk(List pts) { + if (pts.length < 5) return; + double len = 0; + for (int i = 1; i < pts.length; i++) { + len += (pts[i] - pts[i - 1]).distance; + } + if (len < 24) return; + + // 图元库组合(回溯):2.5 秒内新笔迹先尝试与「上一步刚生成的图形」 + // 合成图元(如 圆 + 叉 = 指示灯)——即使第一笔已被即时识别成标准图形。 + final String? convId = _lastConvId; + final DateTime? convAt = _lastConvAt; + if (convId != null && + convAt != null && + DateTime.now().difference(convAt).inMilliseconds <= 2500 && + c.arch.shapeById(convId) != null) { + final ArchSymbolMatch? sm = recognizeArchSymbol( + >[_lastConvPts, pts], SymbolCache.all); + if (sm != null) { + final Rect prevRect = c.arch.shapeById(convId)!.rect; + final Rect b = prevRect.expandToInclude(_ptsBounds(pts)); + _lastConvId = null; + _startConversion( + pts, + _symbolShapeFor(sm.symbol, b), + removeIds: {convId}, + ); + return; + } + } + + final ArchRecognition? r = recognizeArchStroke(pts); + if (r == null) { + final ArchStroke st = ArchStroke( + id: archNewId('K', c.arch.allIds), + pts: pts, + color: c.archColor, + ); + c.addArchStroke(st); + // 图元库识别(可扩展):内置识别不了的笔迹先匹配图元库(单笔)。 + final ArchSymbolMatch? sm1 = + recognizeArchSymbol(>[pts], SymbolCache.all); + if (sm1 != null) { + _commitSymbolConversion(pts, sm1.symbol, removeIds: {st.id}); + _lastInkId = null; + _lastInkAt = null; + return; + } + // 两笔组合:先按图元库匹配(如「圆 + 叉 = 指示灯」),再走内置组合。 + final String? prevId = _lastInkId; + final DateTime? prevAt = _lastInkAt; + if (prevId != null && + prevAt != null && + DateTime.now().difference(prevAt).inSeconds <= 10) { + final ArchStroke? prev = c.arch.strokeById(prevId); + if (prev != null) { + final ArchSymbolMatch? sm2 = recognizeArchSymbol( + >[prev.pts, pts], SymbolCache.all); + if (sm2 != null) { + _commitSymbolConversion( + pts, + sm2.symbol, + removeIds: {prevId, st.id}, + ); + _lastInkId = null; + _lastInkAt = null; + return; + } + final ArchRecognition? r2 = + recognizeArchStrokes(>[prev.pts, pts]); + if (r2 != null && r2.type != ArchShapeType.line) { + final ArchShape shape = _snapShapeToGrid(archShapeFromRecognition( + r2, + id: archNewId('S', c.arch.allIds), + color: c.archColor, + )); + _startConversion( + pts, + shape, + removeIds: {prevId, st.id}, + ); + _lastInkId = null; + _lastInkAt = null; + return; + } + } + } + _lastInkId = st.id; + _lastInkAt = DateTime.now(); + return; + } + + _lastInkId = null; + _lastInkAt = null; + + // 手绘箭头两端都落在图形上 → 直接生成吸附连线。 + if (r.type == ArchShapeType.line && r.a != null && r.b != null) { + final ArchShape? sf = _shapeAt(r.a!); + final ArchShape? st = _shapeAt(r.b!); + if (sf != null && st != null && sf.id != st.id) { + c.addArchConnector(ArchConnector( + id: archNewId('C', c.arch.allIds), + fromId: sf.id, + from: archNearestBorderPoint(sf, r.a!), + toId: st.id, + to: archNearestBorderPoint(st, r.b!), + )); + return; + } + } + + final ArchShape shape = + _snapShapeToGrid(archShapeFromRecognition( + r, + id: archNewId('S', c.arch.allIds), + color: c.archColor, + )); + + // 圆柱拼接:与上一段「部件」(顶盖 / 柱体)组合成圆柱。 + final String? partId = _lastPartId; + final ArchRecognition? partRec = _lastPartRec; + final DateTime? partAt = _lastPartAt; + if (partId != null && + partRec != null && + partAt != null && + DateTime.now().difference(partAt).inSeconds <= 10 && + c.arch.shapeById(partId) != null) { + final ArchRecognition? cyl = archCylinderFromRecognitions(partRec, r) ?? + archCylinderFromRecognitions(r, partRec); + if (cyl != null) { + final ArchShape cylShape = _snapShapeToGrid(archShapeFromRecognition( + cyl, + id: archNewId('S', c.arch.allIds), + color: c.archColor, + )); + _startConversion(pts, cylShape, removeIds: {partId}); + _lastPartId = null; + _lastPartRec = null; + _lastPartAt = null; + return; + } + } + + _startConversion(pts, shape); + _lastPartId = shape.id; + _lastPartRec = r; + _lastPartAt = DateTime.now(); + } + + /// 折点拖动的实时预览图形。 + ArchShape? _vertexPreview() { + final ArchShape? origin = _vertexOrigin; + final List? pts = _vertexPts; + if (origin == null || pts == null) return null; + if (origin.type == ArchShapeType.line) { + return origin.copyWith( + a: pts[0], + b: pts[1], + rect: Rect.fromPoints(pts[0], pts[1]), + ); + } + return origin.copyWith(pts: List.of(pts), rect: _ptsBounds(pts)); + } + + /// 识别后按网格吸附图形位置(用户偏好「优先吸附网格」)。 + ArchShape _snapShapeToGrid(ArchShape s) { + if (!c.arch.gridSnap || s.isLinear) return s; + final Offset tl = archSnapPoint(c.arch, s.rect.topLeft); + return s.copyWith( + rect: Rect.fromLTWH(tl.dx, tl.dy, s.rect.width, s.rect.height), + ); + } + + /// 由手柄拖拽计算新外接矩形(圆保持正圆,最小 24px,可吸附网格)。 + Rect _resizeFrom(ArchShape origin, int handle, Offset world) { + final Rect r = origin.rect; + const double minSize = 24; + double l = r.left; + double t = r.top; + double rt = r.right; + double b = r.bottom; + final Offset snapped = + c.arch.gridSnap ? archSnapPoint(c.arch, world) : world; + switch (handle) { + case 0: + l = snapped.dx; + t = snapped.dy; + break; + case 1: + t = snapped.dy; + break; + case 2: + rt = snapped.dx; + t = snapped.dy; + break; + case 3: + rt = snapped.dx; + break; + case 4: + rt = snapped.dx; + b = snapped.dy; + break; + case 5: + b = snapped.dy; + break; + case 6: + l = snapped.dx; + b = snapped.dy; + break; + default: + l = snapped.dx; + } + if ((rt - l) < minSize) { + if (snapped.dx > r.center.dx) { + rt = l + minSize; + } else { + l = rt - minSize; + } + } + if ((b - t) < minSize) { + if (snapped.dy > r.center.dy) { + b = t + minSize; + } else { + t = b - minSize; + } + } + Rect nr = Rect.fromLTRB(l, t, rt, b); + if (origin.type == ArchShapeType.circle) { + final double side = math.max(nr.width, nr.height); + nr = Rect.fromCenter(center: r.center, width: side, height: side); + } + return nr; + } + + /// 开始编辑图形文字(画布内联输入框)。 + void _beginTextEdit(ArchShape s) => _beginEdit(s.id, s.text); + + /// 开始编辑连线标签(画布内联输入框,定位在标签锚点处)。 + void _beginConnLabelEdit(ArchConnector cn) => _beginEdit(cn.id, cn.label); + + /// 开始内联编辑(图形文字 / 连线标签共用)。 + void _beginEdit(String id, String initial) { + _editCtrl?.dispose(); + _editCtrl = TextEditingController(text: initial); + _editFocus?.dispose(); + _editFocus = FocusNode(); + _editFocus!.addListener(() { + if (_editFocus?.hasFocus == false) _commitTextEdit(); + }); + _editId = id; + c.selectArch(id); + setState(() {}); + WidgetsBinding.instance.addPostFrameCallback((_) { + _editFocus?.requestFocus(); + }); + } + + /// 提交文字编辑(图形文字或连线标签)。 + void _commitTextEdit() { + final String? id = _editId; + final TextEditingController? ctrl = _editCtrl; + if (id == null || ctrl == null) return; + _editId = null; + final ArchShape? s = c.arch.shapeById(id); + if (s != null) { + if (s.text != ctrl.text) { + c.updateArchShape(s.copyWith(text: ctrl.text), status: '编辑文字'); + } + } else { + final ArchConnector? cn = c.arch.connectorById(id); + if (cn != null && cn.label != ctrl.text) { + c.updateArchConnector(cn.copyWith(label: ctrl.text), + status: '编辑连线标签'); + } + } + setState(() {}); + } + + // ===================== 构建 ===================== + + /// 构建画布(含内联文字编辑与空状态提示)。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return LayoutBuilder( + builder: (BuildContext ctx, BoxConstraints cons) { + final Size size = Size(cons.maxWidth, cons.maxHeight); + c.setArchViewport(size); + final ArchDoc doc = c.arch; + final Rect? mq = _marquee && _mqStart != null && _mqEnd != null + ? Rect.fromPoints(_mqStart!, _mqEnd!) + : null; + return Focus( + autofocus: true, + onKeyEvent: _onKey, + child: MouseRegion( + cursor: c.archTool == ArchTool.pen + ? SystemMouseCursors.precise + : SystemMouseCursors.basic, + onHover: (PointerHoverEvent e) { + final Offset w = _toWorld(e.localPosition); + final Offset? cur = _cursorWorld; + if (cur == null || (cur - w).distance > 0.4) { + setState(() => _cursorWorld = w); + } + }, + onExit: (_) { + if (_cursorWorld != null) { + setState(() => _cursorWorld = null); + } + }, + child: Listener( + onPointerDown: (PointerDownEvent e) => _onPointerDown(e, size), + onPointerMove: (PointerMoveEvent e) => _onPointerMove(e, size), + onPointerUp: (PointerUpEvent e) => _onPointerUp(e, size), + onPointerCancel: (PointerCancelEvent e) => _onPointerUp(e, size), + onPointerSignal: (PointerSignalEvent e) { + if (e is PointerScrollEvent) _onScroll(e, size); + }, + // 裁剪到画布范围内:避免缩小 / 平移后内容(图形、栅格点、标尺线) + // 溢出到左侧边栏与顶部工具栏(CustomPaint 默认不裁剪)。 + child: ClipRect( + child: Stack( + children: [ + Positioned.fill( + child: CustomPaint( + painter: ArchPainter( + doc: doc, + t: t, + selectedIds: c.archSelIds.toSet(), + conversions: _conversions, + nowMs: _nowMs, + draft: _draft, + penColor: c.archColor, + previewConnector: _connVertexUpdated, + guideXs: _guideXs, + guideYs: _guideYs, + cursorWorld: _cursorWorld, + showRulers: c.archRulers, + moveDeltas: _moveDeltas, + resizeId: + _resizeHandle != null ? _resizeOrigin?.id : null, + resizeRect: _resizeRect, + marquee: mq, + previewShape: _vertexPreview(), + sketchMode: c.sketchMode, + sketchSel: { + ...c.sketchSelIds, + ...c.sketchPendingIds, + }, + sketchPreview: _skPreview(), + sketchSnap: _skLiveSnap?.pos, + ), + ), + ), + if (_editId != null) _textEditorOverlay(t), + if (c.sketchMode + ? c.sketch.isEmpty && _skClicks.isEmpty + : doc.isEmpty && _draft == null) + _emptyHint(t), + ], + ), + ), + ), + ), + ); + }, + ); + } + + /// 内联文字编辑框(覆盖在被编辑图形 / 连线标签锚点上)。 + Widget _textEditorOverlay(Tokens t) { + if (_editId == null) return const SizedBox.shrink(); + final TextEditingController? ctrl = _editCtrl; + if (ctrl == null) return const SizedBox.shrink(); + final double z = c.arch.zoom; + Rect r; + final ArchShape? s = c.arch.shapeById(_editId); + if (s != null) { + r = s.rect; + } else { + final ArchConnector? cn = c.arch.connectorById(_editId); + if (cn == null) return const SizedBox.shrink(); + final ArchConnGeometry g = archConnectorGeometry(c.arch, cn); + r = Rect.fromCenter(center: g.label, width: 170, height: 34); + } + return Positioned( + left: r.left * z + c.arch.panX, + top: r.top * z + c.arch.panY, + width: math.max(90, r.width * z), + height: math.max(30, r.height * z), + child: Material( + color: t.panel, + elevation: 3, + borderRadius: BorderRadius.circular(6), + child: TextField( + controller: ctrl, + focusNode: _editFocus, + autofocus: true, + textAlign: TextAlign.center, + maxLines: null, + style: TextStyle( + color: t.text, + fontSize: 12.5 * z.clamp(0.8, 1.4), + fontWeight: FontWeight.w600, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const [ + 'Microsoft YaHei', + 'Segoe UI', + 'sans-serif', + ], + ), + decoration: const InputDecoration( + border: InputBorder.none, + isDense: true, + contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 6), + ), + onSubmitted: (_) => _commitTextEdit(), + ), + ), + ); + } + + /// 空画布提示(不拦截指针)。 + Widget _emptyHint(Tokens t) { + return IgnorePointer( + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.gesture, size: 46, color: t.dim), + const SizedBox(height: 10), + Text( + c.sketchMode + ? '参数化草图:左侧选「直线 / 圆 / 弧 / 矩形」点两下绘制;' + '选中对象加约束 / 尺寸,拖动实时求解' + : '按住拖动,随手画一个矩形 / 圆 / 箭头 / 折线 / 曲线,松手自动识别', + style: TextStyle(color: t.sub, fontSize: 13), + ), + const SizedBox(height: 6), + Text( + '文字:双击空白处或图形直接输入;也可以从左侧「图形库」插入', + style: TextStyle(color: t.dim, fontSize: 11.5), + ), + ], + ), + ), + ); + } +} diff --git a/lib/ui/brand_menu.dart b/lib/ui/brand_menu.dart new file mode 100644 index 0000000..f8cd515 --- /dev/null +++ b/lib/ui/brand_menu.dart @@ -0,0 +1,429 @@ +/// 左上角品牌按钮 +「EDC|易得设计」设计合集菜单。 +/// +/// 点开左上角 logo:菜单从 logo **下方**下拉展开(不遮挡 logo)。 +/// 菜单由模块注册表驱动:首页入口 + 已开放模块(可进入/新建)+ +/// 未开放模块(灰色显示,无「规划中」字样)+ 底部「软件设置」。 +/// 具体动作由外壳(AppShell)通过 [BrandMenuButton.onCommand] 执行: +/// 命令为 `_home` / `_settings` / 模块 id。 +library; + +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 'app_logo.dart'; + +/// 品牌按钮:logo + 当前模块名,点击在下方弹出合集菜单。 +class BrandMenuButton extends StatelessWidget { + /// 构造品牌按钮。 + const BrandMenuButton({ + super.key, + required this.controller, + required this.onCommand, + this.scale = 1.0, + this.compact = false, + }); + + /// 全局应用控制器。 + final AppController controller; + + /// 菜单命令回调(`_home` / `_settings` / 模块 id)。 + final Future Function(String cmd) onCommand; + + /// 工具栏缩放系数(触屏平台整体缩小)。 + final double scale; + + /// 紧凑布局(隐藏副标题)。 + final bool compact; + + /// 当前模块名(首页显示「设计合集」)。 + String get _label { + final EdcModule? m = moduleOf(controller.appMode); + return m == null ? '设计合集' : '${m.name}设计'; + } + + /// 构建按钮。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + final BorderRadius radius = BorderRadius.circular(10); + return Tooltip( + message: 'EDC|易得设计:设计合集', + child: Material( + color: t.panel, + borderRadius: radius, + child: InkWell( + onTap: () => _open(context), + borderRadius: radius, + hoverColor: t.accent.withValues(alpha: 0.08), + child: Container( + // 高度只由内容决定:去掉上下留白(按钮高度 = 内容高度)。 + padding: EdgeInsets.only(left: 9 * scale, right: 9 * scale), + decoration: BoxDecoration( + borderRadius: radius, + border: Border.all(color: t.line2), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + AppLogo(size: (compact ? 22 : 24) * scale), + SizedBox(width: 7 * scale), + Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _label, + style: TextStyle( + color: t.text, + fontSize: (compact ? 12.5 : 13) * scale, + fontWeight: FontWeight.w700, + letterSpacing: 0.5 * scale, + height: 1.1, + ), + ), + if (!compact) + Text( + 'Easy Design Collection', + style: TextStyle( + color: t.dim, + fontSize: 9.5 * scale, + height: 1.1, + ), + ), + ], + ), + SizedBox(width: 4 * scale), + Icon(Icons.arrow_drop_down, color: t.sub, size: 17 * scale), + ], + ), + ), + ), + ), + ); + } + + /// 弹出合集菜单(logo 下方下拉,不遮挡 logo)。 + Future _open(BuildContext context) async { + final RenderBox button = context.findRenderObject()! as RenderBox; + final OverlayState overlay = Overlay.of(context); + final RenderBox overlayBox = + overlay.context.findRenderObject()! as RenderBox; + final Offset tl = button.localToGlobal(Offset.zero, ancestor: overlayBox); + final Offset br = button.localToGlobal( + button.size.bottomRight(Offset.zero), + ancestor: overlayBox); + const double menuW = 204; + final double left = tl.dx + .clamp(8.0, math.max(8.0, overlayBox.size.width - menuW - 8)); + final double top = br.dy + 6; + final Object? picked = await showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: '关闭菜单', + barrierColor: Colors.black.withValues(alpha: 0.06), + transitionDuration: const Duration(milliseconds: 150), + pageBuilder: (BuildContext ctx, Animation a1, + Animation a2) => + const SizedBox.shrink(), + transitionBuilder: (BuildContext ctx, Animation anim, + Animation sec, Widget child) { + final Animation curved = + CurvedAnimation(parent: anim, curve: Curves.easeOutCubic); + return Stack( + children: [ + Positioned( + left: left, + top: top, + child: FadeTransition( + opacity: curved, + child: ScaleTransition( + scale: Tween(begin: 0.96, end: 1).animate(curved), + alignment: Alignment.topLeft, + child: _panel(ctx), + ), + ), + ), + ], + ); + }, + ); + if (picked is String && context.mounted) { + await onCommand(picked); + } + } + + /// 菜单底部「软件设置」入口。 + Widget _settingsItem(BuildContext context) { + final Tokens t = context.tok; + return InkWell( + onTap: () => Navigator.of(context).pop('_settings'), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + child: Row( + children: [ + Container( + width: 30, + height: 30, + alignment: Alignment.center, + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: t.line), + ), + child: Icon(Icons.settings_outlined, size: 17, color: t.sub), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('软件设置', + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: FontWeight.w600, + )), + Text('外观 · 网格 · 更新', + style: TextStyle(color: t.dim, fontSize: 10.5)), + ], + ), + ), + Icon(Icons.chevron_right, size: 16, color: t.dim), + ], + ), + ), + ); + } + + /// 菜单面板(品牌头部 + 首页 + 模块注册表 + 未开放模块 + 软件设置)。 + Widget _panel(BuildContext context) { + final Tokens t = context.tok; + final bool atHome = controller.appMode == AppMode.home; + final String? curId = moduleOf(controller.appMode)?.id; + final double maxH = math.max( + 180, + MediaQuery.sizeOf(context).height - 120, + ); + return Material( + color: t.dialog, + elevation: 14, + borderRadius: BorderRadius.circular(14), + child: Container( + width: 204, + constraints: BoxConstraints(maxHeight: maxH), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all(color: t.line2), + ), + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + 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(), + Text('v$kAppVersion', + style: TextStyle(color: t.dim, fontSize: 10)), + ], + ), + ), + Divider(height: 1, thickness: 1, color: t.line), + const SizedBox(height: 6), + // 首页(空白启动工作台)。 + _homeItem(context, atHome), + 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), + Divider(height: 1, thickness: 1, color: t.line), + // 未开放模块:仅灰色显示。 + for (final EdcModule m in kModules) + if (!m.available) _soon(context, m), + const SizedBox(height: 6), + Divider(height: 1, thickness: 1, color: t.line), + const SizedBox(height: 4), + _settingsItem(context), + const SizedBox(height: 4), + ], + ), + ), + ), + ); + } + + /// 「首页」条目。 + Widget _homeItem(BuildContext context, bool current) { + final Tokens t = context.tok; + return InkWell( + onTap: () => Navigator.of(context).pop('_home'), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), + child: Row( + children: [ + Container( + width: 30, + height: 30, + alignment: Alignment.center, + decoration: BoxDecoration( + color: current ? t.accent.withValues(alpha: 0.16) : t.panel2, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: current ? t.accent : t.line), + ), + child: + Icon(Icons.home_outlined, size: 17, color: current ? t.accent : t.sub), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '首页', + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: + current ? FontWeight.w700 : FontWeight.w600, + ), + ), + Text('新建 · 打开 · 最近', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10.5)), + ], + ), + ), + if (current) Icon(Icons.check_circle, size: 16, color: t.accent), + ], + ), + ), + ); + } + + /// 已开放模块条目(点按 = 进入该模块并新建文档)。 + Widget _item( + BuildContext context, + EdcModule m, { + required bool current, + }) { + final Tokens t = context.tok; + return InkWell( + onTap: () => Navigator.of(context).pop(m.id), + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7), + child: Row( + children: [ + Container( + width: 30, + height: 30, + alignment: Alignment.center, + decoration: BoxDecoration( + color: current + ? t.accent.withValues(alpha: 0.16) + : Color(m.accent).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: current ? t.accent : t.line), + ), + child: Icon(m.icon, + size: 17, color: current ? t.accent : Color(m.accent)), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${m.name}设计', + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: + current ? FontWeight.w700 : FontWeight.w600, + ), + ), + Text( + m.blurb, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10.5), + ), + ], + ), + ), + if (current) Icon(Icons.check_circle, size: 16, color: t.accent), + ], + ), + ), + ); + } + + /// 未开放模块:仅灰色显示(不可点)。 + Widget _soon(BuildContext context, EdcModule m) { + final Tokens t = context.tok; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + child: Row( + children: [ + Container( + width: 26, + height: 26, + alignment: Alignment.center, + decoration: BoxDecoration( + color: t.panel2.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(7), + border: Border.all(color: t.line.withValues(alpha: 0.6)), + ), + child: Icon(m.icon, size: 15, color: t.dim.withValues(alpha: 0.75)), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(m.name, + style: TextStyle( + color: t.dim.withValues(alpha: 0.75), + fontSize: 12, + )), + Text(m.blurb, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: t.dim.withValues(alpha: 0.55), + fontSize: 10, + )), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index d6ff43a..b9bce76 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -4,7 +4,7 @@ // 向下通过 AppController 读写项目状态、通过 dart:io 访问文件系统。 // 包含: // · 通用消息提示(showMessage); -// · .seq.json 文件浏览/保存对话框(FileBrowserDialog / pickFile); +// · .edc.json 文件浏览/保存对话框(FileBrowserDialog / pickFile); // · 动作编辑、依赖编辑、文档设置、帮助中心等业务对话框。 import 'dart:io'; import 'dart:math' as math; @@ -14,12 +14,15 @@ import 'package:flutter/material.dart' hide Action; import '../license/license_service.dart'; import '../model/models.dart'; import '../model/units.dart'; +import '../modules/module_registry.dart'; import '../persistence/android_docs.dart'; import '../persistence/storage.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; +import '../update/update_service.dart'; import '../version.dart'; import 'app_logo.dart'; +import 'update_dialog.dart'; // ===================== 对话框等比缩放 ===================== @@ -70,7 +73,7 @@ Future showMessage(BuildContext context, String title, String message) { // ===================== 文件浏览 / 保存对话框 ===================== -/// 文件浏览对话框:用于打开或另存为文件(工程 `.seq.json`、导出 `.svg` / `.png`)。 +/// 文件浏览对话框:用于打开或另存为文件(设计文档 `.seq.json` / `.arch.json`、导出 `.svg` / `.png` / `.dxf`)。 /// /// [saveMode] 为 true 时进入保存流程,否则为打开流程;[suffix] 决定文件过滤 /// 与保存时自动补全的后缀;[defaultName] 为保存模式的默认文件名。 @@ -80,7 +83,7 @@ class FileBrowserDialog extends StatefulWidget { required this.saveMode, this.initialPath, this.defaultName, - this.suffix = '.seq.json', + this.suffix = '.edc.json', }); /// 是否为保存模式(true = 另存为,false = 打开)。 @@ -89,7 +92,7 @@ class FileBrowserDialog extends StatefulWidget { final String? initialPath; /// 保存模式的默认文件名(如 `装配线节拍.svg`)。 final String? defaultName; - /// 文件后缀:过滤目录列表并自动补全用户输入(如 `.svg` / `.png` / `.seq.json`)。 + /// 文件后缀:过滤目录列表并自动补全用户输入(如 `.svg` / `.png` / `.edc.json`)。 final String suffix; /// 创建文件浏览对话框对应的状态对象。 @@ -115,7 +118,7 @@ class _FileBrowserDialogState extends State { final String base = widget.defaultName ?? (widget.initialPath != null && widget.initialPath!.isNotEmpty ? widget.initialPath!.split(RegExp(r'[\\/]')).last - : '节拍方案${widget.suffix}'); + : '未命名设计${widget.suffix}'); _name = TextEditingController(text: base); _bootstrap(); } @@ -175,7 +178,7 @@ class _FileBrowserDialogState extends State { String _ensureSuffix(String raw) { String n = raw.trim(); if (n.isEmpty) return n; - const List known = ['.seq.json', '.json', '.svg', '.png']; + const List known = ['.arch.json', '.edc.json', '.seq.json', '.json', '.svg', '.png', '.dxf']; for (final String k in known) { if (n.toLowerCase().endsWith(k)) { if (k == widget.suffix) return n; @@ -193,7 +196,15 @@ class _FileBrowserDialogState extends State { final List all = _dir.listSync(); _entries = all.where((FileSystemEntity e) { if (e is Directory) return true; - return e.path.toLowerCase().endsWith(widget.suffix.toLowerCase()); + final String p = e.path.toLowerCase(); + // 设计文档同时兼容旧的 .edc.json / .seq.json;其它后缀按后缀精确过滤。 + if (widget.suffix.toLowerCase().contains('json')) { + return p.endsWith('.edc.json') || + p.endsWith('.seq.json') || + p.endsWith('.arch.json') || + p.endsWith('.json'); + } + return p.endsWith(widget.suffix.toLowerCase()); }).toList() ..sort((FileSystemEntity a, FileSystemEntity b) { final bool ad = a is Directory; @@ -403,13 +414,13 @@ class _FileBrowserDialogState extends State { /// 打开文件选择对话框并返回所选路径。 /// /// [save] 决定保存或打开模式;[suffix] 决定文件过滤与自动补全的后缀 -/// (`.seq.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。 +/// (`.edc.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。 Future pickFile( BuildContext context, { required bool save, String? initialPath, String? defaultName, - String suffix = '.seq.json', + String suffix = '.edc.json', }) { return showDialog( context: context, @@ -447,7 +458,7 @@ class _SaveLocationDialogState extends State { super.initState(); final Map s = AndroidDocs.settings(); _base = s['base'] ?? 'documents'; - _folder = TextEditingController(text: s['folder'] ?? 'SequenceDiagram'); + _folder = TextEditingController(text: s['folder'] ?? AndroidDocs.defaultFolder); } @override @@ -513,7 +524,7 @@ class _SaveLocationDialogState extends State { } } -/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/SequenceDiagram)。 +/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/EDC,兼容旧目录 SequenceDiagram)。 /// /// - 保存模式:显示当前保存位置(可点「更改位置」修改),输入文件名自动补全后缀; /// - 打开模式:列出目录中匹配后缀的文件,点选返回文件名。 @@ -580,7 +591,7 @@ class _AndroidFileDialogState extends State { String _ensureSuffix(String raw) { String n = raw.trim(); if (n.isEmpty) return n; - const List known = ['.seq.json', '.json', '.svg', '.png']; + const List known = ['.arch.json', '.edc.json', '.seq.json', '.json', '.svg', '.png', '.dxf']; for (final String k in known) { if (n.toLowerCase().endsWith(k)) { if (k == widget.suffix) return n; @@ -2036,6 +2047,442 @@ class _StationRowState extends State<_StationRow> { /// 帮助中心对话框:以四个标签页展示快速开始、快捷键、 /// 双视图说明以及单位与导出等信息。 +/// 软件设置:集中设置入口(外观 / 文档默认 / 架构图网格 / 更新)。 +/// +/// 从左上角「EDC|易得设计」菜单底部的「软件设置」打开;文档级的完整设置 +/// (单位 / 循环 / 相位等)仍在「文档设置」(F2 / 左侧栏)里。 +class SoftwareSettingsDialog extends StatefulWidget { + /// 构造软件设置对话框。 + const SoftwareSettingsDialog({super.key, required this.controller}); + + /// 全局应用控制器。 + final AppController controller; + + /// 创建状态对象。 + @override + State createState() => _SoftwareSettingsDialogState(); +} + +/// 软件设置对话框状态。 +class _SoftwareSettingsDialogState extends State { + /// 控制器快捷访问。 + AppController get c => widget.controller; + + /// 检查更新:发现新版本直接弹更新对话框。 + Future _checkUpdate() async { + c.setStatus('正在检查更新…'); + try { + final UpdateInfo? info = await UpdateService.check(); + if (!mounted) return; + if (info == null) { + c.setStatus('已是最新版本(v$kAppVersion)'); + await showMessage(context, '检查更新', '当前已是最新版本(v$kAppVersion)。'); + return; + } + await showDialog( + context: context, + builder: (_) => UpdateDialog(controller: c, info: info), + ); + } catch (e) { + if (mounted) await showMessage(context, '检查更新失败', '$e'); + } + } + + /// 渲染设置表单。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return Dialog( + backgroundColor: t.dialog, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + child: scaledDialogBox( + context, + 680, + 600, + Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text('软件设置', + style: TextStyle( + fontSize: 17, fontWeight: FontWeight.w700, color: t.text)), + const SizedBox(width: 14), + Text('外观 / 文档默认 / 架构图网格 / 更新', + style: TextStyle(fontSize: 11, color: t.dim)), + const Spacer(), + Text('v$kAppVersion', style: TextStyle(fontSize: 11, color: t.dim)), + ], + ), + const Divider(height: 24), + Expanded( + child: ListView( + children: [ + _section(t, '外观'), + Row( + children: [ + Expanded( + child: _optCard( + t, + active: c.brightness == Brightness.light, + title: '浅色主题', + subtitle: '白底 · 打印 / 工艺卡友好', + onTap: () => c.setTheme(Brightness.light), + ), + ), + const SizedBox(width: 10), + Expanded( + child: _optCard( + t, + active: c.brightness == Brightness.dark, + title: '深色主题', + subtitle: '暗光环境护眼', + onTap: () => c.setTheme(Brightness.dark), + ), + ), + ], + ), + const SizedBox(height: 18), + _section(t, '文档默认'), + _rowSwitch( + t, + '保留空泳道', + '动作全部移走的泳道保留(序号不变;关闭则自动移除)', + c.project.keepEmptyLanes, + (bool v) => c.setKeepEmptyLanes(v), + ), + _rowSwitch( + t, + '自动保存', + '保存过一次路径后按间隔写回文件(同步 .bak 备份)', + c.project.autoSaveEnabled, + (bool v) => c.setAutoSave(enabled: v), + ), + if (c.project.autoSaveEnabled) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Text('间隔', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 10), + for (final int m in [1, 5, 10, 30]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: _chip( + t, + '$m 分钟', + c.project.autoSaveMinutes == m, + () => c.setAutoSave(minutes: m), + ), + ), + ], + ), + ), + const SizedBox(height: 10), + _section(t, '架构图网格'), + _rowSwitch( + t, + '吸附网格', + '识别 / 移动 / 缩放优先对位到网格', + c.arch.gridSnap, + (bool v) => c.setArchGrid(snap: v), + ), + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Text('粒度', style: TextStyle(color: t.sub, fontSize: 11)), + const SizedBox(width: 10), + for (final double g in [10, 20, 40, 80]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: _chip( + t, + '${g.round()} px', + c.arch.gridSize == g, + () => c.setArchGrid(size: g), + ), + ), + ], + ), + ), + const SizedBox(height: 18), + _section(t, '更新'), + Row( + children: [ + Expanded( + child: Text('当前版本 v$kAppVersion;检查到新版本可直接升级。', + style: TextStyle(color: t.dim, fontSize: 11)), + ), + OutlinedButton( + onPressed: _checkUpdate, + child: const Text('检查更新'), + ), + ], + ), + ], + ), + ), + const Divider(height: 24), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + FilledButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('完成'), + ), + ], + ), + ], + ), + ), + ), + ); + } + + /// 小节标题。 + Widget _section(Tokens t, String s) => Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + s, + style: TextStyle( + color: t.text2, + fontSize: 12.5, + fontWeight: FontWeight.w700, + ), + ), + ); + + /// 选项卡片(主题等二选一)。 + Widget _optCard( + Tokens t, { + required bool active, + required String title, + required String subtitle, + required VoidCallback onTap, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.14) : t.panel2, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: active ? t.accent : t.line, + width: active ? 1.3 : 1, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + color: active ? t.accent : t.text, + fontSize: 12.5, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text(subtitle, style: TextStyle(color: t.dim, fontSize: 10.5)), + ], + ), + ), + ); + } + + /// 开关行。 + Widget _rowSwitch( + Tokens t, + String title, + String desc, + bool value, + ValueChanged onChanged, + ) { + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, + style: TextStyle( + color: t.text, fontSize: 12, fontWeight: FontWeight.w600)), + Text(desc, + style: TextStyle(color: t.dim, fontSize: 10.5, height: 1.4)), + ], + ), + ), + Switch( + value: value, + onChanged: onChanged, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + ); + } + + /// 粒度 / 间隔小圆片。 + Widget _chip(Tokens t, String label, bool active, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(7), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 4), + decoration: BoxDecoration( + color: active ? t.accent.withValues(alpha: 0.16) : t.panel2, + borderRadius: BorderRadius.circular(7), + border: Border.all(color: active ? t.accent : t.line), + ), + child: Text( + label, + style: TextStyle( + color: active ? t.accent : t.sub, + fontSize: 10.5, + fontWeight: active ? FontWeight.w700 : FontWeight.w500, + ), + ), + ), + ); + } +} + +/// 通用文本编辑对话框(图形文字 / 连线标签共用)。 +/// +/// 返回新文本;取消返回 null。 +/// 「打开文档…」的文档类型选择:列出全部模块(未开放灰显不可选)。 +/// +/// 返回所选模块;用户取消返回 null。 +Future showDocumentTypeDialog(BuildContext context) async { + return showDialog( + context: context, + builder: (BuildContext ctx) { + final Tokens t = ctx.tok; + return AlertDialog( + backgroundColor: t.dialog, + title: Text('打开文档', + style: TextStyle( + color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), + content: SizedBox( + width: 400, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final EdcModule m in kModules) + InkWell( + onTap: m.available ? () => Navigator.pop(ctx, m) : null, + borderRadius: BorderRadius.circular(9), + child: Opacity( + opacity: m.available ? 1 : 0.5, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 8), + child: Row( + children: [ + Container( + width: 30, + height: 30, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Color(m.accent).withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(8), + ), + child: + Icon(m.icon, size: 17, color: Color(m.accent)), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(m.name, + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: FontWeight.w600, + )), + Text( + '文档后缀 ${m.suffix}' + '${m.available ? '' : ' · 未开放'}', + style: TextStyle( + color: t.dim, fontSize: 10.5), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), child: const Text('取消')), + ], + ); + }, + ); +} + +Future showTextEditDialog( + BuildContext context, { + required String title, + required String initial, +}) async { + final TextEditingController ctrl = TextEditingController(text: initial); + final String? result = await showDialog( + context: context, + builder: (BuildContext ctx) { + final Tokens t = ctx.tok; + return AlertDialog( + backgroundColor: t.dialog, + title: Text(title, + style: TextStyle( + color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), + content: SizedBox( + width: 380, + child: TextField( + controller: ctrl, + autofocus: true, + minLines: 1, + maxLines: 4, + style: TextStyle(color: t.text, fontSize: 13), + decoration: InputDecoration( + hintText: '输入文字(可多行)', + hintStyle: TextStyle(color: t.dim, fontSize: 12), + filled: true, + fillColor: t.panel2, + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + onSubmitted: (String v) => Navigator.of(ctx).pop(v), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), child: const Text('取消')), + FilledButton( + onPressed: () => Navigator.of(ctx).pop(ctrl.text), + child: const Text('确定')), + ], + ); + }, + ); + ctrl.dispose(); + return result; +} + class HelpDialog extends StatelessWidget { const HelpDialog({super.key}); @@ -2084,7 +2531,7 @@ class HelpDialog extends StatelessWidget { children: [ // 目标:完成方案的搭建与动作的增删改。 _section(t, >[ - ['我要新建方案', '顶部「新建」创建空白节拍;「打开」载入 .seq.json。'], + ['我要新建方案', '顶部「新建」创建空白设计;「打开」按时序 / 架构模块分别载入 .seq.json / .arch.json(兼容旧版 .edc.json)。'], ['我要先看看示例', '首次启动载入 5 个动作的示例节拍(装配线节拍),可直接修改。'], ['我要新增动作', '双击画布空白处在点击相位新增;或左侧「新建」在 0° 新增(默认最外层)。'], ['我要删除动作', '选中后:左侧「删除」/ 行内删除图标 / Delete 键 / 右键菜单;至少保留一个动作 / 泳道。'], @@ -2129,7 +2576,7 @@ class HelpDialog extends StatelessWidget { ['我要导出 SVG', '顶部「导出」下拉菜单 →「导出 SVG」:矢量、分层、带语义 id 与 data-*,可直接进工艺卡 / MES。'], ['我要导出 PNG', '顶部「导出」下拉菜单 →「导出 PNG」:按 2 倍像素比导出当前视图为位图。'], ['我要导出 drawio', '流程图视图专用:顶部「导出」→「导出 drawio」,输出 diagrams.net(draw.io)可继续编辑的工程文件。'], - ['我要保存 / 恢复', '「保存」写入 .seq.json 并生成 .bak;每 5 秒自动快照(异常退出可恢复);F2 文档设置中可开启「自动保存」(默认每 10 分钟一次,需先手动保存过一次路径)。'], + ['我要保存 / 恢复', '「保存」按时序 / 架构模块分别写入 .seq.json / .arch.json 并生成 .bak;每 5 秒自动快照(异常退出可恢复);「软件设置」中可开启「自动保存」(默认每 10 分钟一次,需先手动保存过一次路径)。'], ]), // 目标:调整界面与使用快捷键。 _section(t, >[ @@ -2222,10 +2669,10 @@ class HelpDialog extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('时序图设计 · Sequence Diagram Studio', + Text('EDC|易得设计 · Easy Design Collection', style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), const SizedBox(height: 4), - Text('V1.3.4(${android ? '安卓版' : 'Windows 版'})', + Text('V$kAppVersion(${android ? '安卓版' : 'Windows 版'})', style: TextStyle(color: t.dim, fontSize: 12)), ], ), @@ -2243,9 +2690,9 @@ class HelpDialog extends StatelessWidget { // 注意:绝不能展示「期望授权串」——它等同于 .lic 内容,公开即可被绕过授权。 row('本机 MAC', info.mac ?? '读取失败'), row('版权声明', 'Copyright © 2026 EDC(Easy Design Collection)呆头鹅。保留所有权利。'), - row('产品简介', '面向 PLC 流程节拍 / 相位角设计的设计工具:条形 / 圆周 / 流程图三视图、' - 'FS / SS 依赖与关键路径、泳道加宽(多槽位)与空泳道策略、依赖走线可调、' - '支持导出 SVG / PNG / drawio,成果可直接进工艺卡与 MES。'), + row('产品简介', '设计合集(Easy Design Collection):时序图设计面向 PLC 流程节拍 / ' + '相位角设计(条形 / 圆周 / 流程图三视图、FS / SS 依赖与关键路径、泳道加宽);' + '架构图设计支持手绘识别标准图形、正交连线与标签;支持导出 SVG / PNG / drawio。'), const SizedBox(height: 6), // 官网入口(点击导航到 sincos.cc)。 Row( @@ -2316,7 +2763,7 @@ class HelpDialog extends StatelessWidget { ), const SizedBox(height: 8), guideLine('本版面向应用商店分发,无需授权,全部功能可用。'), - guideLine('保存 / 导出文件位于「文件管理」可见的公共目录(默认 Documents/SequenceDiagram,' + guideLine('保存 / 导出文件位于「文件管理」可见的公共目录(默认 Documents/EDC,' '可在保存对话框中更改位置)。'), ], ), diff --git a/lib/ui/home_view.dart b/lib/ui/home_view.dart new file mode 100644 index 0000000..9d96e4d --- /dev/null +++ b/lib/ui/home_view.dart @@ -0,0 +1,414 @@ +/// 首页(空白启动工作台):新建文档网格 + 打开文档 + 最近打开。 +/// +/// 触屏优先设计:大尺寸卡片与点按区(≥44px)、整页可滚动、不依赖悬停; +/// 手指 / 触控笔 / 鼠标三种输入一致可用(与画布体验保持一致)。 +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 'app_logo.dart'; +import 'update_icon.dart'; + +/// 首页视图。 +class HomeView extends StatefulWidget { + /// 构造首页;各回调由外壳(AppShell)注入,负责实际的文档流程。 + const HomeView({ + super.key, + required this.controller, + required this.onNewModule, + required this.onOpenDocument, + required this.onOpenRecent, + required this.onOpenSettings, + required this.onOpenHelp, + }); + + /// 全局控制器(只读展示用)。 + final AppController controller; + + /// 新建某模块文档。 + final void Function(EdcModule module) onNewModule; + + /// 「打开文档…」(先选类型再选文件)。 + final VoidCallback onOpenDocument; + + /// 打开最近文件。 + final void Function(EdcModule module, RecentDoc doc) onOpenRecent; + + /// 软件设置。 + final VoidCallback onOpenSettings; + + /// 帮助中心。 + final VoidCallback onOpenHelp; + + /// 创建状态。 + @override + State createState() => _HomeViewState(); +} + +/// 首页状态:异步加载最近打开列表。 +class _HomeViewState extends State { + List _recent = const []; + + /// 初始化:加载最近打开。 + @override + void initState() { + super.initState(); + _loadRecent(); + } + + Future _loadRecent() async { + final List list = await RecentStore.load(); + if (!mounted) return; + setState(() => _recent = list); + } + + Future _clearRecent() async { + await RecentStore.clear(); + if (!mounted) return; + setState(() => _recent = const []); + } + + Future _removeRecent(RecentDoc doc) async { + await RecentStore.remove(doc.path); + if (!mounted) return; + setState(() { + _recent = [ + for (final RecentDoc r in _recent) + if (r.path != doc.path) r, + ]; + }); + } + + /// 构建。 + @override + Widget build(BuildContext context) { + final Tokens t = context.tok; + return Scaffold( + backgroundColor: t.bg, + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 980), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(28, 26, 28, 30), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _header(t), + const SizedBox(height: 22), + _sectionTitle(t, '新建文档', '选择要设计的文档类型'), + const SizedBox(height: 12), + Wrap( + spacing: 14, + runSpacing: 14, + children: [ + for (final EdcModule m in kModules) + _moduleCard(t, m), + ], + ), + const SizedBox(height: 24), + _sectionTitle(t, '打开已有文档', '支持 .seq.json / .arch.json(兼容旧版 .edc.json)'), + const SizedBox(height: 12), + Row( + children: [ + FilledButton.icon( + onPressed: widget.onOpenDocument, + icon: const Icon(Icons.folder_open, size: 18), + label: const Text('打开文档…'), + style: FilledButton.styleFrom( + minimumSize: const Size(148, 46), + backgroundColor: t.accent2, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Text( + '也可以把文档文件拖到窗口打开(桌面版);' + '安卓版从公共目录选择。', + style: TextStyle(color: t.dim, fontSize: 11.5), + ), + ), + ], + ), + const SizedBox(height: 24), + Row( + children: [ + Expanded( + child: _sectionTitle( + t, '最近打开', '点按继续上次的设计'), + ), + if (_recent.isNotEmpty) + TextButton( + onPressed: _clearRecent, + style: TextButton.styleFrom( + minimumSize: const Size(64, 36), + ), + child: Text('清空', + style: + TextStyle(color: t.dim, fontSize: 12)), + ), + ], + ), + const SizedBox(height: 8), + if (_recent.isEmpty) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 18), + decoration: BoxDecoration( + color: t.panel.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line), + ), + child: Text( + '还没有打开过文档。从上面选一个类型开始吧。', + style: TextStyle(color: t.dim, fontSize: 12), + ), + ) + else + for (final RecentDoc r in _recent) _recentRow(t, r), + ], + ), + ), + ), + ), + ), + ); + } + + /// 顶部:品牌 + 设置 / 帮助 / 检查更新。 + Widget _header(Tokens t) { + return Row( + children: [ + const AppLogo(size: 46), + const SizedBox(width: 14), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'EDC|易得设计', + style: TextStyle( + color: t.text, + fontSize: 24, + fontWeight: FontWeight.w800, + letterSpacing: 1.2, + ), + ), + Text( + '工程总体设计合集(Easy Design Collection) v$kAppVersion', + style: TextStyle(color: t.dim, fontSize: 11.5), + ), + ], + ), + const Spacer(), + _iconAction(t, Icons.settings_outlined, '软件设置', widget.onOpenSettings), + const SizedBox(width: 8), + _iconAction(t, Icons.help_outline, '帮助中心', widget.onOpenHelp), + const SizedBox(width: 8), + UpdateIcon(size: 36, color: t.sub), + ], + ); + } + + /// 圆形图标按钮(触屏 ≥ 44px 点按区)。 + Widget _iconAction( + Tokens t, IconData icon, String tip, VoidCallback onTap) { + return Tooltip( + message: tip, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + width: 44, + height: 44, + alignment: Alignment.center, + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: t.line), + ), + child: Icon(icon, size: 20, color: t.sub), + ), + ), + ); + } + + /// 分区标题。 + Widget _sectionTitle(Tokens t, String title, String subtitle) { + return Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + title, + style: TextStyle( + color: t.text, + fontSize: 15, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(width: 10), + Padding( + padding: const EdgeInsets.only(bottom: 1.5), + child: Text(subtitle, + style: TextStyle(color: t.dim, fontSize: 11)), + ), + ], + ); + } + + /// 模块卡片(未开放:灰显 + 角标,不可点)。 + Widget _moduleCard(Tokens t, EdcModule m) { + final bool ok = m.available; + return InkWell( + onTap: ok ? () => widget.onNewModule(m) : null, + borderRadius: BorderRadius.circular(15), + child: Opacity( + opacity: ok ? 1 : 0.5, + child: Container( + width: 216, + height: 118, + padding: const EdgeInsets.fromLTRB(16, 14, 16, 12), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(15), + border: Border.all( + color: ok ? t.line : t.line2, + width: ok ? 1.1 : 1, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 34, + height: 34, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Color(m.accent).withValues(alpha: 0.16), + borderRadius: BorderRadius.circular(9), + ), + child: Icon(m.icon, size: 19, color: Color(m.accent)), + ), + const Spacer(), + if (!ok) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 7, vertical: 2), + decoration: BoxDecoration( + color: t.panel2, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: t.line2), + ), + child: Text( + '未开放', + style: TextStyle(color: t.dim, fontSize: 10), + ), + ), + ], + ), + const Spacer(), + Text( + m.name, + style: TextStyle( + color: t.text, + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 2), + Text( + m.blurb, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10.5), + ), + ], + ), + ), + ), + ); + } + + /// 最近打开行(整行 ≥ 48px 点按区)。 + Widget _recentRow(Tokens t, RecentDoc r) { + final EdcModule? m = moduleById(r.moduleId); + final Color accent = m == null ? t.accent2 : Color(m.accent); + final DateTime at = r.at; + final String when = + '${at.year}-${_two(at.month)}-${_two(at.day)} ${_two(at.hour)}:${_two(at.minute)}'; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: InkWell( + onTap: m == null ? null : () => widget.onOpenRecent(m, r), + borderRadius: BorderRadius.circular(11), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: t.panel, + borderRadius: BorderRadius.circular(11), + border: Border.all(color: t.line), + ), + child: Row( + children: [ + Container( + width: 32, + height: 32, + alignment: Alignment.center, + decoration: BoxDecoration( + color: accent.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(m?.icon ?? Icons.description_outlined, + size: 17, color: accent), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + r.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: t.text, + fontSize: 12.5, + fontWeight: FontWeight.w600, + ), + ), + Text( + '${m?.name ?? r.moduleId} · ${r.path}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: t.dim, fontSize: 10.5), + ), + ], + ), + ), + const SizedBox(width: 10), + Text(when, style: TextStyle(color: t.dim, fontSize: 10.5)), + const SizedBox(width: 6), + InkWell( + onTap: () => _removeRecent(r), + borderRadius: BorderRadius.circular(8), + child: const Padding( + padding: EdgeInsets.all(6), + child: Icon(Icons.close, size: 15), + ), + ), + ], + ), + ), + ), + ); + } + + static String _two(int v) => v < 10 ? '0$v' : '$v'; +} diff --git a/lib/update/update_service.dart b/lib/update/update_service.dart index a0a20fc..8166542 100644 --- a/lib/update/update_service.dart +++ b/lib/update/update_service.dart @@ -1,6 +1,8 @@ /// 应用内更新服务:从 Gitea 仓库的「发布(Releases)」检查新版本并下载更新包。 /// -/// 服务器约定(当前仓库 http://124.220.63.9:30000/admin/Sequence-Diagram): +/// 服务器约定(2026-10 起仓库更名 http://124.220.63.9:30000/admin/EasyDesignCollection; +/// 旧名 Sequence-Diagram 在 Gitea 上保留 301 重定向,1.3.4 及更早客户端 +/// 仍能通过旧地址查到更新,随后由本版本的代码切到新地址): /// - 检查:`GET /api/v1/repos/{owner}/{repo}/releases/latest`(公开仓库,无需鉴权); /// - 更新说明:使用 Release 的正文(Markdown); /// - 安装包:使用 Release 附件——安卓为 `.apk`,Windows 为 `.zip`(绿色版整包)。 @@ -20,8 +22,9 @@ class UpdateServer { static const String host = 'http://124.220.63.9:30000'; /// 仓库拥有者。 static const String owner = 'admin'; - /// 仓库名称。 - static const String repo = 'Sequence-Diagram'; + /// 仓库名称(2026-10 由 Sequence-Diagram 改名; + /// 旧名在服务器保留 301 重定向,老客户端查更新不受影响)。 + static const String repo = 'EasyDesignCollection'; /// 版本检查接口(最新正式发布)。 static String get latestReleaseApi => diff --git a/lib/version.dart b/lib/version.dart index aacaa76..803034c 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -2,7 +2,7 @@ /// /// 应用内更新检查用它判断服务器发布的版本是否更新; /// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。 -const String kAppVersion = '1.3.4'; +const String kAppVersion = '1.3.5'; /// 是否要求授权(License)才能导出。 /// diff --git a/pubspec.yaml b/pubspec.yaml index 2b9bd2a..73dfb40 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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.4+20 +version: 1.3.5+26 environment: sdk: ^3.13.3 diff --git a/release/RELEASE_NOTES_v1.2.0.md b/release/RELEASE_NOTES_v1.2.0.md deleted file mode 100644 index 451fc1f..0000000 --- a/release/RELEASE_NOTES_v1.2.0.md +++ /dev/null @@ -1,31 +0,0 @@ -# V1.2.0 更新内容 - -## 新增:应用内更新 - -- 工具栏新增「检查更新」按钮,启动后自动静默检查服务器版本 -- 检测到新版本时按钮出现**红色角标**,点击即可查看更新说明并一键更新 -- 安卓:下载新版本 APK 后直接拉起系统安装器(签名一致,可直接覆盖安装) -- Windows:下载绿色版整包后自动覆盖并重启,无需安装 -- 没有检测到新版本(或安装包)时,会明确提示「当前已是最新版本」 - -## AI 自然语言生成强化 - -- **流式输出**:生成过程实时显示已用时、思考与输出字数,可随时取消 -- **超时保护**:长时间无响应自动中断并给出提示 -- **增量修改**:新增「修改当前工程」模式——在现有时序图上增删改,不再只能整图重画 -- **自动纠错**:模型输出格式有误时自动修复重试;结果自动清洗(非法时长、无效依赖、层号归一化) -- **分层优化**:按并行资源智能分层,避免层数爆炸 - -## 交互与界面 - -- 条形 / 圆周视图的编辑工具栏统一为 7 个按钮(添加 / 编辑 / 复制 / 删除 / 层+ / 层− / 对齐), - 按钮缩小到 60%,条形在左下角、圆周在右上角,不再遮挡预览 -- 右下角预览卡缩小,减少对画布的遮挡 -- **换泳道更顺畅**:拖拽动作到其它泳道不再回弹,可同时前后滑移 -- **手写笔兼容改善**:拖拽端点改时长更稳定,精确点在把手上也能直接拖拽 -- 依赖标签(FS / SS 等)字号缩小、自动避让排布,不再相互压盖;去掉五角星标记 - -## 修复 - -- 修复应用图标:圆环缺口方向修正到正上方(与软件内标志一致),并消除缺口内的残留细线 -- 版本信息统一为「时序图设计」V1.2.0 diff --git a/release/RELEASE_NOTES_v1.2.1.md b/release/RELEASE_NOTES_v1.2.1.md deleted file mode 100644 index 0e882d4..0000000 --- a/release/RELEASE_NOTES_v1.2.1.md +++ /dev/null @@ -1,8 +0,0 @@ -# V1.2.1 更新内容 - -- 更新按钮图标改为全新设计的「升级」样式(圆环 + 上箭头 + 底座横杠), - 与界面整体风格统一,一眼可辨是「检查更新」 -- 更新对话框标题图标同步更新 -- 右下角缩略预览(条形 / 圆周)中的动作线条改细到约 2px,更符合缩略图观感 -- **动作两端改为方头**(带小圆角):条形与圆周视图中的动作长度严格等于 - 真实时长,不再因圆头端帽向外多出而误读;SVG / PNG 导出同步 diff --git a/release/RELEASE_NOTES_v1.2.2.md b/release/RELEASE_NOTES_v1.2.2.md deleted file mode 100644 index a17be1f..0000000 --- a/release/RELEASE_NOTES_v1.2.2.md +++ /dev/null @@ -1,5 +0,0 @@ -# V1.2.2 更新内容 - -- **修复发布版无法联网的问题**:补充网络访问权限(INTERNET),并为更新服务器 - 配置明文 HTTP 白名单——应用内「检查更新」恢复正常(此前 release 版收不到更新提示) -- AI 自然语言生成在发布版中同样恢复可用 diff --git a/release/RELEASE_NOTES_v1.2.3.md b/release/RELEASE_NOTES_v1.2.3.md deleted file mode 100644 index 13d875b..0000000 --- a/release/RELEASE_NOTES_v1.2.3.md +++ /dev/null @@ -1,5 +0,0 @@ -# V1.2.3 更新内容 - -- 修复「适应视图」在条形视图动作较多时的显示问题:画面被缩小后现在会**居中显示**, - 不再偏移到左上角(此前固定 pan=0 导致缩小的内容钉在左上角) -- 圆周视图的适应视图行为保持不变(本来就是居中计算) diff --git a/release/RELEASE_NOTES_v1.3.0.md b/release/RELEASE_NOTES_v1.3.0.md deleted file mode 100644 index b929037..0000000 --- a/release/RELEASE_NOTES_v1.3.0.md +++ /dev/null @@ -1,19 +0,0 @@ -# V1.3.0 更新内容 - -## 全新:流程图视图(第三个视图模式) -- 由时序图**自动生成**:泳道 = 轨道;动作节点显示「序号. 名称 + 时长 · 工位」 -- 依赖连线:绿色实线 FS 顺序 / 琥珀虚线 SS 并行(含偏移角标注) -- 关键路径加粗光晕;无前置依赖的动作自动从「开始」并列引出,形成并行分支 -- 左侧相位阶段栏:相位分区按动作归属竖排显示(每个动作行归属覆盖占比最大的分区) -- 只读预览:点击节点可选中联动动作,修改请回条形 / 圆周视图 - (流程图页的 AI 生成、撤销 / 重做、动作增删、属性编辑等入口会自动置灰) - -## 导出升级 -- 导出按钮合并为下拉菜单:**SVG / PNG 三种视图通用** -- 流程图额外支持导出 **drawio**:可在 diagrams.net(draw.io)中继续编辑, - 泳道、相位分区、依赖关系都保留,方便二次加工 - -## 其他 -- 首次启动的默认示例升级为完整「装配线节拍」(8 个动作 / 3 个工位 / 4 个相位分区) -- 左侧栏「视图模式」只保留条形 / 圆周节拍切换(流程图入口在顶部工具栏) -- 修复若干界面细节与截图工具问题 diff --git a/release/RELEASE_NOTES_v1.3.1.md b/release/RELEASE_NOTES_v1.3.1.md deleted file mode 100644 index 7a168c7..0000000 --- a/release/RELEASE_NOTES_v1.3.1.md +++ /dev/null @@ -1,8 +0,0 @@ -# V1.3.1 更新内容 - -- 视图切换强化:每次切换条形 / 圆周 / 流程图都会自动「适应窗口」, - 不会再沿用上一个视图的缩放与平移(此前切换后画面可能跑偏) -- 预览缩略图区域固定尺寸:动作再多也不会撑大「条形预览 / 圆周预览」卡片, - 只会在内部自动缩小缩略图、把线条画得更细 -- 更新按钮的「有新版本」红点改为显示在按钮**左上角** -- 默认示例数据精简:首次启动为 5 个动作 / 3 个工位 / 3 个相位分区,更清爽 diff --git a/release/RELEASE_NOTES_v1.3.2.md b/release/RELEASE_NOTES_v1.3.2.md deleted file mode 100644 index 65b1f3b..0000000 --- a/release/RELEASE_NOTES_v1.3.2.md +++ /dev/null @@ -1,9 +0,0 @@ -# V1.3.2 更新内容 - -- 移除顶部工具栏右上角多余的「流程图」快捷按钮 - (流程图入口保留在「条形节拍 / 圆周节拍 / 流程图」分段切换中) -- 画布标题精简:条形 / 圆周视图改为「标题 +(线型说明)」单行展示, - 不再单独占一行,节省纵向显示空间 -- 视图的完整说明(同心圆环含义、循环换算、流程图读法等)统一移入 - 「帮助」(F1)→「相位分区与视图」中查阅 -- 默认示例保持精简:5 个动作 / 3 个工位 / 3 个相位分区 diff --git a/release/RELEASE_NOTES_v1.3.3.md b/release/RELEASE_NOTES_v1.3.3.md deleted file mode 100644 index a7cf4e7..0000000 --- a/release/RELEASE_NOTES_v1.3.3.md +++ /dev/null @@ -1,11 +0,0 @@ -# V1.3.3 更新内容 - -- **依赖连线自动错开**:同一走线分组内的多条依赖(同泳道 / 相邻泳道 / - 跨行绕行)不再完全重叠,依次自动错开 -- **新增「拖动调整走线」**:点选连线后可拖动整条线 - - 条形 / 流程图:上下拖动平移横线;跨行走廊为左右拖动 - - 圆周视图:沿半径方向(法线)拖动 - - 直角拐点随平移保留,走线始终保持正交;双击连线或 - 右键「复位走线偏移」即可恢复自动位置 - - 三种视图(条形 / 圆周 / 流程图)均支持;偏移随工程保存 -- 默认示例保持精简:5 个动作 / 3 个工位 / 3 个相位分区 diff --git a/release/RELEASE_NOTES_v1.3.4.md b/release/notes/RELEASE_NOTES_v1.3.4.md similarity index 100% rename from release/RELEASE_NOTES_v1.3.4.md rename to release/notes/RELEASE_NOTES_v1.3.4.md diff --git a/release/notes/RELEASE_NOTES_v1.3.5.md b/release/notes/RELEASE_NOTES_v1.3.5.md new file mode 100644 index 0000000..b30753f --- /dev/null +++ b/release/notes/RELEASE_NOTES_v1.3.5.md @@ -0,0 +1,55 @@ +# V1.3.5 更新内容 + +## 软件更名与品牌 + +- 正式更名 **EDC|易得设计**(Easy Design Collection);可执行文件更名为 + `EasyDesignCollection.exe`,安卓应用名同步; +- 仓库更名为 `EasyDesignCollection`(旧地址保留 301 重定向,老版本「检查更新」不受影响)。 + +## 空白启动 · 文档中心 + +- 打开软件不再直接进入时序图,而是**空白首页**(像 Creo / COMSOL 一样先选文档); +- 「新建文档」总览六个专业模块:**架构图、时序图**已开放;电器原理图、IO 表、 + 拓扑图、PID 图灰显「未开放」; +- 支持「打开文档…」「最近打开」(可单条删除 / 清空); +- 品牌菜单重做:首页 + 模块列表 + 软件设置,宽度紧凑、副标题精简。 + +## 架构图模块(本轮重点) + +- **手绘识别**统一按标准图形识别(矩形 / 圆 / 箭头 / 折线 / 曲线 / 云 / 圆柱……), + 识别不了的笔迹保留为墨迹;文字统一双击输入; +- **图元库(Visio 式可扩展)**: + - 内置电气图元(断路器 / 熔断器 / 线圈 / 触点 / 按钮 / 指示灯 / 电机 / 接地……) + 可点击插入; + - 支持「导入图元」与「从选中图形存为图元」,用户图元跨工程复用; + - 图元库按分类折叠(默认收起,只展开选中的库); +- **手绘识别基于图元库**:内置识别不了的笔迹会与图元库轮廓匹配——库里有什么 + 就能画什么;支持多笔组合(如「圆 + 叉 = 指示灯」),且与上一笔刚生成的图形 + 也能在 2.5 秒内回溯合并; +- **识别后图形可编辑尺寸**:选中任意图形 / 曲线 / 图元,右栏「尺寸」区直接改 + 宽度 / 高度 / 长度 / 直径(比例保持),可开启画布标注,双击尺寸标签改值; +- IT 系统设计图元:服务器 / 客户端 / 移动端 / 防火墙 / 交换机 / 消息队列; +- **四边标尺升级**:单位强制 **mm**(左上角单位徽标),垂直轴数值显示在右侧, + 游标位置线为实线; +- 默认画布为 **A0 图纸**(1189×841 mm,新建自动适配居中); +- 图层(可见 / 锁定 / 颜色 / 重命名)、F8 正交 / F10 极轴、网格吸附、磁力对齐线; +- 连线:画路径识别直线 / 折线、折点编辑、端点可拖到别的图形**重新吸附**(或脱离); +- PPT 式对齐 / 均布(左 / 右 / 水平居中 / 顶 / 底 / 垂直居中 / 横向均布 / 纵向均布); +- 导出:**SVG / PNG / DXF**(AutoCAD 可直接打开继续编辑); +- 修复:缩小时画布内容溢出到侧栏 / 工具栏(裁剪修复)。 + +## 时序图模块 + +- 保存格式分离:时序图保存为 **`*.seq.json`**(只含时序内容); +- 架构图另存为独立文件 **`*.arch.json`**; +- 旧版 `.edc.json` 文件继续兼容打开。 + +## 其他 + +- 数据目录更名 `%APPDATA%/EDC`(旧目录首次启动自动复制迁移,不改写原目录); + 新增素材库目录 `library/`(符号 / 图片 / 模板);安卓公共目录为 `Documents/EDC`(兼容旧目录读取); +- 架构画布单位与标尺统一为毫米(1 单位 = 1 mm); +- 更新通道与安卓、Windows 双端同步构建。 + +> 更新提示:更新包下载与发布上传统一限速 320KB/s;安卓包约 53MB, +> 下载约需 3 分钟,请保持屏幕常亮与网络稳定。 diff --git a/scripts/publish_release.ps1 b/scripts/publish_release.ps1 index 9e45d4e..1204c5a 100644 --- a/scripts/publish_release.ps1 +++ b/scripts/publish_release.ps1 @@ -3,12 +3,13 @@ # # 用法(在仓库根目录或任意位置): # powershell -File scripts\publish_release.ps1 -Version 1.2.1 ` -# -NotesFile release\RELEASE_NOTES_v1.2.1.md +# -NotesFile release\notes\RELEASE_NOTES_v1.2.1.md # # 说明: # - 更新说明写入 Release 正文(Markdown),客户端「检查更新」时读取展示; -# - 安卓 APK:默认取 release\sequence_diagram_android_v<版本>_release.apk; -# - Windows 绿色版:默认把 dist\ 打包为 zip 后上传(客户端下载后原地覆盖); +# - 安卓 APK:默认取 release\android\EasyDesignCollection_android_v<版本>_release.apk; +# - Windows 绿色版:默认把 release\windows\EasyDesignCollection\ 打包为 zip +# (客户端下载后原地解压覆盖;zip 内部必须平铺,脚本自动生成于 release\windows\); # - 安装包作为 Release 附件保存,不进入 git 历史,仓库保持精简; # - 发布幂等:v<版本> 已存在(如上次上传中断)时复用它并更新说明; # - 发布完成后自动清理历史附件:只保留「最新 1 个版本」的安装包 @@ -21,7 +22,7 @@ param( [string]$WindowsZipPath = "", [string]$Server = "http://124.220.63.9:30000", [string]$Owner = "admin", - [string]$Repo = "Sequence-Diagram", + [string]$Repo = "EasyDesignCollection", # 2026-10 由 Sequence-Diagram 改名(旧名保留 301 重定向) [string]$Auth = "liuyu65@126.com:ds3317210", # 上传限速(curl --limit-rate):服务器带宽很小(5Mbps), # 限速上传避免打满带宽把服务器压垮(默认 320KB/s ≈ 2.6Mbps)。 @@ -33,23 +34,23 @@ $root = Split-Path -Parent $PSScriptRoot # 仓库根目录(scripts 的上一 # ---- 1) 定位安装包 ---- if ($ApkPath -eq "") { - $ApkPath = Join-Path $root "release\sequence_diagram_android_v${Version}_release.apk" + $ApkPath = Join-Path $root "release\android\EasyDesignCollection_android_v${Version}_release.apk" } if (!(Test-Path $ApkPath)) { throw "找不到 APK:$ApkPath(先执行 flutter build apk --release 并归档到 release\)" } if ($WindowsZipPath -eq "") { - $WindowsZipPath = Join-Path $env:TEMP "sequence_diagram_windows_v${Version}.zip" + $WindowsZipPath = Join-Path $root "release\windows\EasyDesignCollection_windows_v${Version}.zip" } if (!(Test-Path $WindowsZipPath) -or (Get-Item $WindowsZipPath).Length -lt 1048576) { - $dist = Join-Path $root "dist" - if (!(Test-Path (Join-Path $dist "sequence_diagram.exe"))) { - throw "找不到 dist\sequence_diagram.exe(先执行 flutter build windows --release 并同步到 dist\)" + $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 并同步到该目录)" } Write-Host "打包 Windows 绿色版:$WindowsZipPath" if (Test-Path $WindowsZipPath) { Remove-Item $WindowsZipPath -Force } - & tar.exe -a -cf $WindowsZipPath -C $dist . + & tar.exe -a -cf $WindowsZipPath -C $winDir . if ($LASTEXITCODE -ne 0) { throw "打包失败" } } diff --git a/test/arch_export_test.dart b/test/arch_export_test.dart new file mode 100644 index 0000000..9345601 --- /dev/null +++ b/test/arch_export_test.dart @@ -0,0 +1,63 @@ +// 架构图导出测试:SVG 元素完整性 + DXF 结构 + PNG 位图渲染(3840×2160)。 +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/theme/tokens.dart'; + +void main() { + test('架构图 SVG:包含图形 / 连线 / 标签 / 墨迹元素', () { + final String svg = buildArchSvg( + doc: archDemoDoneScene(), + baseTokens: Tokens.light, + ); + expect(svg, contains('')); + expect(svg, contains(' loadZhFonts()); + await tester.runAsync(() => loadMaterialIcons()); + + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final AppController c = AppController(project: demoTiming()); + addTearDown(c.dispose); + + Widget shell(Tokens t) => RepaintBoundary( + key: const ValueKey('shot'), + child: MaterialApp( + theme: buildTheme(t), + debugShowCheckedModeBanner: false, + home: AppShell(controller: c), + ), + ); + + Future shot(String path) async { + await tester.pump(); + await expectLater( + find.byKey(const ValueKey('shot')), matchesGoldenFile(path)); + } + + await tester.pumpWidget(shell(Tokens.light)); + await tester.pump(); + + // 0) 首页(空白启动):新建文档网格 + 未开放模块灰显。 + c.goHome(); + await tester.pump(); + // 等最近打开列表真实读盘(flutter_test 需要 runAsync 才推进真实 IO)。 + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 300))); + await tester.pump(); + await shot('../demo/home-light.png'); + + // 切换到架构图模块(左上角「设计合集」菜单的动作)。 + c.setAppMode(AppMode.architecture); + await tester.pump(); + + // 展开左右侧栏(浮层)并钉住,展示停靠布局(与 tablet 截图一致的操作)。 + await tester.tapAt(const Offset(10, 300)); + await tester.pump(); + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + await tester.tapAt(const Offset(1270, 300)); + await tester.pump(); + if (tester.any(find.byIcon(Icons.push_pin_outlined))) { + await tester.tap(find.byIcon(Icons.push_pin_outlined).first); + await tester.pump(); + } + + // 1) 合集菜单(左上角 logo 展开):首页 / 时序图 / 架构图 / 未开放模块。 + await tester.tap(find.text('架构图设计').first); + await tester.pumpAndSettle(); + await shot('../demo/arch-menu-light.png'); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + + // 2) 手绘稿(墨迹,待识别)。 + c.archLoadDemo(ArchDemoKind.ink); + await tester.pump(); + await shot('../demo/arch-ink-light.png'); + + // 3) 完成图(识别 + 连线 + 标签)。 + c.archLoadDemo(ArchDemoKind.done); + await tester.pump(); + await shot('../demo/arch-done-light.png'); + + // 3.5) 图元库演示:插入「接地 / 指示灯」两个图元(可扩展图元库)。 + c.addArchShape(const ArchShape( + id: 'SY1', + type: ArchShapeType.symbol, + symbolId: 'pe-ground', + rect: Rect.fromLTWH(1000, 790, 80, 145), + fill: 0x264CC9F0, + stroke: 0xFF4CC9F0, + sw: 1.8, + )); + c.addArchShape(const ArchShape( + id: 'SY2', + type: ArchShapeType.symbol, + symbolId: 'hl-lamp', + rect: Rect.fromLTWH(1125, 790, 80, 175), + fill: 0x26FFD166, + stroke: 0xFFFFD166, + sw: 1.8, + )); + await tester.pump(); + await shot('../demo/arch-symbols-light.png'); + + // 4) 深色主题完成图(主题切换有 200ms 过渡,等动画结束再截)。 + c.toggleTheme(); + await tester.pumpWidget(shell(Tokens.dark)); + await tester.pump(const Duration(milliseconds: 400)); + await shot('../demo/arch-done-dark.png'); + + // 5) 参数化草图:几何 + 约束图标 + 驱动尺寸 + 参数列表。 + c.toggleTheme(); + await tester.pumpWidget(shell(Tokens.light)); + await tester.pump(const Duration(milliseconds: 400)); + c.setSketchMode(true); + c.setSketchTool(SketchTool.line); + c.changeSketch((_) => demoSampleSketch()); + c.selectSketchIds(['E1']); + await tester.pump(); + await shot('../demo/arch-sketch-light.png'); + }); + + testWidgets('generate architecture recognition sheet', (WidgetTester tester) async { + await tester.runAsync(() => loadZhFonts()); + await tester.runAsync(() => loadMaterialIcons()); + + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final List<(String, List)> items = archRecognitionSheet(); + // 对照表同时充当「识别回归样本」:每个样本都必须识别成功。 + for (final (String, List) it in items) { + expect(recognizeArchStroke(it.$2), isNotNull, reason: '样本「${it.$1}」应被识别'); + } + + await tester.pumpWidget( + RepaintBoundary( + key: const ValueKey('sheet'), + child: MaterialApp( + theme: buildTheme(Tokens.light), + debugShowCheckedModeBanner: false, + home: Scaffold( + backgroundColor: Tokens.light.bg, + body: Center( + child: CustomPaint( + size: const Size(1216, 720), + painter: _SheetPainter(items), + ), + ), + ), + ), + ), + ); + await tester.pump(); + await expectLater(find.byKey(const ValueKey('sheet')), + matchesGoldenFile('../demo/arch-recognition-light.png')); + }); +} + +/// 参数化草图演示:矩形(H/V 约束)+ 圆(半径尺寸)+ 斜线(平行约束、长度尺寸) +/// + 四分之一圆弧;求解一次使尺寸与几何一致。 +SketchDoc demoSampleSketch() { + const SketchDoc d = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 120, y: 140), + SketchPoint(id: 'P2', x: 390, y: 140), + SketchPoint(id: 'P3', x: 390, y: 300), + SketchPoint(id: 'P4', x: 120, y: 300), + SketchPoint(id: 'P5', x: 520, y: 220), + SketchPoint(id: 'P6', x: 150, y: 430), + SketchPoint(id: 'P7', x: 430, y: 430), + SketchPoint(id: 'P8', x: 560, y: 430), + SketchPoint(id: 'P9', x: 660, y: 430), + SketchPoint(id: 'P10', x: 560, y: 530), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P2', p2: 'P3'), + SketchEntity(id: 'E3', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + SketchEntity(id: 'E4', kind: SketchKind.line, p1: 'P4', p2: 'P1'), + SketchEntity(id: 'E5', kind: SketchKind.circle, p1: 'P5', r: 70), + SketchEntity(id: 'E6', kind: SketchKind.line, p1: 'P6', p2: 'P7'), + SketchEntity( + id: 'E7', + kind: SketchKind.arc, + p1: 'P8', + p2: 'P9', + p3: 'P10', + r: 100), + ], + constraints: [ + SketchConstraint(id: 'K1', type: SketchConsType.horizontal, a: 'E1'), + SketchConstraint(id: 'K2', type: SketchConsType.vertical, a: 'E2'), + SketchConstraint(id: 'K3', type: SketchConsType.horizontal, a: 'E3'), + SketchConstraint(id: 'K4', type: SketchConsType.vertical, a: 'E4'), + SketchConstraint(id: 'K5', type: SketchConsType.parallel, a: 'E6', b: 'E1'), + ], + dims: [ + SketchDim(id: 'D1', type: SketchDimType.length, value: 270, a: 'E1'), + SketchDim(id: 'D2', type: SketchDimType.radius, value: 70, a: 'E5'), + SketchDim(id: 'D3', type: SketchDimType.length, value: 280, a: 'E6'), + ], + ); + return solveSketch(d).doc; +} + +/// 识别对照表:3 列网格,每格「手绘墨迹 → 识别结果」两个小画格。 +class _SheetPainter extends CustomPainter { + _SheetPainter(this.items); + + final List<(String, List)> items; + + @override + void paint(Canvas canvas, Size size) { + final Tokens t = Tokens.light; + const int cols = 3; + final int rows = (items.length + cols - 1) ~/ cols; + final double cw = size.width / cols; + final double ch = size.height / rows; + for (int i = 0; i < items.length; i++) { + final Rect cell = Rect.fromLTWH( + (i % cols) * cw, + (i ~/ cols) * ch, + cw, + ch, + ); + _cell(canvas, t, cell, items[i].$1, items[i].$2); + } + } + + void _cell(Canvas canvas, Tokens t, Rect cell, String label, List ink) { + final Rect box = cell.deflate(14); + canvas.drawRRect( + RRect.fromRectAndRadius(box, const Radius.circular(12)), + Paint()..color = t.panel, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(box, const Radius.circular(12)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = t.line2, + ); + final TextPainter tp = TextPainter( + text: TextSpan( + text: '$label · 手绘', + style: TextStyle( + color: t.sub, + fontSize: 12.5, + fontWeight: FontWeight.w700, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Segoe UI'], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, box.topLeft + const Offset(12, 8)); + final TextPainter tp2 = TextPainter( + text: TextSpan( + text: '→ 识别结果', + style: TextStyle( + color: t.ok, + fontSize: 11, + fontWeight: FontWeight.w600, + fontFamily: 'Microsoft YaHei UI', + fontFamilyFallback: const ['Microsoft YaHei', 'Segoe UI'], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp2.paint(canvas, box.topLeft + Offset(12 + tp.width + 12, 10)); + + final Rect leftPane = Rect.fromLTWH( + box.left + 12, box.top + 34, box.width / 2 - 18, box.height - 46); + final Rect rightPane = Rect.fromLTWH( + box.center.dx + 6, box.top + 34, box.width / 2 - 18, box.height - 46); + + const int inkColor = 0xFF64748B; + final List strokes = [ + ArchStroke(id: 'k', pts: ink, color: inkColor), + ]; + _pane(canvas, t, leftPane, ArchDoc(strokes: strokes)); + final ArchRecognition? r = recognizeArchStroke(ink); + _pane( + canvas, + t, + rightPane, + r == null + ? ArchDoc(strokes: strokes) + : ArchDoc(shapes: [ + archShapeFromRecognition(r, id: 'r', color: kArchPalette[0]), + ]), + ); + } + + void _pane(Canvas canvas, Tokens t, Rect pane, ArchDoc doc) { + canvas.save(); + canvas.clipRRect(RRect.fromRectAndRadius(pane, const Radius.circular(8))); + canvas.drawRRect( + RRect.fromRectAndRadius(pane, const Radius.circular(8)), + Paint()..color = t.canvas2, + ); + canvas.save(); + canvas.translate(pane.left, pane.top); + final Rect b = doc.contentBounds().inflate(18); + final double z = + math.min(pane.width / b.width, pane.height / b.height).clamp(0.05, 2.0); + ArchPainter( + doc: doc.copyWith( + zoom: z, + panX: pane.width / 2 - b.center.dx * z, + panY: pane.height / 2 - b.center.dy * z, + ), + t: t, + ).paint(canvas, pane.size); + canvas.restore(); + canvas.restore(); + } + + @override + bool shouldRepaint(covariant _SheetPainter oldDelegate) => false; +} diff --git a/test/arch_symbol_recognizer_test.dart b/test/arch_symbol_recognizer_test.dart new file mode 100644 index 0000000..1c62020 --- /dev/null +++ b/test/arch_symbol_recognizer_test.dart @@ -0,0 +1,159 @@ +// 图元库手绘识别测试:内置符号笔迹命中、乱涂拒绝、自定义图元可识别。 +import 'dart:io'; +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'; + +/// 线段采样。 +List seg(Offset a, Offset b, {int n = 10}) => [ + for (int i = 0; i <= n; i++) Offset.lerp(a, b, i / n)!, + ]; + +/// 圆弧采样(默认整圆)。 +List arcPts(Offset c, double r, + {int n = 40, double from = 0, double sweep = math.pi * 2}) => + [ + for (int i = 0; i <= n; i++) + c + + Offset( + math.cos(from + sweep * i / n) * r, + math.sin(from + sweep * i / n) * r, + ), + ]; + +void main() { + group('图元库手绘识别', () { + test('接地符号(4 笔):命中 pe-ground', () { + final ArchSymbolMatch? m = recognizeArchSymbol( + >[ + seg(const Offset(50, 2), const Offset(50, 52)), + seg(const Offset(30, 52), const Offset(70, 52)), + seg(const Offset(38, 62), const Offset(62, 62)), + seg(const Offset(45, 72), const Offset(55, 72)), + ], + SymbolLibrary.builtin, + ); + expect(m, isNotNull, reason: '接地符号应被识别'); + expect(m!.symbol.id, 'pe-ground'); + }); + + test('指示灯(桩 + 圆 + 两笔叉,5 笔):命中 hl-lamp', () { + final ArchSymbolMatch? m = recognizeArchSymbol( + >[ + seg(const Offset(50, 4), const Offset(50, 28)), + arcPts(const Offset(50, 50), 22), + seg(const Offset(36, 36), const Offset(64, 64)), + seg(const Offset(64, 36), const Offset(36, 64)), + seg(const Offset(50, 72), const Offset(50, 96)), + ], + SymbolLibrary.builtin, + ); + expect(m, isNotNull, reason: '指示灯应被识别'); + expect(m!.symbol.id, 'hl-lamp'); + }); + + test('电机(圆 + M):命中 motor-m 或灯类中更像的(不误判为无关图元)', () { + final ArchSymbolMatch? m = recognizeArchSymbol( + >[ + arcPts(const Offset(50, 50), 24), + // M 字(两笔折线)。 + [ + const Offset(38, 58), + const Offset(44, 42), + const Offset(50, 58), + ], + [ + const Offset(50, 58), + const Offset(56, 42), + const Offset(62, 58), + ], + ], + SymbolLibrary.builtin, + ); + // 圆 + M 与「圆 + 叉」轮廓整体差异较大:允许识别(电机)或不识别, + // 但绝不能误判成完全无关的形状(如防火墙 / 服务器)。 + if (m != null) { + expect(m.symbol.id, anyOf('motor-m', 'hl-lamp')); + } + }); + + test('乱涂 / 直线:拒绝识别(null)', () { + expect( + recognizeArchSymbol( + >[ + [ + const Offset(0, 0), + const Offset(10, 30), + const Offset(25, 5), + const Offset(40, 35), + const Offset(60, 10), + const Offset(75, 40), + const Offset(90, 15), + ], + ], + SymbolLibrary.builtin, + ), + isNull, + reason: '无意义涂鸦不应被识别', + ); + expect( + recognizeArchSymbol( + >[seg(const Offset(0, 0), const Offset(80, 50))], + SymbolLibrary.builtin, + ), + isNull, + reason: '普通斜线不应被识别为图元', + ); + }); + + test('自定义图元:保存到用户目录后能被识别', () async { + final Directory tmp = await Directory.systemTemp.createTemp('edc-symr-'); + addTearDown(() async => tmp.delete(recursive: true)); + // 自定义三角形图元。 + await SymbolLibrary.saveUser( + const LibSymbol( + id: 'my-tri', + name: '自定义三角', + category: '自定义', + prims: [ + SymPrim( + kind: SymPrimKind.polyline, + pts: [50, 10, 90, 80, 10, 80, 50, 10], + ), + ], + pins: [], + ), + dir: tmp, + ); + final List catalog = await SymbolLibrary.all(dir: tmp); + final ArchSymbolMatch? m = recognizeArchSymbol( + >[ + [ + const Offset(50, 10), + const Offset(90, 80), + const Offset(10, 80), + const Offset(50, 10), + ], + ], + catalog, + ); + expect(m, isNotNull, reason: '自定义图元应能被识别(图元库可扩展)'); + expect(m!.symbol.id, 'my-tri'); + }); + + test('空 / 过短笔迹:null', () { + expect(recognizeArchSymbol(const >[], SymbolLibrary.builtin), isNull); + expect( + recognizeArchSymbol( + >[ + [Offset.zero, const Offset(1, 1)], + ], + SymbolLibrary.builtin, + ), + isNull, + ); + }); + }); +} diff --git a/test/arch_test.dart b/test/arch_test.dart new file mode 100644 index 0000000..25027c6 --- /dev/null +++ b/test/arch_test.dart @@ -0,0 +1,858 @@ +// 架构图模块测试:手绘识别(直线 / 箭头 / 矩形 / 圆 / 椭圆 / 三角形 / 菱形)、 +// 数据模型 JSON 往返、示例场景完整性。 +import 'dart:convert'; +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/model/models.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; + +void main() { + group('手绘识别', () { + test('直线:接近水平 → 吸附为水平线', () { + final ArchRecognition? r = recognizeArchStroke( + sketchLine(const Offset(20, 100), const Offset(220, 92), seed: 3), + ); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.line); + expect(r.arrow, isFalse); + expect((r.a!.dy - r.b!.dy).abs(), lessThan(0.001)); + }); + + test('直线:斜线保持角度', () { + final ArchRecognition? r = recognizeArchStroke( + sketchLine(const Offset(20, 20), const Offset(200, 160), seed: 4), + ); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.line); + expect(r.arrow, isFalse); + expect(r.b!.dx - r.a!.dx, greaterThan(150)); + }); + + test('箭头:箭杆 + 尖端折返 → 识别为箭头', () { + final ArchRecognition? r = recognizeArchStroke( + sketchArrow(const Offset(20, 140), const Offset(240, 60), seed: 5), + ); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.line); + expect(r.arrow, isTrue); + }); + + test('矩形:随手画的方块 → 扶正为矩形', () { + const Rect target = Rect.fromLTWH(30, 40, 160, 110); + final List pts = sketchPolyline( + [ + target.topLeft, + target.topRight, + target.bottomRight, + target.bottomLeft, + target.topLeft + const Offset(12, 0), + ], + seed: 6, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.rect); + expect((r.rect.left - target.left).abs(), lessThan(6)); + expect((r.rect.width - target.width).abs(), lessThan(8)); + expect((r.rect.height - target.height).abs(), lessThan(8)); + }); + + test('圆形:随手画的圆 → 扶正为圆(宽高一致)', () { + final List pts = sketchEllipse( + Rect.fromCircle(center: const Offset(100, 100), radius: 70), + seed: 7, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.circle); + expect((r.rect.width - r.rect.height).abs(), lessThan(0.01)); + }); + + test('椭圆:长宽比保留', () { + const Rect target = Rect.fromLTWH(20, 40, 200, 100); + final ArchRecognition? r = recognizeArchStroke(sketchEllipse(target, seed: 8)); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.ellipse); + expect(r.rect.width / r.rect.height, greaterThan(1.6)); + }); + + test('三角形:顶点朝上', () { + const Rect target = Rect.fromLTWH(30, 30, 160, 120); + final List pts = sketchPolyline( + [ + Offset(target.center.dx, target.top), + target.bottomRight, + target.bottomLeft, + Offset(target.center.dx + 10, target.top), + ], + seed: 9, + jitter: 1.4, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.triangle); + expect(r.dir, 0); + }); + + test('菱形', () { + const Rect target = Rect.fromLTWH(30, 40, 160, 120); + final List pts = sketchPolyline( + [ + Offset(target.center.dx, target.top), + Offset(target.right, target.center.dy), + Offset(target.center.dx, target.bottom), + Offset(target.left, target.center.dy), + Offset(target.center.dx + 10, target.top), + ], + seed: 10, + jitter: 1.4, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.diamond); + }); + + test('折线:L 形 → 识别为折线并扶正水平 / 垂直段', () { + final ArchRecognition? r = recognizeArchStroke(sketchPolyline( + [const Offset(20, 20), const Offset(180, 30), const Offset(190, 160)], + seed: 11, + )); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.polyline); + final List pts = r.pts!; + expect(pts.length, 3); + expect((pts[1].dy - pts[0].dy).abs(), lessThan(0.001)); + expect((pts[2].dx - pts[1].dx).abs(), lessThan(0.001)); + }); + + test('连线轨迹简化:多段折线 + 近轴段扶正', () { + final List pts = sketchPolyline( + [ + const Offset(20, 20), + const Offset(180, 30), + const Offset(190, 160) + ], + seed: 11, + ); + final List v = simplifyArchPolyline(pts); + expect(v.length, 3); + expect((v[1].dy - v[0].dy).abs(), lessThan(0.001)); + expect((v[2].dx - v[1].dx).abs(), lessThan(0.001)); + }); + + test('曲线:平滑 S 形 → 识别为曲线', () { + final ArchRecognition? r = recognizeArchStroke( + sketchCurve(const Offset(30, 130), const Offset(200, 60), seed: 12), + ); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.curve); + expect(r.pts!.length, greaterThanOrEqualTo(3)); + }); + + test('云:多鼓包闭合曲线 → 识别为云', () { + const Rect rect = Rect.fromLTWH(40, 40, 200, 130); + final ArchShape proto = + ArchShape(id: 'p', type: ArchShapeType.cloud, rect: rect); + final List pts = archInkOutline( + archShapePath(proto), + seed: 21, + jitter: 1.6, + gapFrac: 0.06, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.cloud); + }); + + test('圆柱:柱体 + 顶盖一笔画 → 识别为圆柱', () { + const Rect rect = Rect.fromLTWH(40, 40, 150, 150); + final ArchShape proto = + ArchShape(id: 'p', type: ArchShapeType.cylinder, rect: rect); + final List pts = archInkOutline( + archShapePath(proto), + seed: 22, + jitter: 1.5, + gapFrac: 0.05, + ); + final ArchRecognition? r = recognizeArchStroke(pts); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.cylinder); + }); + + test('两笔组合:分开两笔画的矩形 → 合并识别为矩形', () { + const Rect target = Rect.fromLTWH(40, 40, 160, 110); + final List a = sketchPolyline( + [target.topLeft, target.topRight, target.bottomRight], + seed: 31, + ); + final List b = sketchPolyline( + [target.bottomRight, target.bottomLeft, target.topLeft], + seed: 32, + ); + final ArchRecognition? r = recognizeArchStrokes(>[a, b]); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.rect); + }); + + test('圆柱拼接:顶盖椭圆 + 柱体矩形 → 圆柱', () { + const ArchRecognition lid = ArchRecognition( + type: ArchShapeType.ellipse, + rect: Rect.fromLTWH(40, 40, 140, 56), + ); + const ArchRecognition body = ArchRecognition( + type: ArchShapeType.rect, + rect: Rect.fromLTWH(40, 68, 140, 110), + ); + final ArchRecognition? r = archCylinderFromRecognitions(body, lid); + expect(r, isNotNull); + expect(r!.type, ArchShapeType.cylinder); + expect(r.rect.top, 40); + expect(archCylinderFromRecognitions(lid, lid), isNull); + }); + + test('对照表样本全部识别成功', () { + for (final (String, List) item in archRecognitionSheet()) { + final ArchRecognition? r = recognizeArchStroke(item.$2); + expect(r, isNotNull, reason: '样本「${item.$1}」应被识别'); + } + }); + }); + + group('架构图模型', () { + test('JSON 往返:图形 / 墨迹 / 连线 / 视口', () { + final ArchDoc doc = ArchDoc( + shapes: [ + const ArchShape( + id: 'S1', + type: ArchShapeType.roundRect, + rect: Rect.fromLTWH(10, 20, 120, 60), + radius: 12, + fill: 0x264CC9F0, + stroke: 0xFF4CC9F0, + text: 'PLC', + ), + const ArchShape( + id: 'S2', + type: ArchShapeType.line, + rect: Rect.fromLTWH(0, 0, 100, 50), + a: Offset(0, 0), + b: Offset(100, 50), + arrow: true, + ), + ], + strokes: [ + const ArchStroke( + id: 'K1', + pts: [Offset(1, 2), Offset(3, 4)], + color: 0xFF64748B, + ), + ], + connectors: [ + const ArchConnector( + id: 'C1', + fromId: 'S1', + from: Offset(0, 0), + toId: 'S2', + to: Offset(1, 1), + label: 'EtherCAT', + dash: true, + ), + ], + zoom: 0.8, + panX: 12, + panY: -5, + ); + final ArchDoc back = ArchDoc.fromJson( + jsonDecode(jsonEncode(doc.toJson())) as Map, + ); + expect(back.shapes.length, 2); + expect(back.shapes[0].type, ArchShapeType.roundRect); + expect(back.shapes[0].radius, 12); + expect(back.shapes[0].text, 'PLC'); + expect(back.shapes[1].arrow, isTrue); + expect(back.strokes.single.pts.length, 2); + expect(back.connectors.single.label, 'EtherCAT'); + expect(back.connectors.single.dash, isTrue); + expect(back.zoom, 0.8); + expect(back.panX, 12); + expect(back.panY, -5); + }); + + test('工程文件往返保留架构图(暂不与时序图互通)', () { + final Project p = Project.demo().copyWith(arch: archDemoDoneScene()); + final Project back = Project.decode(p.encode()); + expect(back.arch.shapes.length, p.arch.shapes.length); + expect(back.arch.connectors.length, p.arch.connectors.length); + expect(back.actions.length, p.actions.length); + expect(back.name, p.name); + }); + + test('JSON 往返:走线方式 / 网格 / 折线点', () { + final ArchDoc doc = ArchDoc( + shapes: [ + const ArchShape( + id: 'S1', + type: ArchShapeType.polyline, + rect: Rect.fromLTWH(0, 0, 100, 60), + fill: 0, + stroke: 0xFF4CC9F0, + pts: [Offset(0, 0), Offset(60, 0), Offset(60, 60)], + ), + ], + connectors: [ + const ArchConnector( + id: 'C1', + from: Offset(0, 0), + to: Offset(80, 80), + route: ArchRoute.ortho, + ), + ], + gridSnap: false, + gridSize: 40, + ); + final ArchDoc back = ArchDoc.fromJson( + jsonDecode(jsonEncode(doc.toJson())) as Map, + ); + expect(back.connectors.single.route, ArchRoute.ortho); + expect(back.gridSnap, isFalse); + expect(back.gridSize, 40); + expect(back.shapes.single.type, ArchShapeType.polyline); + expect(back.shapes.single.pts.length, 3); + }); + + test('连线折点:JSON 往返 + 几何经过折点', () { + final ArchDoc doc = ArchDoc( + connectors: [ + const ArchConnector( + id: 'C1', + from: Offset(0, 0), + to: Offset(100, 0), + mids: [Offset(40, 0), Offset(40, 60)], + ), + ], + ); + final ArchDoc back = ArchDoc.fromJson( + jsonDecode(jsonEncode(doc.toJson())) as Map, + ); + expect(back.connectors.single.mids.length, 2); + final ArchConnGeometry g = + archConnectorGeometry(back, back.connectors.single); + expect(g.pts.length, 4); + expect(g.pts[1], const Offset(40, 0)); + expect(g.pts[2], const Offset(40, 60)); + }); + + test('连线吸附:开始 / 结束吸附到最近边缘点', () { + const Rect rr = Rect.fromLTWH(100, 100, 200, 100); + final ArchShape rect = + ArchShape(id: 'S', type: ArchShapeType.rect, rect: rr); + // 外部点 clamp 到最近边。 + expect(archNearestBorderPoint(rect, const Offset(350, 140)), + const Offset(300, 140)); + // 内部点投影到最近一条边。 + final Offset inside = archNearestBorderPoint(rect, const Offset(200, 130)); + final bool onBorder = (inside.dx - rr.left).abs() < 0.01 || + (inside.dx - rr.right).abs() < 0.01 || + (inside.dy - rr.top).abs() < 0.01 || + (inside.dy - rr.bottom).abs() < 0.01; + expect(onBorder, isTrue); + // 椭圆按径向投影到边界。 + final ArchShape ell = ArchShape( + id: 'E', + type: ArchShapeType.ellipse, + rect: const Rect.fromLTWH(0, 0, 200, 100)); + expect(archNearestBorderPoint(ell, const Offset(300, 50)), + const Offset(200, 50)); + }); + + test('移动吸附:磁力对齐线与网格回退', () { + const Rect a = Rect.fromLTWH(0, 0, 100, 60); + const Rect b = Rect.fromLTWH(200, 0, 100, 60); + final ArchDoc doc = ArchDoc( + shapes: [ + const ArchShape(id: 'A', type: ArchShapeType.rect, rect: a), + const ArchShape(id: 'B', type: ArchShapeType.rect, rect: b), + ], + gridSnap: false, + ); + // 拖 B:左边缘离 A 的右边缘 3px(tol=6)→ 磁力吸附对齐 + 导引线。 + final ArchMoveSnap snap = archSnapMoveDelta( + doc: doc, + movingIds: {'B'}, + union: b.shift(const Offset(-97, 0)), // 左缘 103,靠近 A 右缘 100(差 3px) + rawDelta: const Offset(-97, 0), + tol: 6, + gridSnap: false, + ); + expect(snap.guideX, 100); + expect(snap.delta.dx, -100); + // 网格回退:无对齐时按网格吸附主选中图形。 + final ArchDoc grid = doc.copyWith(gridSnap: true, gridSize: 20); + final ArchMoveSnap g2 = archSnapMoveDelta( + doc: grid, + movingIds: {'B'}, + union: b.shift(const Offset(103, 7)), + rawDelta: const Offset(103, 7), + tol: 6, + gridSnap: true, + ); + expect(g2.delta.dx, 100); + expect(g2.delta.dy, 0); + }); + + test('正交 / 极轴:位移约束', () { + expect( + archConstrainDelta( + raw: const Offset(30, 10), ortho: true, polar: false, polarDeg: 15), + const Offset(30, 0), + ); + expect( + archConstrainDelta( + raw: const Offset(10, 30), ortho: true, polar: false, polarDeg: 15), + const Offset(0, 30), + ); + final Offset p = archConstrainDelta( + raw: const Offset(100, 96.6), ortho: false, polar: true, polarDeg: 15); + final double ang = math.atan2(p.dy, p.dx) * 180 / math.pi; + expect((ang - 45).abs(), lessThan(0.01)); + expect( + (p.distance - math.sqrt(100 * 100 + 96.6 * 96.6)).abs(), + lessThan(0.01), + ); + }); + + test('图层:JSON 往返 / 可见性 / 内容范围', () { + final ArchDoc doc = ArchDoc( + layers: [ + const ArchLayer(id: 'L0', name: '默认', color: 0xFF4CC9F0), + const ArchLayer( + id: 'LY2', + name: '电控', + color: 0xFF34D399, + visible: false, + locked: true), + ], + shapes: [ + const ArchShape( + id: 'S1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(0, 0, 100, 60), + layerId: 'L0'), + const ArchShape( + id: 'S2', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(500, 0, 100, 60), + layerId: 'LY2'), + ], + ); + final ArchDoc back = ArchDoc.fromJson( + jsonDecode(jsonEncode(doc.toJson())) as Map, + ); + expect(back.layers.length, 2); + expect(back.layerById('LY2').visible, isFalse); + expect(back.isLayerLocked('LY2'), isTrue); + expect(back.isLayerVisible('L0'), isTrue); + // 隐藏图层不计入内容范围。 + expect(back.contentBounds().right, lessThan(200)); + }); + + test('图层归属:新增对象自动进入活动图层', () { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.addArchLayer(); + final String active = c.arch.activeLayer; + c.addArchShape(const ArchShape( + id: 'S9', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(0, 0, 10, 10), + )); + expect(c.arch.shapeById('S9')!.layerId, active); + }); + + test('removeIds 连带删除吸附在图形上的连线', () { + final ArchDoc doc = archDemoDoneScene().removeIds({'S4'}); + expect(doc.shapeById('S4'), isNull); + expect( + doc.connectors + .any((ArchConnector c) => c.fromId == 'S4' || c.toId == 'S4'), + isFalse, + ); + }); + + test('连线端点:吸附图形时实时求边框交点', () { + final ArchDoc doc = archDemoDoneScene(); + final ArchConnector c = + doc.connectors.firstWhere((ArchConnector x) => x.id == 'C4'); + final (Offset a, Offset b) = archConnectorEnds(doc, c); + final ArchShape s5 = doc.shapeById('S5')!; + // 终点应落在视觉相机(S5)的边框上。 + expect(s5.rect.inflate(2).contains(b), isTrue); + expect((a - b).distance, greaterThan(10)); + }); + }); + + group('示例场景', () { + test('手绘稿全部为墨迹(等待识别)', () { + final ArchDoc ink = archDemoInkScene(); + expect(ink.strokes.length, greaterThan(10)); + expect(ink.shapes, isEmpty); + expect(ink.connectors, isEmpty); + }); + + test('完成图含图形 / 连线 / 标题', () { + final ArchDoc done = archDemoDoneScene(); + expect(done.shapes.length, greaterThan(8)); + expect(done.connectors.length, 9); + expect(done.shapes.any((ArchShape s) => s.text.contains('系统架构')), isTrue); + }); + }); + + group('对齐 / 均布', () { + AppController makeController() { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.addArchShape(const ArchShape( + id: 'A1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(0, 0, 100, 60))); + c.addArchShape(const ArchShape( + id: 'A2', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(220, 90, 60, 40))); + c.addArchShape(const ArchShape( + id: 'A3', + type: ArchShapeType.circle, + rect: Rect.fromLTWH(500, 300, 80, 80))); + c.selectArchIds(['A1', 'A2', 'A3']); + return c; + } + + test('左对齐 / 顶对齐:全部对齐到选中范围边界', () { + final AppController c = makeController(); + c.alignArchSelection(ArchAlign.left); + final double left = c.arch.shapeById('A1')!.bounds.left; + for (final String id in ['A2', 'A3']) { + expect(c.arch.shapeById(id)!.bounds.left, closeTo(left, 0.001)); + } + c.alignArchSelection(ArchAlign.top); + final double top = c.arch.shapeById('A1')!.bounds.top; + for (final String id in ['A2', 'A3']) { + expect(c.arch.shapeById(id)!.bounds.top, closeTo(top, 0.001)); + } + }); + + test('横向 / 纵向均布:中心等距', () { + final AppController c = makeController(); + c.alignArchSelection(ArchAlign.distributeH); + final List cx = [ + for (final String id in ['A1', 'A2', 'A3']) + c.arch.shapeById(id)!.bounds.center.dx, + ]; + expect((cx[1] - cx[0]) - (cx[2] - cx[1]), closeTo(0, 0.001)); + c.alignArchSelection(ArchAlign.distributeV); + final List cy = [ + for (final String id in ['A1', 'A2', 'A3']) + c.arch.shapeById(id)!.bounds.center.dy, + ]; + expect((cy[1] - cy[0]) - (cy[2] - cy[1]), closeTo(0, 0.001)); + }); + + test('数量不足:仅提示不改动', () { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.addArchShape(const ArchShape( + id: 'B1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(0, 0, 40, 40))); + c.addArchShape(const ArchShape( + id: 'B2', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(80, 80, 40, 40))); + c.selectArchIds(['B1', 'B2']); + final Rect before = c.arch.shapeById('B2')!.bounds; + c.alignArchSelection(ArchAlign.distributeH); + expect(c.status, contains('均布')); + expect(c.arch.shapeById('B2')!.bounds, before); + }); + }); + + group('分文件保存', () { + test('时序图 JSON 不含架构图部分;架构图独立序列化往返', () { + final Project p = Project.demo().copyWith(arch: archDemoDoneScene()); + final Map seq = + jsonDecode(p.encode(includeArch: false)) as Map; + final Map body = seq['project'] as Map; + expect(body.containsKey('arch'), isFalse); + // 默认(含架构图)仍写入:自动快照 / 旧文件兼容继续可用。 + final Map full = + jsonDecode(p.encode()) as Map; + expect( + (full['project'] as Map).containsKey('arch'), isTrue); + // 独立架构图文档往返。 + final ArchDoc back = ArchDoc.decode(p.arch.encode()); + expect(back.shapes.length, p.arch.shapes.length); + expect(back.connectors.length, p.arch.connectors.length); + expect(back.layers.length, p.arch.layers.length); + }); + }); + + group('连线端点重吸附', () { + test('端点可换绑到其它图形(吸附边框点)或脱离为自由端点', () { + final ArchDoc doc = archDemoDoneScene(); + final ArchConnector c4 = + doc.connectors.firstWhere((ArchConnector x) => x.id == 'C4'); + final ArchShape s5 = doc.shapeById('S5')!; + // 换绑:起点吸附到 S5 的边框。 + final Offset border = archNearestBorderPoint(s5, s5.rect.center); + final ArchConnector moved = c4.copyWith(fromId: 'S5', from: border); + expect(moved.fromId, 'S5'); + expect(s5.rect.inflate(2).contains(moved.from), isTrue); + // 脱离:显式置 null(哨兵语义),位置保留。 + final ArchConnector free = c4.copyWith(fromId: null); + expect(free.fromId, isNull); + expect(free.from, c4.from); + }); + }); + + group('IT 图元', () { + test('新增图元:标签 / 默认尺寸 / 路径 / JSON 往返', () { + for (final ArchShapeType type in [ + ArchShapeType.server, + ArchShapeType.client, + ArchShapeType.mobile, + ArchShapeType.firewall, + ArchShapeType.netSwitch, + ArchShapeType.queue, + ArchShapeType.symbol, + ]) { + expect(archShapeTypeLabel(type).isNotEmpty, isTrue); + final Size d = archDefaultSize(type); + expect(d.width, greaterThan(40), reason: archShapeTypeLabel(type)); + final ArchShape s = ArchShape( + id: 'X1', + type: type, + rect: const Rect.fromLTWH(0, 0, 160, 100), + stroke: 0xFF4CC9F0, + sw: 1.8, + ); + final Path path = archShapePath(s); + expect(path.getBounds().isEmpty, isFalse, + reason: archShapeTypeLabel(type)); + final ArchShape back = ArchShape.fromJson(s.toJson()); + expect(back.type, type); + } + }); + }); + + group('尺寸编辑(识别后图形)', () { + test('矩形宽 / 圆直径:直接缩放且中心保持', () { + const ArchShape rect = ArchShape( + id: 'D1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(100, 100, 200, 120), + ); + final ArchShape w = archShapeApplyDim(rect, ArchDimKind.width, 300); + expect(w.rect.width, 300); + expect(w.rect.center, rect.rect.center); + expect(w.rect.height, 120); + final ArchShape c = archShapeApplyDim( + const ArchShape( + id: 'D2', + type: ArchShapeType.circle, + rect: Rect.fromLTWH(0, 0, 80, 80), + ), + ArchDimKind.diameter, + 120, + ); + expect(c.rect.width, 120); + expect(c.rect.height, 120); + }); + + test('直线 / 曲线长度:按比例缩放保持形状', () { + const ArchShape line = ArchShape( + id: 'L1', + type: ArchShapeType.line, + rect: Rect.fromLTWH(0, 0, 100, 0), + a: Offset(0, 0), + b: Offset(100, 0), + ); + expect(archShapeDimValue(line, ArchDimKind.length), 100); + final ArchShape l2 = archShapeApplyDim(line, ArchDimKind.length, 250); + expect(archShapeDimValue(l2, ArchDimKind.length), closeTo(250, 0.01)); + expect(l2.rect.center, line.rect.center); + + const ArchShape curve = ArchShape( + id: 'C1', + type: ArchShapeType.curve, + rect: Rect.fromLTWH(0, 0, 100, 50), + pts: [Offset(0, 0), Offset(100, 0), Offset(100, 50)], + ); + expect(archShapeLength(curve), closeTo(150, 0.01)); + final ArchShape c2 = archShapeApplyDim(curve, ArchDimKind.length, 300); + expect(archShapeLength(c2), closeTo(300, 0.5)); + final Rect b2 = archLinearBounds(c2); + expect(b2.width / b2.height, closeTo(2.0, 0.01)); + }); + + test('尺寸标注 JSON 往返', () { + const ArchShape s = ArchShape( + id: 'S1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(0, 0, 100, 80), + dims: {ArchDimKind.width, ArchDimKind.height}, + ); + final ArchShape back = ArchShape.fromJson( + jsonDecode(jsonEncode(s.toJson())) as Map); + expect(back.dims.contains(ArchDimKind.width), isTrue); + expect(back.dims.contains(ArchDimKind.height), isTrue); + }); + + test('控制器:改值缩放 + 标注开关', () { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.addArchShape(const ArchShape( + id: 'S1', + type: ArchShapeType.rect, + rect: Rect.fromLTWH(10, 10, 100, 60), + )); + c.setArchShapeDim('S1', ArchDimKind.width, 260); + expect(c.arch.shapeById('S1')!.rect.width, 260); + c.toggleArchShapeDim('S1', ArchDimKind.width); + expect( + c.arch.shapeById('S1')!.dims.contains(ArchDimKind.width), isTrue); + c.toggleArchShapeDim('S1', ArchDimKind.width); + expect( + c.arch.shapeById('S1')!.dims.contains(ArchDimKind.width), isFalse); + }); + + test('默认画布 A0:空文档内容边界 1189×841', () { + final Rect b = ArchDoc.empty.contentBounds(); + expect(b.width, 1189); + expect(b.height, 841); + }); + }); +} + +// ===================== 手绘样本生成(确定性抖动) ===================== + +double _rnd(math.Random r, double amp) => (r.nextDouble() * 2 - 1) * amp; + +Offset _rot(Offset v, double deg) { + final double a = deg * math.pi / 180; + return Offset(v.dx * math.cos(a) - v.dy * math.sin(a), + v.dx * math.sin(a) + v.dy * math.cos(a)); +} + +/// 直线样本。 +List sketchLine(Offset a, Offset b, {int seed = 1, double jitter = 1.5}) { + final math.Random rnd = math.Random(seed); + final List out = []; + final Offset d = b - a; + final double len = d.distance; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + for (double t = 0; t <= len - 2; t += 6) { + out.add(a + u * t + n * _rnd(rnd, jitter) + u * _rnd(rnd, jitter * 0.5)); + } + out.add(b); + return out; +} + +/// 箭头样本:箭杆 + 尖端折返的「>」形头部(同一笔)。 +List sketchArrow(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) { + final math.Random rnd = math.Random(seed); + final List out = []; + final Offset d = b - a; + final double len = d.distance; + final Offset u = d / len; + final Offset n = Offset(-u.dy, u.dx); + for (double t = 0; t <= len - 4; t += 7) { + out.add(a + u * t + n * _rnd(rnd, jitter)); + } + final double hs = math.min(40, len * 0.18); + final Offset p1 = b + _rot(u, 155) * hs; + final Offset p2 = b + _rot(u, -155) * hs; + final Offset mid = (p1 + p2) / 2; + out.add(b); + for (int i = 1; i <= 4; i++) { + out.add(Offset.lerp(b, p1, i / 4)! + n * _rnd(rnd, jitter * 0.5)); + } + for (int i = 1; i <= 4; i++) { + out.add(i <= 2 + ? Offset.lerp(p1, mid, i / 2)! + : Offset.lerp(mid, p2, (i - 2) / 2)!); + } + return out; +} + +/// 折线样本(矩形 / 三角形 / 菱形轮廓)。 +List sketchPolyline( + List pts, { + int seed = 1, + double step = 4, + double jitter = 1.6, +}) { + final math.Random rnd = math.Random(seed); + final List out = []; + for (int i = 0; i < pts.length - 1; i++) { + final Offset a = pts[i]; + final Offset b = pts[i + 1]; + final double len = (b - a).distance; + if (len < 0.001) continue; + final Offset u = (b - a) / len; + final Offset n = Offset(-u.dy, u.dx); + final int count = math.max(1, (len / step).floor()); + for (int k = 0; k < count; k++) { + out.add(a + u * (len * k / count) + n * _rnd(rnd, jitter) + u * _rnd(rnd, jitter * 0.4)); + } + } + out.add(pts.last + Offset(_rnd(rnd, jitter), _rnd(rnd, jitter))); + return out; +} + +/// 曲线样本:平滑的三次贝塞尔(带抖动)。 +List sketchCurve(Offset a, Offset b, {int seed = 1, double jitter = 1.6}) { + final math.Random rnd = math.Random(seed); + final Offset c1 = Offset(a.dx + 50, a.dy - 90); + final Offset c2 = Offset(b.dx - 50, b.dy + 100); + final List out = []; + const int n = 40; + for (int i = 0; i <= n; i++) { + final double t = i / n; + final double u = 1 - t; + final Offset p = a * (u * u * u) + + c1 * (3 * u * u * t) + + c2 * (3 * u * t * t) + + b * (t * t * t); + out.add(p + Offset(_rnd(rnd, jitter), _rnd(rnd, jitter))); + } + return out; +} + +/// 椭圆 / 圆样本(留收笔缺口)。 +List sketchEllipse( + Rect r, { + int seed = 1, + double jitter = 1.8, + double gapFrac = 0.06, +}) { + final math.Random rnd = math.Random(seed); + final List out = []; + final int n = 90; + final double stop = math.pi * 2 * (1 - gapFrac); + for (int i = 0; i < n; i++) { + final double a = stop * i / n; + final Offset p = Offset( + r.center.dx + r.width / 2 * math.cos(a), + r.center.dy + r.height / 2 * math.sin(a), + ); + out.add(p + Offset(_rnd(rnd, jitter), _rnd(rnd, jitter))); + } + return out; +} diff --git a/test/home_test.dart b/test/home_test.dart new file mode 100644 index 0000000..e7b91b1 --- /dev/null +++ b/test/home_test.dart @@ -0,0 +1,113 @@ +// 首页(空白启动)与模块注册表测试: +// 注册表唯一性 / AppMode 映射;首页新建文档、未开放模块、品牌菜单回首页。 +import 'package:flutter/material.dart' hide Action; +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/modules/module_registry.dart'; +import 'package:sequence_diagram/state/app_controller.dart'; +import 'package:sequence_diagram/theme/tokens.dart'; +import 'package:sequence_diagram/ui/app_shell.dart'; + +void main() { + group('模块注册表', () { + test('id / 后缀唯一;时序与架构已开放,其余未开放', () { + final Set ids = kModules.map((EdcModule m) => m.id).toSet(); + expect(ids.length, kModules.length); + final Set suffixes = + kModules.map((EdcModule m) => m.suffix).toSet(); + expect(suffixes.length, kModules.length); + expect(moduleById('sequence')!.available, isTrue); + expect(moduleById('architecture')!.available, isTrue); + expect(moduleById('elec')!.available, isFalse); + expect(moduleById('unknown-id'), isNull); + }); + + test('AppMode 映射与标题文案', () { + expect(moduleOf(AppMode.home), isNull); + expect(moduleOf(AppMode.sequence)!.name, '时序图'); + expect(moduleOf(AppMode.architecture)!.suffix, '.arch.json'); + expect(appModeLabel(AppMode.home), 'EDC|易得设计'); + expect(appModeLabel(AppMode.sequence), contains('时序图')); + }); + }); + + group('首页(空白启动)', () { + Future pumpHome(WidgetTester tester) async { + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.light), + home: AppShell(controller: c), + )); + c.goHome(); + await tester.pump(); + return c; + } + + testWidgets('空白启动:新建文档网格 + 未开放标注,不渲染工作区', (WidgetTester tester) async { + final AppController c = await pumpHome(tester); + expect(c.appMode, AppMode.home); + expect(find.text('新建文档'), findsOneWidget); + expect(find.text('时序图'), findsOneWidget); + expect(find.text('架构图'), findsOneWidget); + expect(find.text('电器原理图'), findsOneWidget); + expect(find.text('未开放'), findsNWidgets(4)); + expect(find.text('打开文档…'), findsOneWidget); + // 首页不显示工作区工具栏。 + expect(find.text('导出'), findsNothing); + }); + + testWidgets('新建时序图:进入工作区并可操作', (WidgetTester tester) async { + final AppController c = await pumpHome(tester); + await tester.tap(find.text('时序图')); + await tester.pumpAndSettle(); + expect(c.appMode, AppMode.sequence); + expect(find.text('导出'), findsOneWidget); + expect(c.currentFilePath, isNull); + }); + + testWidgets('未开放模块:点按无效', (WidgetTester tester) async { + final AppController c = await pumpHome(tester); + await tester.tap(find.text('电器原理图')); + await tester.pump(); + expect(c.appMode, AppMode.home); + }); + + testWidgets('品牌菜单:已进入模块后返回首页(未保存修改先确认)', (WidgetTester tester) async { + final AppController c = await pumpHome(tester); + await tester.tap(find.text('时序图')); + await tester.pumpAndSettle(); + expect(c.appMode, AppMode.sequence); + // 打开品牌菜单(按钮显示当前模块名 + 设计;状态栏也有同名文案,取第一个)。 + await tester.tap(find.text('时序图设计').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('首页')); + await tester.pumpAndSettle(); + // 新文档未保存 → 弹出放弃确认。 + expect(find.text('放弃未保存的修改?'), findsOneWidget); + await tester.tap(find.text('继续')); + await tester.pumpAndSettle(); + expect(c.appMode, AppMode.home); + expect(find.text('新建文档'), findsOneWidget); + }); + + testWidgets('品牌菜单:从时序图切到架构图(确认丢弃后)', (WidgetTester tester) async { + final AppController c = await pumpHome(tester); + await tester.tap(find.text('时序图')); + await tester.pumpAndSettle(); + // 打开品牌菜单(按钮显示当前模块名 + 设计;状态栏也有同名文案,取第一个)。 + await tester.tap(find.text('时序图设计').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('架构图设计')); + await tester.pumpAndSettle(); + expect(find.text('放弃未保存的修改?'), findsOneWidget); + await tester.tap(find.text('继续')); + await tester.pumpAndSettle(); + expect(c.appMode, AppMode.architecture); + expect(find.text('导出'), findsOneWidget); + }); + }); +} diff --git a/test/roundtrip_test.dart b/test/roundtrip_test.dart new file mode 100644 index 0000000..6992bf5 --- /dev/null +++ b/test/roundtrip_test.dart @@ -0,0 +1,304 @@ +// 保存完整性审计:编码 → 解码 → 再编码必须逐字符一致 +//(即「保存的文件重新打开后,与保存前绝对一样」)。 +// +// 覆盖:时序图全字段(含依赖 / 分区 / 泳道槽位 / 视图状态 / 半透明颜色)、 +// 架构图全字段(含全部图形类型 / 墨迹 / 连线 / 图层 / 参数化草图)、 +// 以及真实文件写入 → 读回的一致性。 +import 'dart:io'; +import 'dart:ui' show Offset, Rect; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/arch/arch_models.dart'; +import 'package:sequence_diagram/model/models.dart'; +import 'package:sequence_diagram/sketch/sketch_models.dart'; + +/// 富字段时序图样例。 +Project makeSeq() => Project( + name: '回转 <"引号"> \\ 反斜杠 与换行\n第二行', + units: const UnitSettings( + timeUnit: TimeUnit.min, + phaseUnit: PhaseUnit.percent, + precision: 2, + snapAngle: 0.5, + snapTime: 0.05, + cycleInputPolicy: CycleInputPolicy.keepTime, + showGrid: false, + snapGrid: false, + autoSplitWrap: false, + preset: 'custom', + ), + cycle: const Cycle(durationMs: 12345), + stations: const [ + Station(id: 'ST1', name: '上料', order: 0, color: 0xFF4CC9F0), + Station(id: 'ST2', name: '加工 A', order: 1, color: 0xFF7BD88F), + Station(id: 'ST3', name: '下料', order: 2, color: 0x80FF8A5C), // 半透明 + ], + actions: [ + const Action( + id: 'A1', + name: '夹紧', + stationId: 'ST1', + driver: '气缸 Y1', + startAngle: 0, + durationAngle: 70.5, + layer: 0, + row: 0, + color: 0xFF4CC9F0, + deps: [ + Dependency( + fromId: 'A0', + toId: 'A1', + type: DepType.ss, + offsetAngle: 12.5, + routeOffset: 7.5), + ], + ), + const Action( + id: 'A2', + name: '动作 2', + stationId: 'ST2', + driver: '', + startAngle: 80, + durationAngle: 60, + layer: 2, + row: 1, + color: 0x99FFD166, // 半透明 + deps: [ + Dependency(fromId: 'A1', toId: 'A2', type: DepType.ff), + Dependency( + fromId: 'A1', toId: 'A2', type: DepType.sf, offsetAngle: -3), + ], + ), + ], + viewState: const ViewState( + mode: ViewMode.circular, + zoom: 1.75, + panX: -123.5, + panY: 88.25, + showDeps: false, + showRuler: false, + showPhaseBands: false, + showRingBg: false, + showLayerLabels: false, + selectedIds: ['A2', 'A1'], + ), + phaseZones: const [ + PhaseZone(name: '加工相位', startAngle: 45, endAngle: 180.25), + PhaseZone(name: '跨圈相位', startAngle: 335, endAngle: 385), + ], + keepEmptyLanes: true, + minLaneCount: 5, + laneSlots: const {0: 2, 2: 3}, + autoSaveEnabled: true, + autoSaveMinutes: 30, + ); + +/// 富字段架构图样例(含全部图形类型 / 墨迹 / 连线 / 图层 / 草图)。 +ArchDoc makeArch() => ArchDoc( + shapes: [ + for (int i = 0; i < ArchShapeType.values.length; i++) + ArchShape( + id: 'S${i + 1}', + type: ArchShapeType.values[i], + rect: Rect.fromLTWH(20.5 + i * 30, 40.25 - i * 5, 160, 96), + radius: ArchShapeType.values[i] == ArchShapeType.roundRect ? 16 : 0, + dir: ArchShapeType.values[i] == ArchShapeType.triangle ? 2 : 0, + a: ArchShapeType.values[i] == ArchShapeType.line + ? const Offset(10, 20) + : null, + b: ArchShapeType.values[i] == ArchShapeType.line + ? const Offset(210, 90) + : null, + arrow: ArchShapeType.values[i] == ArchShapeType.line, + fill: 0x264CC9F0, + stroke: 0xFF35618E, + sw: 2.25, + text: '文字 ${i + 1}\n第二行', + pts: (ArchShapeType.values[i] == ArchShapeType.polyline || + ArchShapeType.values[i] == ArchShapeType.curve) + ? const [ + Offset(0, 0), + Offset(40, 30), + Offset(90, 10), + ] + : const [], + layerId: i.isEven ? 'LY1' : 'LY2', + symbolId: ArchShapeType.values[i] == ArchShapeType.symbol + ? 'pe-ground' + : '', + dims: i == 0 + ? const { + ArchDimKind.width, + ArchDimKind.height, + } + : const {}, + ), + ], + strokes: const [ + ArchStroke( + id: 'K1', + pts: [Offset(5, 6), Offset(7.5, 8.25), Offset(10, 12)], + color: 0xFF7C3AED, + w: 2.75, + layerId: 'LY2', + ), + ], + connectors: const [ + ArchConnector( + id: 'C1', + fromId: 'S1', + from: Offset(100, 200), + toId: 'S2', + to: Offset(300, 240), + label: 'EtherCAT\n双行标签', + dash: true, + color: 0xFF7C8DA6, + mids: [Offset(160, 180), Offset(220, 260)], + layerId: 'LY1', + ), + ArchConnector( + id: 'C2', + from: Offset(-50, -60), + to: Offset(55.5, 66.25), + route: ArchRoute.ortho, + color: 0xFF38BDF8, + ), + ], + zoom: 0.63, + panX: -123.5, + panY: 88.25, + gridSnap: false, + gridSize: 37.5, + layers: const [ + ArchLayer(id: 'LY1', name: '电力', color: 0xFFFFD166), + ArchLayer(id: 'LY2', name: '网络', color: 0xFF38BDF8, visible: false), + ArchLayer(id: 'LY3', name: '锁定层', color: 0xFF94A3B8, locked: true), + ], + activeLayerId: 'LY2', + sketch: const SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 10.5, y: 20.25), + SketchPoint(id: 'P2', x: 210.75, y: 20), + SketchPoint(id: 'P3', x: 210, y: 120.5, fixed: true), + SketchPoint(id: 'P4', x: 60, y: 90), + SketchPoint(id: 'P5', x: 300, y: 260), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity( + id: 'E2', kind: SketchKind.circle, p1: 'P3', r: 44.5), + SketchEntity( + id: 'E3', + kind: SketchKind.arc, + p1: 'P4', + p2: 'P1', + p3: 'P2', + r: 62, + ccw: false), + ], + constraints: [ + SketchConstraint( + id: 'K1', type: SketchConsType.horizontal, a: 'E1'), + SketchConstraint(id: 'K2', type: SketchConsType.vertical, a: 'E1'), + SketchConstraint( + id: 'K3', type: SketchConsType.pointOnEntity, a: 'P4', b: 'E1'), + SketchConstraint( + id: 'K4', + type: SketchConsType.tangent, + a: 'E1', + b: 'E2', + internal: true), + ], + dims: [ + SketchDim( + id: 'D1', type: SketchDimType.length, value: 123.5, a: 'E1'), + SketchDim( + id: 'D2', type: SketchDimType.radius, value: 44.5, a: 'E2'), + SketchDim( + id: 'D3', + type: SketchDimType.angle, + value: 37.5, + a: 'E1', + b: 'E3'), + SketchDim( + id: 'D4', + type: SketchDimType.distance, + value: 88.25, + a: 'P1', + b: 'P5'), + ], + ), + ); + +void main() { + group('时序图文档往返', () { + test('全字段:encode → decode → encode 逐字符一致', () { + final Project p = makeSeq(); + final String s1 = p.encode(); + final Project back = Project.decode(s1); + final String s2 = back.encode(); + expect(s2, s1, reason: '保存后重新打开再保存,文件内容必须完全一致'); + + // 抽查关键字段 + 半透明颜色。 + expect(back.name, p.name); + expect(back.laneSlots[2], 3); + expect(back.actions.first.deps.first.routeOffset, 7.5); + expect(back.actions[1].color, 0x99FFD166); + expect(back.stations[2].color, 0x80FF8A5C); + expect(back.viewState.selectedIds, ['A2', 'A1']); + expect(back.units.cycleInputPolicy, CycleInputPolicy.keepTime); + }); + + test('文件层面:写入磁盘 → 读回 → 完全一致', () async { + final Directory tmp = await Directory.systemTemp.createTemp('edc-rt-'); + addTearDown(() async => tmp.delete(recursive: true)); + final Project p = makeSeq(); + final File f = + File('${tmp.path}${Platform.pathSeparator}doc.seq.json'); + await f.writeAsString(p.encode(includeArch: false), flush: true); + final String read = await f.readAsString(); + expect(Project.decode(read).encode(includeArch: false), + p.encode(includeArch: false)); + }); + }); + + group('架构图文档往返', () { + test('全字段(含 IT 图元 / 连线 / 图层 / 草图):逐字符一致', () { + final ArchDoc doc = makeArch(); + final String s1 = doc.encode(); + final ArchDoc back = ArchDoc.decode(s1); + final String s2 = back.encode(); + expect(s2, s1, reason: '架构图保存后重新打开再保存,文件内容必须完全一致'); + + expect(back.shapes.length, ArchShapeType.values.length); + expect(back.layers[1].visible, isFalse); + expect(back.layers[2].locked, isTrue); + expect( + back.connectors.firstWhere((ArchConnector c) => c.id == 'C2').route, + ArchRoute.ortho); + expect(back.sketch.points[2].fixed, isTrue); + expect(back.sketch.dims.length, 4); + }); + + test('文件层面:写入磁盘 → 读回 → 完全一致', () async { + final Directory tmp = await Directory.systemTemp.createTemp('edc-rt-'); + addTearDown(() async => tmp.delete(recursive: true)); + final ArchDoc doc = makeArch(); + final File f = + File('${tmp.path}${Platform.pathSeparator}doc.arch.json'); + await f.writeAsString(doc.encode(), flush: true); + final String read = await f.readAsString(); + expect(ArchDoc.decode(read).encode(), doc.encode()); + }); + + test('时序图与架构图互不混装(分文件契约)', () { + final Project p = makeSeq().copyWith(arch: makeArch()); + // 时序图文件不含架构数据。 + expect(p.encode(includeArch: false).contains('"arch"'), isFalse); + // 架构图文件不含时序数据。 + final String arch = makeArch().encode(); + expect(arch.contains('"stations"'), isFalse); + expect(arch.contains('"actions"'), isFalse); + }); + }); +} diff --git a/test/sketch_test.dart b/test/sketch_test.dart new file mode 100644 index 0000000..423bc53 --- /dev/null +++ b/test/sketch_test.dart @@ -0,0 +1,532 @@ +// 参数化草图测试:约束求解(水平 / 竖直 / 平行 / 垂直 / 相等 / 点在线上)、 +// 驱动尺寸(长度 / 半径 / 角度 / 距离)、拖拽求解、修剪、JSON 往返、 +// 控制器集成与画布交互(两次点击画直线)。 +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/model/models.dart'; +import 'package:sequence_diagram/sketch/sketch_models.dart'; +import 'package:sequence_diagram/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'; + +/// 简易构造:两点直线 + 可选约束。 +SketchDoc twoPointLine() => const SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 10), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + ], + ); + +void main() { + group('约束求解', () { + test('水平约束:求解后两端 y 相等', () { + final SketchDoc doc = twoPointLine().copyWith( + constraints: const [ + SketchConstraint(id: 'K1', type: SketchConsType.horizontal, a: 'E1'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final SketchPoint a = r.doc.pointById('P1')!; + final SketchPoint b = r.doc.pointById('P2')!; + expect((a.y - b.y).abs(), lessThan(0.01)); + }); + + test('竖直约束:求解后两端 x 相等', () { + final SketchDoc doc = twoPointLine().copyWith( + constraints: const [ + SketchConstraint(id: 'K1', type: SketchConsType.vertical, a: 'E1'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final SketchPoint a = r.doc.pointById('P1')!; + final SketchPoint b = r.doc.pointById('P2')!; + expect((a.x - b.x).abs(), lessThan(0.01)); + }); + + test('长度尺寸:驱动直线长度', () { + final SketchDoc doc = twoPointLine().copyWith( + dims: const [ + SketchDim(id: 'D1', type: SketchDimType.length, value: 250, a: 'E1'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final Offset a = r.doc.pointById('P1')!.pos; + final Offset b = r.doc.pointById('P2')!.pos; + expect((b - a).distance, closeTo(250, 0.5)); + }); + + test('半径尺寸:驱动圆半径', () { + final SketchDoc doc = const SketchDoc( + points: [SketchPoint(id: 'P1', x: 50, y: 50)], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.circle, p1: 'P1', r: 20), + ], + dims: [ + SketchDim(id: 'D1', type: SketchDimType.radius, value: 77, a: 'E1'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + expect(r.doc.entityById('E1')!.r, closeTo(77, 0.1)); + }); + + test('角度尺寸:两线夹角被驱动到 45°', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 0), + SketchPoint(id: 'P3', x: 0, y: 0), + SketchPoint(id: 'P4', x: 100, y: 30), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + ], + dims: [ + SketchDim(id: 'D1', type: SketchDimType.angle, value: 45, a: 'E1', b: 'E2'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final double? ang = + sketchMeasure(r.doc, SketchDimType.angle, 'E1', 'E2'); + expect(ang, isNotNull); + expect(ang!, closeTo(45, 1.0)); + }); + + test('平行 + 相等:求解后两线平行且等长', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 0), + SketchPoint(id: 'P3', x: 0, y: 50), + SketchPoint(id: 'P4', x: 60, y: 90), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + ], + constraints: [ + SketchConstraint(id: 'K1', type: SketchConsType.parallel, a: 'E1', b: 'E2'), + SketchConstraint(id: 'K2', type: SketchConsType.equal, a: 'E1', b: 'E2'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final SketchEntity e1 = r.doc.entityById('E1')!; + final SketchEntity e2 = r.doc.entityById('E2')!; + final Offset d1 = r.doc.pointById(e1.p2)!.pos - r.doc.pointById(e1.p1)!.pos; + final Offset d2 = r.doc.pointById(e2.p2)!.pos - r.doc.pointById(e2.p1)!.pos; + final double cross = (d1.dx * d2.dy - d1.dy * d2.dx).abs() / + (d1.distance * d2.distance); + expect(cross, lessThan(0.01)); + expect((d1.distance - d2.distance).abs(), lessThan(1.0)); + }); + + test('点在线上:点被拉到直线附近', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 0), + SketchPoint(id: 'P3', x: 40, y: 25), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + ], + constraints: [ + SketchConstraint( + id: 'K1', + type: SketchConsType.pointOnEntity, + a: 'P3', + b: 'E1'), + ], + ); + final SketchSolveResult r = solveSketch(doc); + final Offset p = r.doc.pointById('P3')!.pos; + final Offset a = r.doc.pointById('P1')!.pos; + final Offset b = r.doc.pointById('P2')!.pos; + final double dist = (p - a).dx * (b - a).dy - (p - a).dy * (b - a).dx; + expect((dist / (b - a).distance).abs(), lessThan(0.1)); + }); + }); + + group('拖拽求解(矩形保持直角)', () { + test('拖一角:水平 / 竖直约束保持', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'A', x: 0, y: 0), + SketchPoint(id: 'B', x: 100, y: 0), + SketchPoint(id: 'C', x: 100, y: 60), + SketchPoint(id: 'D', x: 0, y: 60), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'A', p2: 'B'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'B', p2: 'C'), + SketchEntity(id: 'E3', kind: SketchKind.line, p1: 'C', p2: 'D'), + SketchEntity(id: 'E4', kind: SketchKind.line, p1: 'D', p2: 'A'), + ], + constraints: [ + SketchConstraint(id: 'K1', type: SketchConsType.horizontal, a: 'E1'), + SketchConstraint(id: 'K2', type: SketchConsType.vertical, a: 'E2'), + SketchConstraint(id: 'K3', type: SketchConsType.horizontal, a: 'E3'), + SketchConstraint(id: 'K4', type: SketchConsType.vertical, a: 'E4'), + ], + ); + final SketchSolveResult r = solveSketch( + doc, + dragPoints: {'B': const Offset(150, -20)}, + ); + final SketchPoint a = r.doc.pointById('A')!; + final SketchPoint b = r.doc.pointById('B')!; + final SketchPoint c = r.doc.pointById('C')!; + final SketchPoint d = r.doc.pointById('D')!; + expect((a.y - b.y).abs(), lessThan(0.5)); + expect((b.x - c.x).abs(), lessThan(0.5)); + expect((c.y - d.y).abs(), lessThan(0.5)); + expect((d.x - a.x).abs(), lessThan(0.5)); + expect((b.pos - const Offset(150, -20)).distance, lessThan(6)); + }); + + test('拖线段中点:图标整体平移(两热点同移)', () { + final SketchDoc doc = twoPointLine(); + final SketchSolveResult r = solveSketch( + doc, + dragPoints: { + 'P1': const Offset(20, 5), + 'P2': const Offset(120, 15), + }, + ); + final Offset p1 = r.doc.pointById('P1')!.pos; + final Offset p2 = r.doc.pointById('P2')!.pos; + expect((p1 - const Offset(20, 5)).distance, lessThan(3)); + expect((p2 - const Offset(120, 15)).distance, lessThan(3)); + }); + }); + + group('修剪', () { + test('一条直线被另一条切分:点击段被删除,剩余保留', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 0), + SketchPoint(id: 'P3', x: 50, y: -50), + SketchPoint(id: 'P4', x: 50, y: 50), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + ], + ); + // 点击 E1 右侧段(x=70)。 + final SketchDoc? out = sketchTrimLine(doc, 'E1', const Offset(70, 0)); + expect(out, isNotNull); + // 原 E1 消失,剩余一段(0..50)。 + expect(out!.entityById('E1'), isNull); + final List lines = out.entities + .where((SketchEntity e) => e.kind == SketchKind.line) + .toList(); + expect(lines.length, 2); // 剩余段 + 切线 E2 + final SketchEntity piece = + lines.firstWhere((SketchEntity e) => e.id != 'E2'); + final Offset a = out.pointById(piece.p1)!.pos; + final Offset b = out.pointById(piece.p2)!.pos; + final double near100 = ((a - const Offset(100, 0)).distance + + (b - const Offset(100, 0)).distance); + final double near0 = ((a - Offset.zero).distance + (b - Offset.zero).distance); + // 保留的是近原点的一侧。 + expect(near0, lessThan(near100)); + }); + + test('两条切线之间:点击中段被彻底切除(一分为二)', () { + const SketchDoc doc = SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 0), + SketchPoint(id: 'P3', x: 30, y: -20), + SketchPoint(id: 'P4', x: 30, y: 20), + SketchPoint(id: 'P5', x: 70, y: -20), + SketchPoint(id: 'P6', x: 70, y: 20), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + SketchEntity(id: 'E3', kind: SketchKind.line, p1: 'P5', p2: 'P6'), + ], + ); + final SketchDoc? out = sketchTrimLine(doc, 'E1', const Offset(50, 0)); + expect(out, isNotNull); + final List lines = out!.entities + .where((SketchEntity e) => e.kind == SketchKind.line) + .toList(); + expect(lines.length, 4); // 两段残余 + 两条切线 + expect(out.entityById('E1'), isNull); + }); + + test('无交点:整条删除', () { + final SketchDoc doc = twoPointLine(); + final SketchDoc? out = sketchTrimLine(doc, 'E1', const Offset(50, 5)); + expect(out, isNotNull); + expect(out!.entities, isEmpty); + }); + }); + + group('捕捉与自动约束', () { + test('捕捉已有点:返回该点 id', () { + final SketchDoc doc = twoPointLine(); + final SketchSnap snap = sketchSnap( + doc, + const Offset(103, 12), + gridSnap: false, + grid: 20, + ); + expect(snap.pointId, 'P2'); + }); + + test('近轴自动约束:水平 / 竖直识别', () { + expect(sketchAutoAxis(Offset.zero, const Offset(100, 1)), + SketchConsType.horizontal); + expect(sketchAutoAxis(Offset.zero, const Offset(1, 100)), + SketchConsType.vertical); + expect(sketchAutoAxis(Offset.zero, const Offset(100, 40)), isNull); + }); + + test('约束 / 尺寸可用性判断', () { + final SketchDoc doc = twoPointLine(); + expect(sketchCanConstrain(doc, SketchConsType.horizontal, ['E1']), + isTrue); + expect( + sketchCanConstrain(doc, SketchConsType.parallel, ['E1']), + isFalse); + expect(sketchCanDim(doc, SketchDimType.length, ['E1']), isTrue); + expect(sketchCanDim(doc, SketchDimType.radius, ['E1']), isFalse); + }); + }); + + group('序列化', () { + test('SketchDoc JSON 往返(含约束与尺寸)', () { + final SketchDoc doc = twoPointLine().copyWith( + constraints: const [ + SketchConstraint(id: 'K1', type: SketchConsType.horizontal, a: 'E1'), + ], + dims: const [ + SketchDim(id: 'D1', type: SketchDimType.length, value: 120, a: 'E1'), + ], + ); + final SketchDoc back = SketchDoc.decode(doc.encode()); + expect(back.points.length, 2); + expect(back.entities.length, 1); + expect(back.constraints.single.type, SketchConsType.horizontal); + expect(back.dims.single.value, 120); + }); + + test('ArchDoc 往返包含草图', () { + final ArchDoc doc = ArchDoc.empty.copyWith(sketch: twoPointLine()); + final ArchDoc back = ArchDoc.decode(doc.encode()); + expect(back.sketch.entities.length, 1); + expect(back.sketch.points.length, 2); + }); + }); + + group('自由度', () { + test('宽松草图:剩余自由度为正;全约束:归零附近', () { + final SketchDoc loose = twoPointLine(); + expect(sketchDofCount(loose), 4); // 4 变量 + final SketchDoc fixed = twoPointLine().copyWith( + points: const [ + SketchPoint(id: 'P1', x: 0, y: 0, fixed: true), + SketchPoint(id: 'P2', x: 100, y: 10, fixed: true), + ], + ); + expect(sketchDofCount(fixed), 0); + }); + }); + + group('控制器集成', () { + test('添加尺寸驱动几何;拖动不破坏尺寸;撤销可用', () { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.setSketchMode(true); + c.changeSketch((_) => twoPointLine()); + c.selectSketchIds(['E1']); + c.addSketchDim(SketchDimType.length, 300); + final SketchEntity e = c.sketch.entityById('E1')!; + final double len = (c.sketch.pointById(e.p2)!.pos - + c.sketch.pointById(e.p1)!.pos) + .distance; + expect(len, closeTo(300, 1)); + // 拖动 P2:尺寸约束优先,长度保持。 + c.beginSketchUndo(); + c.dragSketch( + points: {'P2': const Offset(600, 500)}); + final double len2 = (c.sketch.pointById(e.p2)!.pos - + c.sketch.pointById(e.p1)!.pos) + .distance; + expect(len2, closeTo(300, 2)); + // 撤销回到拖拽前(尺寸仍在)。 + c.undo(); + expect(c.sketch.dimById('D1'), isNotNull); + // 架构文档 JSON 带草图。 + final ArchDoc back = ArchDoc.decode(c.arch.encode()); + expect(back.sketch.dims.length, 1); + }); + + test('约束入口:选择不满足时给出提示且不改动', () { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.changeSketch((_) => twoPointLine()); + c.selectSketchIds(['E1']); + final int before = c.sketch.constraints.length; + c.addSketchConstraint(SketchConsType.perpendicular); + expect(c.sketch.constraints.length, before); + expect(c.status, contains('垂直')); + }); + }); + + group('约束 / 尺寸命令流(Creo 风格)', () { + AppController makeCmdController() { + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + c.setSketchMode(true); + c.changeSketch( + (_) => const SketchDoc( + points: [ + SketchPoint(id: 'P1', x: 0, y: 0), + SketchPoint(id: 'P2', x: 100, y: 10), + SketchPoint(id: 'P3', x: 0, y: 100), + SketchPoint(id: 'P4', x: 100, y: 90), + ], + entities: [ + SketchEntity(id: 'E1', kind: SketchKind.line, p1: 'P1', p2: 'P2'), + SketchEntity(id: 'E2', kind: SketchKind.line, p1: 'P3', p2: 'P4'), + ], + ), + ); + return c; + } + + test('水平命令:点命令 → 点直线立即执行;保持激活可连续执行', () { + final AppController c = makeCmdController(); + c.beginSketchConstraint(SketchConsType.horizontal); + expect(c.sketchPendingCons, SketchConsType.horizontal); + expect(c.status, contains('点击一条直线')); + c.sketchCommandPick(const SketchHit(entityId: 'E1')); + expect( + c.sketch.constraints.any((SketchConstraint k) => + k.type == SketchConsType.horizontal && k.a == 'E1'), + isTrue, + ); + // 命令保持激活(Creo 风格连续使用)。 + expect(c.sketchPendingCons, SketchConsType.horizontal); + c.sketchCommandPick(const SketchHit(entityId: 'E2')); + expect( + c.sketch.constraints + .where((SketchConstraint k) => k.type == SketchConsType.horizontal) + .length, + 2, + ); + // 求解后 E1 两端 y 相等。 + final SketchPoint a = c.sketch.pointById('P1')!; + final SketchPoint b = c.sketch.pointById('P2')!; + expect((a.y - b.y).abs(), lessThan(0.01)); + }); + + test('平行命令:两次点选执行;点错对象给出提示且不执行', () { + final AppController c = makeCmdController(); + c.beginSketchConstraint(SketchConsType.parallel); + c.sketchCommandPick(const SketchHit(entityId: 'E1')); + expect(c.sketchPendingIds, ['E1']); + c.sketchCommandPick(const SketchHit(entityId: 'E2')); + expect( + c.sketch.constraints + .any((SketchConstraint k) => k.type == SketchConsType.parallel), + isTrue, + ); + expect(c.sketchPendingIds, isEmpty); + // 点一个点对象 → 提示且不产生约束。 + c.sketchCommandPick(const SketchHit(pointId: 'P1')); + expect(c.status, contains('直线')); + }); + + test('长度尺寸命令:自动标注当前值并标记待编辑;改值精确驱动', () { + final AppController c = makeCmdController(); + c.beginSketchDim(SketchDimType.length); + expect(c.status, contains('点击一条直线')); + c.sketchCommandPick(const SketchHit(entityId: 'E1')); + final SketchDim d = c.sketch.dims.single; + expect(d.type, SketchDimType.length); + expect(d.value, closeTo(100.5, 0.2)); // 当前测量值 + expect(c.sketchDimToEdit, d.id); // 待弹数值编辑框 + c.clearSketchDimToEdit(); + expect(c.sketchDimToEdit, isNull); + // 改值精确驱动。 + c.setSketchDimValue(d.id, 250); + final SketchEntity e = c.sketch.entityById('E1')!; + final double len = (c.sketch.pointById(e.p2)!.pos - + c.sketch.pointById(e.p1)!.pos) + .distance; + expect(len, closeTo(250, 0.5)); + }); + + test('距离尺寸命令:两次点选 → 生成距离标注', () { + final AppController c = makeCmdController(); + c.beginSketchDim(SketchDimType.distance); + c.sketchCommandPick(const SketchHit(pointId: 'P1')); + c.sketchCommandPick(const SketchHit(pointId: 'P2')); + final SketchDim d = c.sketch.dims.single; + expect(d.type, SketchDimType.distance); + expect(d.value, closeTo(100.5, 0.2)); + }); + + test('取消 / 切换命令:状态正确清理', () { + final AppController c = makeCmdController(); + c.beginSketchConstraint(SketchConsType.perpendicular); + c.sketchCommandPick(const SketchHit(entityId: 'E1')); + expect(c.sketchPendingIds, ['E1']); + // 切换到尺寸命令 → 约束命令与拾取被清理。 + c.beginSketchDim(SketchDimType.length); + expect(c.sketchPendingCons, isNull); + expect(c.sketchPendingIds, isEmpty); + expect(c.sketchPendingDim, SketchDimType.length); + // 取消命令。 + c.cancelSketchCommand(); + expect(c.sketchPendingDim, isNull); + expect(c.sketchPendingCons, isNull); + // 再点同一命令 = 取消。 + c.beginSketchConstraint(SketchConsType.horizontal); + c.beginSketchConstraint(SketchConsType.horizontal); + expect(c.sketchPendingCons, isNull); + }); + }); + + testWidgets('草图画布:直线工具两次点击 → 生成实体 + 自动水平约束', + (WidgetTester tester) async { + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + final AppController c = AppController(project: Project.demo()); + addTearDown(c.dispose); + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.light), + home: AppShell(controller: c), + )); + await tester.pump(); + c.setAppMode(AppMode.architecture); + await tester.pump(); + c.setSketchMode(true); + c.setSketchTool(SketchTool.line); + await tester.pump(); + await tester.tapAt(const Offset(500, 300)); + await tester.pump(); + await tester.tapAt(const Offset(820, 302)); + await tester.pump(); + expect(c.sketch.entities.length, 1); + expect(c.sketch.points.length, 2); + expect( + c.sketch.constraints.any( + (SketchConstraint k) => k.type == SketchConsType.horizontal), + isTrue, + ); + }); +} diff --git a/test/symbol_library_test.dart b/test/symbol_library_test.dart new file mode 100644 index 0000000..5a2ada0 --- /dev/null +++ b/test/symbol_library_test.dart @@ -0,0 +1,106 @@ +// 图元库测试:内置符号完整性、JSON 往返、用户目录存取与合并覆盖、坐标换算。 +import 'dart:io'; +import 'dart:ui' show Path, Rect; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/library/symbol_library.dart'; + +void main() { + group('内置符号', () { + test('数量 / id 唯一 / 名称分类引脚完整', () { + expect(SymbolLibrary.builtin.length, greaterThanOrEqualTo(12)); + final Set ids = { + for (final LibSymbol s in SymbolLibrary.builtin) s.id, + }; + expect(ids.length, SymbolLibrary.builtin.length); + for (final LibSymbol s in SymbolLibrary.builtin) { + expect(s.name.isNotEmpty, isTrue, reason: '${s.id} 名称缺失'); + expect(s.category.isNotEmpty, isTrue, reason: '${s.id} 分类缺失'); + expect(s.prims.isNotEmpty, isTrue, reason: '${s.id} 基元缺失'); + expect(s.pins.isNotEmpty, isTrue, reason: '${s.id} 引脚缺失'); + } + }); + + test('引脚坐标在归一化画布边界内', () { + for (final LibSymbol s in SymbolLibrary.builtin) { + for (final SymPin p in s.pins) { + expect(p.x, inInclusiveRange(-5, 105), reason: '${s.id}/${p.id}'); + expect(p.y, inInclusiveRange(-5, 105), reason: '${s.id}/${p.id}'); + } + } + }); + }); + + test('JSON 往返(含文本基元与引脚)', () { + final LibSymbol s = + SymbolLibrary.builtin.firstWhere((LibSymbol x) => x.id == 'km-coil'); + final LibSymbol back = LibSymbol.fromJson(s.toJson()); + expect(back.name, s.name); + expect(back.prims.length, s.prims.length); + expect( + back.prims + .where((SymPrim p) => p.kind == SymPrimKind.text) + .single + .label, + 'KM', + ); + expect(back.pins.map((SymPin p) => p.id).toList(), ['A1', 'A2']); + }); + + test('路径换算:线基元落在目标矩形内', () { + const Rect box = Rect.fromLTWH(10, 20, 200, 200); + const SymPrim line = + SymPrim(kind: SymPrimKind.line, pts: [50, 0, 50, 100]); + final Path path = symPrimPath(line, box)!; + final Rect b = path.getBounds(); + expect(b.center.dx, closeTo(10 + 100, 0.01)); + expect(b.top, closeTo(20, 0.01)); + expect(b.bottom, closeTo(220, 0.01)); + }); + + test('用户目录存取 / 删除 / all() 合并与覆盖', () async { + final Directory tmp = await Directory.systemTemp.createTemp('edc-sym-'); + addTearDown(() async => tmp.delete(recursive: true)); + expect(await SymbolLibrary.loadUser(dir: tmp), isEmpty); + + const LibSymbol custom = LibSymbol( + id: 'my-sym', + name: '自定义符号', + category: '自定义', + prims: [ + SymPrim(kind: SymPrimKind.circle, pts: [50, 50], r: 30), + ], + pins: [SymPin(id: '1', x: 50, y: 0)], + ); + await SymbolLibrary.saveUser(custom, dir: tmp); + final List loaded = await SymbolLibrary.loadUser(dir: tmp); + expect(loaded.single.id, 'my-sym'); + + final List merged = await SymbolLibrary.all(dir: tmp); + expect(merged.length, SymbolLibrary.builtin.length + 1); + + // 用户符号覆盖同名内置 id。 + await SymbolLibrary.saveUser( + const LibSymbol( + id: 'motor-m', + name: '电机(自定义)', + category: '自定义', + prims: [ + SymPrim(kind: SymPrimKind.rect, pts: [20, 20, 60, 60]), + ], + pins: [SymPin(id: '1', x: 50, y: 0)], + ), + dir: tmp, + ); + final List merged2 = await SymbolLibrary.all(dir: tmp); + expect(merged2.length, SymbolLibrary.builtin.length + 1); + expect( + merged2.firstWhere((LibSymbol s) => s.id == 'motor-m').name, + '电机(自定义)', + ); + + await SymbolLibrary.deleteUser('my-sym', dir: tmp); + await SymbolLibrary.deleteUser('motor-m', dir: tmp); + expect(await SymbolLibrary.loadUser(dir: tmp), isEmpty); + }); +} diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 148cfb8..fc460f2 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,10 +1,10 @@ # Project-level configuration. cmake_minimum_required(VERSION 3.14) -project(sequence_diagram LANGUAGES CXX) +project(EasyDesignCollection LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. -set(BINARY_NAME "sequence_diagram") +set(BINARY_NAME "EasyDesignCollection") # 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 3dc8db7..c87522b 100644 --- a/windows/runner/Runner.rc +++ b/windows/runner/Runner.rc @@ -90,12 +90,12 @@ BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "呆头鹅" "\0" - VALUE "FileDescription", "时序图设计 Sequence Diagram Studio" "\0" + VALUE "FileDescription", "EDC|易得设计 Easy Design Collection" "\0" VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "sequence_diagram" "\0" + VALUE "InternalName", "EasyDesignCollection" "\0" VALUE "LegalCopyright", "Copyright (C) 2026 呆头鹅. All rights reserved." "\0" - VALUE "OriginalFilename", "sequence_diagram.exe" "\0" - VALUE "ProductName", "时序图设计" "\0" + VALUE "OriginalFilename", "EasyDesignCollection.exe" "\0" + VALUE "ProductName", "Easy Design Collection" "\0" VALUE "ProductVersion", VERSION_AS_STRING "\0" END END diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp index 3c27fc4..26b7ce1 100644 --- a/windows/runner/flutter_window.cpp +++ b/windows/runner/flutter_window.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include "flutter/generated_plugin_registrant.h"