1.3.5:更名 EDC|易得设计,空白启动首页 + 可扩展图元库识别,架构图大版本
- 品牌:更名 EDC|易得设计(exe/安卓/仓库 EasyDesignCollection;旧地址 301 兼容老客户端更新) - 首页:空白启动 + 六模块「新建文档」选择 + 最近打开;品牌菜单重做 - 架构图:手绘识别统一图形;Visio 式可扩展图元库(导入 / 存为图元 / 分类折叠 / 手绘匹配 / 多笔回溯组合);识别后图形尺寸编辑(宽高长径 + 画布标注 + 双击改值); IT 系统图元;mm 标尺(右轴数值 / 实线游标 / A0 默认画布);图层、F8 正交 / F10 极轴、 对齐均布;连线端点换绑重吸附;DXF / SVG / PNG 导出;缩小时画布溢出到侧栏的裁剪修复 - 时序图:分文件保存(*.seq.json / *.arch.json;旧 .edc.json 兼容) - 路径:运行时目录迁移 %APPDATA%/EDC;素材库 library/;安卓 Documents/EDC - 清理:参数化草图入口冻结;Windows Ink 原生桥移除;dist/ 退役 - 构建:exe + APK 双端同步(1.3.5+26);发布脚本切换 release/ 新目录结构
This commit is contained in:
@@ -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,
|
||||
<Offset>[
|
||||
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<Offset> 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<String> 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<Offset> pts = <Offset>[];
|
||||
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<Offset> pts = <Offset>[];
|
||||
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', ' ');
|
||||
@@ -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<Uint8List> 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 <String>[
|
||||
'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('<?xml version="1.0" encoding="UTF-8"?>');
|
||||
sb.writeln(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="${w.round()}" height="${h.round()}" '
|
||||
'viewBox="${_n(b.left)} ${_n(b.top)} ${_n(w)} ${_n(h)}">');
|
||||
sb.writeln('<rect x="${_n(b.left)}" y="${_n(b.top)}" width="${_n(w)}" height="${_n(h)}" fill="#ffffff"/>');
|
||||
|
||||
// 连线(底层)。
|
||||
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(
|
||||
'<path d="${_smoothD(s.pts)}" fill="none" stroke="${_hex(s.color)}" stroke-width="${_n(s.w)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
sb.writeln('</svg>');
|
||||
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(
|
||||
'<path d="$d" fill="none" stroke="$color" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"$dash/>');
|
||||
// 箭头(终点方向)。
|
||||
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(
|
||||
'<polygon points="${_n(b2.dx)},${_n(b2.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
|
||||
}
|
||||
}
|
||||
// 标签(白底片 + 文本)。
|
||||
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(
|
||||
'<rect x="${_n(bg.left)}" y="${_n(bg.top)}" width="${_n(bg.width)}" height="${_n(bg.height)}" rx="5" '
|
||||
'fill="#ffffff" stroke="#c9d6e5" stroke-width="1"/>');
|
||||
sb.writeln(
|
||||
'<text x="${_n(g.label.dx)}" y="${_n(g.label.dy)}" text-anchor="middle" dominant-baseline="central" '
|
||||
'font-family="Microsoft YaHei UI" font-size="10.5" fill="${_hex(0xFF334155)}">${_esc(c.label)}</text>');
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个标准图形。
|
||||
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(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.roundRect:
|
||||
final double rad = math.min(s.radius, math.min(r.width, r.height) * 0.45);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.ellipse:
|
||||
case ArchShapeType.circle:
|
||||
sb.writeln(
|
||||
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(r.center.dy)}" rx="${_n(r.width / 2)}" ry="${_n(r.height / 2)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.triangle:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archTrianglePoints(s))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.diamond:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archDiamondPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.hexagon:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archHexagonPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
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(
|
||||
'<path d="M ${_n(l)} ${_n(tp + ry)} L ${_n(l)} ${_n(bt - ry)} '
|
||||
'A ${_n(r.width / 2)} ${_n(ry)} 0 0 0 ${_n(rt)} ${_n(bt - ry)} '
|
||||
'L ${_n(rt)} ${_n(tp + ry)} Z" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
// 顶盖(稍亮)。
|
||||
final double lidOp =
|
||||
math.min(1.0, (_opValue(s.fill) + 0.10));
|
||||
sb.writeln(
|
||||
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(tp + ry)}" rx="${_n(r.width / 2)}" ry="${_n(ry)}" '
|
||||
'fill="$fill" fill-opacity="${lidOp.toStringAsFixed(3)}" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.cloud:
|
||||
// 双层绘制:第一层带描边,第二层纯填充覆盖内部接缝 → 外轮廓保持描边。
|
||||
final List<Offset> circles = <Offset>[
|
||||
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<double> radii = <double>[
|
||||
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(
|
||||
'<circle cx="${_n(circles[i].dx)}" cy="${_n(circles[i].dy)}" r="${_n(radii[i])}" '
|
||||
'fill="$fill" fill-opacity="$fillOp"'
|
||||
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
|
||||
}
|
||||
sb.writeln(
|
||||
'<rect x="${_n(base.left)}" y="${_n(base.top)}" width="${_n(base.width)}" height="${_n(base.height)}" '
|
||||
'rx="${_n(r.height * 0.22)}" fill="$fill" fill-opacity="$fillOp"'
|
||||
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
|
||||
}
|
||||
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(
|
||||
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b2.dx)}" y2="${_n(b2.dy)}" '
|
||||
'stroke="$stroke" stroke-width="${_n(s.sw)}" stroke-linecap="round"/>');
|
||||
if (s.arrow) {
|
||||
_svgArrow(sb, a, b2, stroke);
|
||||
}
|
||||
break;
|
||||
case ArchShapeType.polyline:
|
||||
if (s.pts.length >= 2) {
|
||||
sb.writeln(
|
||||
'<polyline points="${_points(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
break;
|
||||
case ArchShapeType.curve:
|
||||
if (s.pts.length >= 2) {
|
||||
sb.writeln(
|
||||
'<path d="${_splineD(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
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(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
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('<line x1="${_n(x0)}" y1="${_n(y)}" x2="${_n(x1)}" y2="${_n(y)}" $inner/>');
|
||||
}
|
||||
|
||||
void dot(double x, double y, double radius) {
|
||||
sb.writeln(
|
||||
'<circle cx="${_n(x)}" cy="${_n(y)}" r="${_n(radius)}" fill="$stroke" fill-opacity="0.85"/>');
|
||||
}
|
||||
|
||||
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(
|
||||
'<rect x="${_n(screen.left)}" y="${_n(screen.top)}" width="${_n(screen.width)}" height="${_n(screen.height)}" rx="${_n(math.min(8, screen.height * 0.12))}" fill="none" stroke="$stroke" stroke-width="$sw"/>');
|
||||
sb.writeln(
|
||||
'<line x1="${_n(r.center.dx)}" y1="${_n(screen.bottom)}" x2="${_n(r.center.dx)}" y2="${_n(r.bottom - r.height * 0.10)}" $inner/>');
|
||||
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(
|
||||
'<line x1="${_n(x)}" y1="${_n(y0)}" x2="${_n(x)}" y2="${_n(y1)}" $inner/>');
|
||||
}
|
||||
}
|
||||
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(
|
||||
'<rect x="${_n(x)}" y="${_n(r.bottom - r.height * 0.42)}" width="${_n(size * 1.4)}" height="${_n(size)}" rx="1.5" fill="$stroke" fill-opacity="0.85"/>');
|
||||
}
|
||||
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(
|
||||
'<path d="M ${_n(x - h * 0.35)} ${_n(r.center.dy - h * 0.5)} L ${_n(x + h * 0.35)} ${_n(r.center.dy)} L ${_n(x - h * 0.35)} ${_n(r.center.dy + h * 0.5)}" fill="none" $inner/>');
|
||||
}
|
||||
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(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="6" '
|
||||
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-dasharray="4 3"/>');
|
||||
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(
|
||||
'<text x="${_n(tl.dx)}" y="${_n(tl.dy)}" font-family="Microsoft YaHei UI" font-size="${_n(size)}" '
|
||||
'font-weight="600" fill="$stroke">${_esc(p.label)}</text>');
|
||||
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(
|
||||
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b.dx)}" y2="${_n(b.dy)}" '
|
||||
'stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
|
||||
case SymPrimKind.polyline:
|
||||
if (p.pts.length < 4) break;
|
||||
final List<Offset> pts = <Offset>[
|
||||
for (int i = 0; i + 1 < p.pts.length; i += 2) p2(p.pts[i], p.pts[i + 1]),
|
||||
];
|
||||
sb.writeln(
|
||||
'<polyline points="${_points(pts)}" fill="none" stroke="$stroke" stroke-width="$sw" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
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(
|
||||
'<circle cx="${_n(c.dx)}" cy="${_n(c.dy)}" r="${_n(rr)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
case SymPrimKind.rect:
|
||||
if (p.pts.length < 4) break;
|
||||
final Offset tl = p2(p.pts[0], p.pts[1]);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(tl.dx)}" y="${_n(tl.dy)}" width="${_n(p.pts[2] / 100 * r.width)}" height="${_n(p.pts[3] / 100 * r.height)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
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(
|
||||
'<path d="M ${_n(s0.dx)} ${_n(s0.dy)} A ${_n(rr)} ${_n(rr)} 0 $large $sweep ${_n(s1.dx)} ${_n(s1.dy)}" '
|
||||
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 箭头头部(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(
|
||||
'<polygon points="${_n(b.dx)},${_n(b.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
|
||||
}
|
||||
|
||||
/// 多行居中文本(每行一个 tspan)。
|
||||
void _svgMultilineText(
|
||||
StringBuffer sb, String text, double cx, double cy, String color, double size) {
|
||||
final List<String> lines = text.split('\n');
|
||||
final double lineH = size * 1.25;
|
||||
final double startY = cy - (lines.length - 1) * lineH / 2;
|
||||
sb.writeln(
|
||||
'<text text-anchor="middle" dominant-baseline="central" font-family="Microsoft YaHei UI" '
|
||||
'font-size="${_n(size)}" font-weight="600" fill="$color">');
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
sb.writeln(
|
||||
'<tspan x="${_n(cx)}" y="${_n(startY + i * lineH)}">${_esc(lines[i])}</tspan>');
|
||||
}
|
||||
sb.writeln('</text>');
|
||||
}
|
||||
|
||||
// ===================== 工具 =====================
|
||||
|
||||
/// 数字格式化(最多 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<Offset> pts) =>
|
||||
pts.map((Offset p) => '${_n(p.dx)},${_n(p.dy)}').join(' ');
|
||||
|
||||
/// 折线 d。
|
||||
String _polyD(List<Offset> 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<Offset> 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<Offset> 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('"', '"');
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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<Offset>? pts;
|
||||
}
|
||||
|
||||
/// 识别一笔手绘:成功返回标准图形,失败返回 null(调用方保留墨迹)。
|
||||
ArchRecognition? recognizeArchStroke(List<Offset> raw) {
|
||||
final List<Offset> 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<List<Offset>> 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<List<Offset>> strokes) {
|
||||
final List<List<Offset>> parts = <List<Offset>>[
|
||||
for (final List<Offset> 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<Offset> a = parts[0];
|
||||
final List<Offset> 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<Offset> merged;
|
||||
double gap;
|
||||
if (g1 <= g2 && g1 <= g3 && g1 <= g4) {
|
||||
merged = <Offset>[...a, ...b];
|
||||
gap = g1;
|
||||
} else if (g2 <= g3 && g2 <= g4) {
|
||||
merged = <Offset>[...a, ...b.reversed];
|
||||
gap = g2;
|
||||
} else if (g3 <= g4) {
|
||||
merged = <Offset>[...a.reversed, ...b];
|
||||
gap = g3;
|
||||
} else {
|
||||
merged = <Offset>[...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<List<Offset>> _splitOnJumps(List<Offset> pts, double diag) {
|
||||
final double thr = math.max(14.0, 0.18 * diag);
|
||||
final List<List<Offset>> parts = <List<Offset>>[];
|
||||
List<Offset> cur = <Offset>[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 = <Offset>[pts[i]];
|
||||
} else {
|
||||
cur.add(pts[i]);
|
||||
}
|
||||
}
|
||||
if (cur.length >= 4) parts.add(cur);
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// 圆柱顶盖(扁椭圆)识别:放宽椭圆残差阈值(扁椭圆曲率大、抖动残差偏高),
|
||||
/// 只要「近椭圆」即可作为顶盖。
|
||||
ArchRecognition? _recognizeLid(List<Offset> lidPts) {
|
||||
final Rect lb = _bounds(lidPts);
|
||||
if (math.min(lb.width, lb.height) < 10) return null;
|
||||
final List<Offset> 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<Offset> bodyPts, List<Offset> 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<Offset> 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<Offset> pts = r.pts ?? const <Offset>[];
|
||||
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<Offset> 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<Offset> 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<int> idx =
|
||||
_rdpIndices(pts, math.max(3.0, 0.03 * diag));
|
||||
final List<int> merged = _mergeOpen(pts, idx, 24);
|
||||
final List<Offset> v = <Offset>[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<Offset> snapped = _snapAxisSegments(v, 12);
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.polyline,
|
||||
rect: _bounds(snapped),
|
||||
pts: snapped,
|
||||
);
|
||||
}
|
||||
// 平缓弯曲 → 曲线:用更粗的简化取「通过点」,保留动势。
|
||||
final List<int> idx2 = _rdpIndices(pts, math.max(5.0, 0.07 * diag));
|
||||
final List<Offset> cv = <Offset>[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<Offset> pts, List<Offset> v) {
|
||||
if (v.length < 2) return false;
|
||||
final List<int> idx = <int>[];
|
||||
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<Offset> simplifyArchPolyline(List<Offset> pts) {
|
||||
final List<Offset> 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<int> idx = _rdpIndices(clean, math.max(4.0, 0.035 * diag));
|
||||
final List<int> merged = _mergeOpen(clean, idx, 24);
|
||||
final List<Offset> v = <Offset>[for (final int i in merged) clean[i]];
|
||||
if (v.length < 2) return <Offset>[clean.first, clean.last];
|
||||
return _snapAxisSegments(v, 12);
|
||||
}
|
||||
|
||||
/// 合并共线折点(开放折线:只处理内部顶点)。
|
||||
List<int> _mergeOpen(List<Offset> pts, List<int> idx, double tolDeg) {
|
||||
final List<int> cur = List<int>.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<Offset> _snapAxisSegments(List<Offset> v, double tolDeg) {
|
||||
final List<Offset> out = List<Offset>.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<Offset> pts) {
|
||||
final int total = pts.length;
|
||||
if (total < 24) return 0;
|
||||
final int k = math.max(2, total ~/ 20);
|
||||
final List<double> turns = <double>[];
|
||||
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<Offset> raw, Rect bb, double diag) {
|
||||
final List<Offset> pts = _resample(raw, 72);
|
||||
final double res90 = _percentile(_ellipseResiduals(pts, bb), 0.90);
|
||||
final List<int> poly =
|
||||
_rdpIndices(pts, math.max(2.2, 0.016 * diag), closed: true);
|
||||
final List<int> 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<int>? 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<int>? 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<Offset> pts, Rect bb, List<int> merged) {
|
||||
final List<Offset> v = <Offset>[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<Offset> 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<Offset> pts, Rect bb, List<int> merged) {
|
||||
final List<Offset> v = <Offset>[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<double> _ellipseResiduals(List<Offset> pts, Rect bb) {
|
||||
final double rx = bb.width / 2;
|
||||
final double ry = bb.height / 2;
|
||||
if (rx < 1 || ry < 1 || pts.isEmpty) return <double>[1];
|
||||
final List<double> out = <double>[];
|
||||
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<double> values, double q) {
|
||||
if (values.isEmpty) return 1;
|
||||
final List<double> s = List<double>.of(values)..sort();
|
||||
final int idx = ((s.length - 1) * q).round().clamp(0, s.length - 1);
|
||||
return s[idx];
|
||||
}
|
||||
|
||||
/// 贴边率:笔迹点贴近外接矩形四条边的比例
|
||||
/// (区分「有直边的矩形」与「全曲线的椭圆」)。
|
||||
double _sideFit(List<Offset> 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<Offset> pts, Rect bb) {
|
||||
final List<Offset> corners = <Offset>[
|
||||
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<Offset> pts, List<int> quad) {
|
||||
final List<Offset> v = <Offset>[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<int>? _tryMergeToQuad(List<Offset> pts, List<int> merged, double maxDev) {
|
||||
final int n = merged.length;
|
||||
if (n == 4) return merged;
|
||||
if (n < 4 || n > 6) return null;
|
||||
double best = maxDev;
|
||||
List<int>? bestSet;
|
||||
if (n == 5) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
final List<int> r = List<int>.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<int> r = List<int>.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<Offset> 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<Offset> _clean(List<Offset> raw) {
|
||||
final List<Offset> out = <Offset>[];
|
||||
for (final Offset p in raw) {
|
||||
if (out.isEmpty || (p - out.last).distance > 0.6) out.add(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 折线总长。
|
||||
double _polyLength(List<Offset> pts) {
|
||||
double s = 0;
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
s += (pts[i] - pts[i - 1]).distance;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// 外接矩形。
|
||||
Rect _bounds(List<Offset> 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<Offset> _resample(List<Offset> pts, int n) {
|
||||
final double len = _polyLength(pts);
|
||||
if (len <= 0.0001 || pts.length < 2) return List<Offset>.of(pts);
|
||||
final double step = len / (n - 1);
|
||||
final List<Offset> out = <Offset>[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<int> _rdpIndices(List<Offset> pts, double eps, {bool closed = false}) {
|
||||
final List<Offset> work =
|
||||
closed ? <Offset>[...pts, pts.first] : pts;
|
||||
final List<bool> keep = List<bool>.filled(work.length, false);
|
||||
keep[0] = true;
|
||||
keep[work.length - 1] = true;
|
||||
final List<List<int>> stack = <List<int>>[
|
||||
<int>[0, work.length - 1],
|
||||
];
|
||||
while (stack.isNotEmpty) {
|
||||
final List<int> 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(<int>[s, idx]);
|
||||
stack.add(<int>[idx, e]);
|
||||
}
|
||||
}
|
||||
final List<int> out = <int>[];
|
||||
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<int> _mergeCollinear(
|
||||
List<Offset> pts,
|
||||
List<int> idx,
|
||||
double tolDeg,
|
||||
double minSeg,
|
||||
) {
|
||||
final List<int> cur = List<int>.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;
|
||||
@@ -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<ArchDemoEntry> archDemoEntries() => <ArchDemoEntry>[
|
||||
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<ArchDemoConn> archDemoConns() => <ArchDemoConn>[
|
||||
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<ArchStroke> strokes = <ArchStroke>[];
|
||||
final Map<String, ArchShape> byId = <String, ArchShape>{};
|
||||
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<Offset> 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<Offset> 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<ArchShape> shapes = <ArchShape>[
|
||||
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<String, ArchShape> byId = <String, ArchShape>{
|
||||
for (final ArchShape s in shapes) s.id: s,
|
||||
};
|
||||
final List<ArchConnector> conns = <ArchConnector>[];
|
||||
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<Offset>)> archRecognitionSheet() {
|
||||
final List<(String, List<Offset>)> out = <(String, List<Offset>)>[];
|
||||
int seed = 101;
|
||||
void addStroke(String label, List<Offset> 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<Offset> archInkOutline(
|
||||
Path path, {
|
||||
required int seed,
|
||||
double jitter = 1.7,
|
||||
double gapFrac = 0.07,
|
||||
}) {
|
||||
final List<PathMetric> metrics = path.computeMetrics().toList();
|
||||
double total = 0;
|
||||
for (final PathMetric m in metrics) {
|
||||
total += m.length;
|
||||
}
|
||||
if (total < 10) return <Offset>[];
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
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<Offset> _inkLine(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
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<Offset> _inkArrow(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
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));
|
||||
}
|
||||
@@ -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<List<Offset>> strokes,
|
||||
List<LibSymbol> catalog, {
|
||||
double maxScore = kArchSymbolMaxScore,
|
||||
double margin = kArchSymbolMargin,
|
||||
int inputSamples = 96,
|
||||
int refSamples = 128,
|
||||
}) {
|
||||
// 每笔独立重采样(避免笔与笔之间产生"跳线"污染),按各笔长度分配采样数。
|
||||
final List<List<Offset>> parts = <List<Offset>>[];
|
||||
final List<double> lens = <double>[];
|
||||
double total = 0;
|
||||
for (final List<Offset> 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<Offset> pts = <Offset>[];
|
||||
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<double> scales = <double>[0.7, 0.85, 1.0, 1.2, 1.45];
|
||||
final List<List<Offset>> scaled = <List<Offset>>[
|
||||
for (final double s in scales)
|
||||
<Offset>[for (final Offset p in input.pts) p * s],
|
||||
];
|
||||
|
||||
ArchSymbolMatch? best;
|
||||
double second = double.infinity;
|
||||
for (final LibSymbol sym in catalog) {
|
||||
final List<Offset> 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<Offset> 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<Offset> pts;
|
||||
final double extent;
|
||||
|
||||
static _Np of(List<Offset> pts) {
|
||||
if (pts.isEmpty) return const _Np(<Offset>[], 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<Offset>.filled(pts.length, Offset.zero), 0);
|
||||
final Offset c = Offset((l + r) / 2, (t + b) / 2);
|
||||
return _Np(<Offset>[
|
||||
for (final Offset p in pts)
|
||||
Offset((p.dx - c.dx) / ext, (p.dy - c.dy) / ext),
|
||||
], ext);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按弧长均匀重采样折线到 [n] 个点。
|
||||
List<Offset> _resample(List<Offset> pts, int n) {
|
||||
if (pts.length <= 1) return List<Offset>.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 <Offset>[pts.first];
|
||||
final List<Offset> out = <Offset>[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<Offset> _sampleSymbol(LibSymbol sym, int n) {
|
||||
final Path path = buildSymbolPath(sym, const Rect.fromLTWH(0, 0, 100, 100));
|
||||
final List<PathMetric> metrics = path.computeMetrics().toList();
|
||||
double total = 0;
|
||||
for (final PathMetric m in metrics) {
|
||||
total += m.length;
|
||||
}
|
||||
if (total < 1e-6) return const <Offset>[];
|
||||
final List<Offset> out = <Offset>[];
|
||||
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<Offset> a, List<Offset> 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<Offset> 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);
|
||||
}
|
||||
@@ -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 <double>[],
|
||||
this.r = 0,
|
||||
this.startDeg = 0,
|
||||
this.sweepDeg = 0,
|
||||
this.label = '',
|
||||
});
|
||||
|
||||
/// 类型。
|
||||
final SymPrimKind kind;
|
||||
|
||||
/// 归一化坐标(含义随类型)。
|
||||
final List<double> pts;
|
||||
|
||||
/// 半径(circle / arc)。
|
||||
final double r;
|
||||
|
||||
/// 起始角(度,arc)。
|
||||
final double startDeg;
|
||||
|
||||
/// 扫掠角(度,arc)。
|
||||
final double sweepDeg;
|
||||
|
||||
/// 文本内容(text)。
|
||||
final String label;
|
||||
|
||||
/// 序列化。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'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<String, dynamic> j) => SymPrim(
|
||||
kind: symPrimKindFrom(j['kind'] as String? ?? 'line'),
|
||||
pts: ((j['pts'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.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<String, dynamic> toJson() => <String, dynamic>{
|
||||
'id': id,
|
||||
if (name.isNotEmpty) 'name': name,
|
||||
'x': x,
|
||||
'y': y,
|
||||
'dir': dir,
|
||||
};
|
||||
|
||||
/// 反序列化。
|
||||
static SymPin fromJson(Map<String, dynamic> 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 <String>[],
|
||||
});
|
||||
|
||||
/// 符号 id(稳定标识;用户符号文件名由它生成)。
|
||||
final String id;
|
||||
|
||||
/// 名称(如「断路器」)。
|
||||
final String name;
|
||||
|
||||
/// 分类(如「开关电器」)。
|
||||
final String category;
|
||||
|
||||
/// 检索标签。
|
||||
final List<String> tags;
|
||||
|
||||
/// 基元列表。
|
||||
final List<SymPrim> prims;
|
||||
|
||||
/// 引脚列表。
|
||||
final List<SymPin> pins;
|
||||
|
||||
/// 序列化。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'id': id,
|
||||
'name': name,
|
||||
'category': category,
|
||||
'tags': tags,
|
||||
'prims': <Map<String, dynamic>>[
|
||||
for (final SymPrim p in prims) p.toJson(),
|
||||
],
|
||||
'pins': <Map<String, dynamic>>[
|
||||
for (final SymPin p in pins) p.toJson(),
|
||||
],
|
||||
};
|
||||
|
||||
/// 反序列化。
|
||||
static LibSymbol fromJson(Map<String, dynamic> j) => LibSymbol(
|
||||
id: j['id'] as String? ?? '',
|
||||
name: j['name'] as String? ?? '未命名',
|
||||
category: j['category'] as String? ?? '未分类',
|
||||
tags: ((j['tags'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => e.toString())
|
||||
.toList(),
|
||||
prims: ((j['prims'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => SymPrim.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
pins: ((j['pins'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => SymPin.fromJson(e as Map<String, dynamic>))
|
||||
.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<LibSymbol> _all = List<LibSymbol>.of(SymbolLibrary.builtin);
|
||||
static Map<String, LibSymbol> _byId = <String, LibSymbol>{
|
||||
for (final LibSymbol s in SymbolLibrary.builtin) s.id: s,
|
||||
};
|
||||
|
||||
/// 全部图元(内置 + 用户)。
|
||||
static List<LibSymbol> get all => _all;
|
||||
|
||||
/// 按 id 查找图元。
|
||||
static LibSymbol? byId(String id) => _byId[id];
|
||||
|
||||
/// 重新加载(应用启动 / 导入 / 保存 / 删除后调用)。
|
||||
static Future<void> refresh() async {
|
||||
final List<LibSymbol> list = await SymbolLibrary.all();
|
||||
_all = list;
|
||||
_byId = <String, LibSymbol>{
|
||||
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<SymPin> _vpins = <SymPin>[
|
||||
SymPin(id: '1', x: 50, y: 0, dir: 't'),
|
||||
SymPin(id: '2', x: 50, y: 100, dir: 'b'),
|
||||
];
|
||||
|
||||
/// 内置符号(电气常用图元;100×100 归一化)。
|
||||
static const List<LibSymbol> builtin = <LibSymbol>[
|
||||
LibSymbol(
|
||||
id: 'qf-brk',
|
||||
name: '断路器 QF',
|
||||
category: '开关电器',
|
||||
tags: <String>['断路器', '空开', 'QF', '开关'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 34]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 34, 66, 56]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 66], r: 3.5),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[72, 26], label: 'QF'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'fu-fuse',
|
||||
name: '熔断器 FU',
|
||||
category: '保护电器',
|
||||
tags: <String>['熔断器', '保险', 'FU'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 32]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[38, 32, 24, 36]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 32, 50, 68]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 68, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 26], label: 'FU'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'km-coil',
|
||||
name: '接触器线圈 KM',
|
||||
category: '开关电器',
|
||||
tags: <String>['接触器', '线圈', 'KM'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 30]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[32, 30, 36, 40]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[40, 44], label: 'KM'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
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: <String>['常开', '动合', 'NO', '触点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 68, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 60, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'nc-contact',
|
||||
name: '常闭触点',
|
||||
category: '开关电器',
|
||||
tags: <String>['常闭', '动断', 'NC', '触点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 50, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 60, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 52, 60, 52]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'sb-no',
|
||||
name: '按钮(常开)SB',
|
||||
category: '主令电器',
|
||||
tags: <String>['按钮', 'SB', '启动'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 26, 60, 26]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 26, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 66, 58]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 58, 50, 78]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 78, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 26]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 30], label: 'SB'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'hl-lamp',
|
||||
name: '指示灯 HL',
|
||||
category: '指示器件',
|
||||
tags: <String>['指示灯', '信号灯', 'HL'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 28]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 50], r: 22),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[36, 36, 64, 64]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[64, 36, 36, 64]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 72, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[72, 34], label: 'HL'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'motor-m',
|
||||
name: '电机 M',
|
||||
category: '负载',
|
||||
tags: <String>['电机', '马达', 'M'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 26]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 50], r: 24),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[42, 42], label: 'M'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 74, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'fr-thermal',
|
||||
name: '热继电器 FR',
|
||||
category: '保护电器',
|
||||
tags: <String>['热继电器', '过载', 'FR'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 22]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[40, 22, 20, 20]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 42, 60, 22]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 42, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 24], label: 'FR'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'terminal',
|
||||
name: '端子 / 接线点',
|
||||
category: '连接器件',
|
||||
tags: <String>['端子', '接线', '连接点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 38]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[40, 38, 20, 24]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 62, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'pe-ground',
|
||||
name: '接地 PE',
|
||||
category: '连接器件',
|
||||
tags: <String>['接地', '地', 'PE'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 52]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[30, 52, 70, 52]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[38, 62, 62, 62]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[45, 72, 55, 72]),
|
||||
],
|
||||
pins: <SymPin>[SymPin(id: '1', x: 50, y: 0, dir: 't')],
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'resistor',
|
||||
name: '电阻 R',
|
||||
category: '无源元件',
|
||||
tags: <String>['电阻', 'R'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 34]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[38, 34, 24, 32]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 66, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[70, 42], label: 'R'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'coil-ka',
|
||||
name: '继电器线圈 KA',
|
||||
category: '开关电器',
|
||||
tags: <String>['继电器', '线圈', 'KA'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 30]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[32, 30, 36, 40]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[40, 44], label: 'KA'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
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: <String>['电源', '直流', 'DC', '电池'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[32, 40, 68, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[42, 50, 58, 50]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[32, 60, 68, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[42, 70, 58, 70]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
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<Directory> _dir(Directory? custom) async =>
|
||||
custom ?? await AppPaths.symbolsDir();
|
||||
|
||||
/// 读取用户符号(目录缺失 / 文件损坏时跳过,不抛异常)。
|
||||
static Future<List<LibSymbol>> loadUser({Directory? dir}) async {
|
||||
try {
|
||||
final Directory d = await _dir(dir);
|
||||
if (!await d.exists()) return <LibSymbol>[];
|
||||
final List<LibSymbol> out = <LibSymbol>[];
|
||||
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<String, dynamic>));
|
||||
} catch (_) {}
|
||||
}
|
||||
return out;
|
||||
} catch (_) {
|
||||
return <LibSymbol>[];
|
||||
}
|
||||
}
|
||||
|
||||
/// 全部符号:内置 + 用户(同 id 时用户覆盖内置)。
|
||||
static Future<List<LibSymbol>> all({Directory? dir}) async {
|
||||
final List<LibSymbol> user = await loadUser(dir: dir);
|
||||
final Set<String> userIds = <String>{
|
||||
for (final LibSymbol s in user) s.id,
|
||||
};
|
||||
return <LibSymbol>[
|
||||
for (final LibSymbol s in builtin)
|
||||
if (!userIds.contains(s.id)) s,
|
||||
...user,
|
||||
];
|
||||
}
|
||||
|
||||
/// 保存用户符号(已存在同 id 时覆盖)。
|
||||
static Future<void> 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<void> 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();
|
||||
}
|
||||
}
|
||||
+24
-5
@@ -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<SequenceDiagramApp> {
|
||||
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<SequenceDiagramApp> {
|
||||
/// 原生窗口标题通道(在 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<void>('setTitle', 'EDC|易得设计')
|
||||
.catchError((Object _) {});
|
||||
return;
|
||||
}
|
||||
final String brand = appModeLabel(_controller.appMode);
|
||||
_windowChannel
|
||||
.invokeMethod<void>('setTitle', '时序图设计 - $name$dirty')
|
||||
.invokeMethod<void>('setTitle', '$brand - $name$dirty')
|
||||
.catchError((Object _) {});
|
||||
}
|
||||
|
||||
@@ -142,7 +159,9 @@ class _SequenceDiagramAppState extends State<SequenceDiagramApp> {
|
||||
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<SequenceDiagramApp> {
|
||||
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),
|
||||
// 固定文本缩放;系统栏图标随主题亮度自动切换(透明系统栏,
|
||||
|
||||
+53
-10
@@ -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<String, dynamic> toJson() => <String, dynamic>{
|
||||
'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<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => Dependency.fromJson(e as Map<String, dynamic>))
|
||||
@@ -361,12 +386,13 @@ class Station {
|
||||
);
|
||||
}
|
||||
|
||||
/// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存。
|
||||
/// 序列化为 JSON;颜色以 `#rrggbb` 字符串保存(半透明时另存 `colorA`)。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'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 <int, int>{},
|
||||
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<int, int>? 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<String, dynamic> toJson() => <String, dynamic>{
|
||||
/// 序列化为 JSON。[includeArch] 为 false 时省略架构图部分。
|
||||
Map<String, dynamic> toJson({bool includeArch = true}) => <String, dynamic>{
|
||||
'schema': schema,
|
||||
'project': <String, dynamic>{
|
||||
'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<dynamic> pz = (p['phaseZones'] as List<dynamic>?) ?? <dynamic>[];
|
||||
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<String, dynamic>?) ?? <String, dynamic>{}),
|
||||
stations: st.map((dynamic e) => Station.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
actions: ac.map((dynamic e) => Action.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
@@ -984,6 +1025,8 @@ class Project {
|
||||
MapEntry<int, int>(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<String, dynamic>?) ?? <String, dynamic>{}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<EdcModule> kModules = <EdcModule>[
|
||||
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}设计';
|
||||
}
|
||||
@@ -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<String> baseOptions = <String>['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<String, dynamic> j = jsonDecode(_settingsFile.readAsStringSync()) as Map<String, dynamic>;
|
||||
_settings = <String, String>{
|
||||
'base': j['base'] as String? ?? 'documents',
|
||||
'folder': j['folder'] as String? ?? 'SequenceDiagram',
|
||||
'folder': j['folder'] as String? ?? defaultFolder,
|
||||
};
|
||||
}
|
||||
} catch (_) {}
|
||||
if (_settings.isEmpty) {
|
||||
_settings = <String, String>{'base': 'documents', 'folder': 'SequenceDiagram'};
|
||||
_settings = <String, String>{'base': 'documents', 'folder': defaultFolder};
|
||||
}
|
||||
return _settings;
|
||||
}
|
||||
@@ -66,7 +74,7 @@ class AndroidDocs {
|
||||
static Future<void> saveSettings(String base, String folder) async {
|
||||
_settings = <String, String>{
|
||||
'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<String, String> 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<String, String> s = settings();
|
||||
return (s['base'] ?? 'documents') == 'documents' &&
|
||||
(s['folder'] ?? defaultFolder) == defaultFolder;
|
||||
}
|
||||
|
||||
/// 列出指定基础目录 + 文件夹下的文件。
|
||||
static Future<List<Map<String, dynamic>>> _listOne(
|
||||
String base, String folder) async {
|
||||
final Object? r =
|
||||
await _channel.invokeMethod<Object?>('listFiles', <String, Object?>{
|
||||
'base': base,
|
||||
'folder': folder,
|
||||
});
|
||||
final List<Object?> list = (r as List<Object?>?) ?? const <Object?>[];
|
||||
return list
|
||||
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// 保存文件到配置的公共目录,返回展示位置。
|
||||
@@ -94,19 +123,33 @@ class AndroidDocs {
|
||||
}
|
||||
|
||||
/// 列出配置目录下的文件(`[{name, size}]`,新在前)。
|
||||
///
|
||||
/// 默认位置额外合并旧目录(Documents/SequenceDiagram)中的文件,
|
||||
/// 同名以新目录为准(兼容旧版本保存的文档)。
|
||||
static Future<List<Map<String, dynamic>>> listFiles() async {
|
||||
final Map<String, String> s = settings();
|
||||
final Object? r = await _channel.invokeMethod<Object?>('listFiles', <String, Object?>{
|
||||
'base': s['base'],
|
||||
'folder': s['folder'],
|
||||
});
|
||||
final List<Object?> list = (r as List<Object?>?) ?? const <Object?>[];
|
||||
return list
|
||||
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
|
||||
.toList();
|
||||
final List<Map<String, dynamic>> primary =
|
||||
await _listOne(s['base'] ?? 'documents', s['folder'] ?? defaultFolder);
|
||||
if (!_useLegacy()) return primary;
|
||||
final List<Map<String, dynamic>> legacy =
|
||||
await _listOne('documents', legacyFolder);
|
||||
final Set<String> names = <String>{
|
||||
for (final Map<String, dynamic> f in primary) (f['name'] as String?) ?? '',
|
||||
};
|
||||
final List<Map<String, dynamic>> out = <Map<String, dynamic>>[...primary];
|
||||
for (final Map<String, dynamic> 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<Uint8List?> readFile(String name) async {
|
||||
final Map<String, String> s = settings();
|
||||
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
|
||||
@@ -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<Object?>('readFile', <String, Object?>{
|
||||
'name': name,
|
||||
'base': 'documents',
|
||||
'folder': legacyFolder,
|
||||
});
|
||||
return legacy as Uint8List?;
|
||||
}
|
||||
|
||||
/// 用系统浏览器打开网址(官网入口;安卓经原生 Intent)。
|
||||
|
||||
@@ -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<Directory> dataRoot() async {
|
||||
await Storage.instance.init();
|
||||
return Storage.instance.appDir;
|
||||
}
|
||||
|
||||
/// 素材库根目录。
|
||||
static Future<Directory> libraryDir() async {
|
||||
final Directory root = await dataRoot();
|
||||
return Directory('${root.path}${Platform.pathSeparator}library');
|
||||
}
|
||||
|
||||
/// 自定义图元目录(`library/symbols`)。
|
||||
static Future<Directory> symbolsDir() async {
|
||||
final Directory lib = await libraryDir();
|
||||
return Directory('${lib.path}${Platform.pathSeparator}symbols');
|
||||
}
|
||||
|
||||
/// 图片素材目录(`library/images`)。
|
||||
static Future<Directory> imagesDir() async {
|
||||
final Directory lib = await libraryDir();
|
||||
return Directory('${lib.path}${Platform.pathSeparator}images');
|
||||
}
|
||||
|
||||
/// 文档模板目录(`library/templates`)。
|
||||
static Future<Directory> templatesDir() async {
|
||||
final Directory lib = await libraryDir();
|
||||
return Directory('${lib.path}${Platform.pathSeparator}templates');
|
||||
}
|
||||
|
||||
/// 确保素材库目录存在(幂等;失败静默,不阻塞启动)。
|
||||
static Future<void> ensureLibrary() async {
|
||||
try {
|
||||
await (await symbolsDir()).create(recursive: true);
|
||||
await (await imagesDir()).create(recursive: true);
|
||||
await (await templatesDir()).create(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -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<String, dynamic> toJson() => <String, dynamic>{
|
||||
'path': path,
|
||||
'moduleId': moduleId,
|
||||
'name': name,
|
||||
'at': atMs,
|
||||
};
|
||||
|
||||
/// 反序列化(无效返回 null)。
|
||||
static RecentDoc? fromJson(dynamic raw) {
|
||||
if (raw is! Map<String, dynamic>) 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<List<RecentDoc>> load() async {
|
||||
try {
|
||||
await Storage.instance.init();
|
||||
final File f = _file(Storage.instance.appDir.path);
|
||||
if (!await f.exists()) return <RecentDoc>[];
|
||||
final dynamic raw = jsonDecode(await f.readAsString());
|
||||
if (raw is! List<dynamic>) return <RecentDoc>[];
|
||||
final List<RecentDoc> out = <RecentDoc>[];
|
||||
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 <RecentDoc>[];
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录一次打开 / 保存(去重后置顶,超限裁剪)。
|
||||
static Future<void> remember({
|
||||
required String path,
|
||||
required String moduleId,
|
||||
String? name,
|
||||
}) async {
|
||||
if (path.isEmpty || moduleId.isEmpty) return;
|
||||
final List<RecentDoc> 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<void> remove(String path) async {
|
||||
final List<RecentDoc> cur = await load();
|
||||
cur.removeWhere((RecentDoc r) => r.path == path);
|
||||
await _save(cur);
|
||||
}
|
||||
|
||||
/// 清空全部记录。
|
||||
static Future<void> clear() async {
|
||||
await _save(<RecentDoc>[]);
|
||||
}
|
||||
|
||||
static Future<void> _save(List<RecentDoc> 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(<Map<String, dynamic>>[
|
||||
for (final RecentDoc r in list) r.toJson(),
|
||||
]),
|
||||
flush: true,
|
||||
);
|
||||
} catch (_) {
|
||||
// 最近列表写入失败不影响主流程。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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<void> _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<String> saveProject(String path, Project project) async {
|
||||
Future<String> 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;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<Offset> pts;
|
||||
|
||||
/// 预览类型(line:折线描边;circle / arc 用第一点为圆心)。
|
||||
final SketchKind kind;
|
||||
|
||||
/// 是否闭合描边。
|
||||
final bool closed;
|
||||
}
|
||||
|
||||
/// 绘制草图内容(调用方已完成 translate + scale)。
|
||||
void paintSketch(
|
||||
Canvas canvas,
|
||||
SketchDoc doc,
|
||||
Tokens t, {
|
||||
Set<String> sel = const <String>{},
|
||||
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<Offset> 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<Offset> _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 ? <Offset>[] : <Offset>[m];
|
||||
case SketchConsType.pointOnEntity:
|
||||
final Offset? p = doc.pointById(k.a)?.pos;
|
||||
return p == null ? <Offset>[] : <Offset>[p + const Offset(10, -10)];
|
||||
case SketchConsType.concentric:
|
||||
final Offset? c = doc.pointById(doc.entityById(k.a)?.p1)?.pos;
|
||||
return c == null ? <Offset>[] : <Offset>[c + const Offset(14, -14)];
|
||||
default:
|
||||
final List<Offset> out = <Offset>[];
|
||||
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));
|
||||
}
|
||||
@@ -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<String, Offset> dragPoints = const <String, Offset>{},
|
||||
Map<String, double> dragRadii = const <String, double>{},
|
||||
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<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(id).dx - t.dx;
|
||||
}));
|
||||
res.add(_Res(6, (List<double> 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<double> x) {
|
||||
acc.x = x;
|
||||
return acc.r(id) - r;
|
||||
}));
|
||||
});
|
||||
|
||||
// ---- 正则项(soft stay) ----
|
||||
final List<double> x0 = vs.x0();
|
||||
for (int i = 0; i < vs.n; i++) {
|
||||
final int idx = i;
|
||||
res.add(_Res(0.03, (List<double> x) => x[idx] - x0[idx]));
|
||||
}
|
||||
|
||||
final (List<double> 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<double> 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<double> 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<double> 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<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(e1.p1).dx - acc.p(e2.p1).dx;
|
||||
}));
|
||||
res.add(_Res(30, (List<double> 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<double> 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<double> 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<double> 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<double> 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<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(e.p2) - acc.p(e.p1)).distance - acc.r(e.id);
|
||||
}));
|
||||
res.add(_Res(30, (List<double> 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<double> 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<double> 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<double> 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<double> 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<double> 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<String, int> _pointIndex = <String, int>{};
|
||||
|
||||
/// 实体 → 半径变量下标。
|
||||
final Map<String, int> _radiusIndex = <String, int>{};
|
||||
|
||||
/// 变量总数。
|
||||
int get n => _n;
|
||||
|
||||
/// 初始变量向量。
|
||||
List<double> x0() {
|
||||
final List<double> x = List<double>.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<double> x) {
|
||||
final List<SketchPoint> pts = <SketchPoint>[
|
||||
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<SketchEntity> ents = <SketchEntity>[
|
||||
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<double> 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<double>, bool, int, double) _lm(
|
||||
List<_Res> res,
|
||||
List<double> x0,
|
||||
int maxIter,
|
||||
) {
|
||||
final int n = x0.length;
|
||||
final List<double> x = List<double>.of(x0);
|
||||
|
||||
double err(List<double> 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<double> rv = List<double>.generate(
|
||||
res.length, (int i) => res[i].weight * res[i].f(x));
|
||||
final List<List<double>> jac = List<List<double>>.generate(
|
||||
res.length,
|
||||
(int _) => List<double>.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<List<double>> a =
|
||||
List<List<double>>.generate(n, (int _) => List<double>.filled(n, 0));
|
||||
final List<double> g = List<double>.filled(n, 0);
|
||||
for (int i = 0; i < res.length; i++) {
|
||||
final List<double> 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<List<double>> ad = List<List<double>>.generate(
|
||||
n,
|
||||
(int p) => List<double>.generate(
|
||||
n,
|
||||
(int q) => a[p][q] + (p == q ? lambda : 0.0),
|
||||
),
|
||||
);
|
||||
final List<double>? d = _solveLinear(ad, g);
|
||||
if (d == null) {
|
||||
lambda *= 8;
|
||||
if (lambda > 1e9) break;
|
||||
continue;
|
||||
}
|
||||
final List<double> x2 =
|
||||
List<double>.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<double>? _solveLinear(List<List<double>> m, List<double> b) {
|
||||
final int n = b.length;
|
||||
final List<List<double>> a = <List<double>>[
|
||||
for (int i = 0; i < n; i++) <double>[...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<double> 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<double> x = List<double>.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;
|
||||
}
|
||||
+1281
-5
File diff suppressed because it is too large
Load Diff
+714
-101
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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<void> 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: <Widget>[
|
||||
AppLogo(size: (compact ? 22 : 24) * scale),
|
||||
SizedBox(width: 7 * scale),
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
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<void> _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<Object>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
barrierLabel: '关闭菜单',
|
||||
barrierColor: Colors.black.withValues(alpha: 0.06),
|
||||
transitionDuration: const Duration(milliseconds: 150),
|
||||
pageBuilder: (BuildContext ctx, Animation<double> a1,
|
||||
Animation<double> a2) =>
|
||||
const SizedBox.shrink(),
|
||||
transitionBuilder: (BuildContext ctx, Animation<double> anim,
|
||||
Animation<double> sec, Widget child) {
|
||||
final Animation<double> curved =
|
||||
CurvedAnimation(parent: anim, curve: Curves.easeOutCubic);
|
||||
return Stack(
|
||||
children: <Widget>[
|
||||
Positioned(
|
||||
left: left,
|
||||
top: top,
|
||||
child: FadeTransition(
|
||||
opacity: curved,
|
||||
child: ScaleTransition(
|
||||
scale: Tween<double>(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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 6, 12, 8),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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,
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+467
-20
@@ -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<void> 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<FileBrowserDialog> {
|
||||
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<FileBrowserDialog> {
|
||||
String _ensureSuffix(String raw) {
|
||||
String n = raw.trim();
|
||||
if (n.isEmpty) return n;
|
||||
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
|
||||
const List<String> known = <String>['.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<FileBrowserDialog> {
|
||||
final List<FileSystemEntity> 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<FileBrowserDialog> {
|
||||
/// 打开文件选择对话框并返回所选路径。
|
||||
///
|
||||
/// [save] 决定保存或打开模式;[suffix] 决定文件过滤与自动补全的后缀
|
||||
/// (`.seq.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。
|
||||
/// (`.edc.json` / `.svg` / `.png`);[defaultName] 为保存模式的默认文件名。
|
||||
Future<String?> pickFile(
|
||||
BuildContext context, {
|
||||
required bool save,
|
||||
String? initialPath,
|
||||
String? defaultName,
|
||||
String suffix = '.seq.json',
|
||||
String suffix = '.edc.json',
|
||||
}) {
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
@@ -447,7 +458,7 @@ class _SaveLocationDialogState extends State<SaveLocationDialog> {
|
||||
super.initState();
|
||||
final Map<String, String> 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<SaveLocationDialog> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/SequenceDiagram)。
|
||||
/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/EDC,兼容旧目录 SequenceDiagram)。
|
||||
///
|
||||
/// - 保存模式:显示当前保存位置(可点「更改位置」修改),输入文件名自动补全后缀;
|
||||
/// - 打开模式:列出目录中匹配后缀的文件,点选返回文件名。
|
||||
@@ -580,7 +591,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
||||
String _ensureSuffix(String raw) {
|
||||
String n = raw.trim();
|
||||
if (n.isEmpty) return n;
|
||||
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
|
||||
const List<String> known = <String>['.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<SoftwareSettingsDialog> createState() => _SoftwareSettingsDialogState();
|
||||
}
|
||||
|
||||
/// 软件设置对话框状态。
|
||||
class _SoftwareSettingsDialogState extends State<SoftwareSettingsDialog> {
|
||||
/// 控制器快捷访问。
|
||||
AppController get c => widget.controller;
|
||||
|
||||
/// 检查更新:发现新版本直接弹更新对话框。
|
||||
Future<void> _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<void>(
|
||||
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: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
_section(t, '外观'),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
Text('间隔', style: TextStyle(color: t.sub, fontSize: 11)),
|
||||
const SizedBox(width: 10),
|
||||
for (final int m in <int>[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: <Widget>[
|
||||
Text('粒度', style: TextStyle(color: t.sub, fontSize: 11)),
|
||||
const SizedBox(width: 10),
|
||||
for (final double g in <double>[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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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<bool> onChanged,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
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<EdcModule?> showDocumentTypeDialog(BuildContext context) async {
|
||||
return showDialog<EdcModule>(
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<String?> showTextEditDialog(
|
||||
BuildContext context, {
|
||||
required String title,
|
||||
required String initial,
|
||||
}) async {
|
||||
final TextEditingController ctrl = TextEditingController(text: initial);
|
||||
final String? result = await showDialog<String>(
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
// 目标:完成方案的搭建与动作的增删改。
|
||||
_section(t, <List<String>>[
|
||||
<String>['我要新建方案', '顶部「新建」创建空白节拍;「打开」载入 .seq.json。'],
|
||||
<String>['我要新建方案', '顶部「新建」创建空白设计;「打开」按时序 / 架构模块分别载入 .seq.json / .arch.json(兼容旧版 .edc.json)。'],
|
||||
<String>['我要先看看示例', '首次启动载入 5 个动作的示例节拍(装配线节拍),可直接修改。'],
|
||||
<String>['我要新增动作', '双击画布空白处在点击相位新增;或左侧「新建」在 0° 新增(默认最外层)。'],
|
||||
<String>['我要删除动作', '选中后:左侧「删除」/ 行内删除图标 / Delete 键 / 右键菜单;至少保留一个动作 / 泳道。'],
|
||||
@@ -2129,7 +2576,7 @@ class HelpDialog extends StatelessWidget {
|
||||
<String>['我要导出 SVG', '顶部「导出」下拉菜单 →「导出 SVG」:矢量、分层、带语义 id 与 data-*,可直接进工艺卡 / MES。'],
|
||||
<String>['我要导出 PNG', '顶部「导出」下拉菜单 →「导出 PNG」:按 2 倍像素比导出当前视图为位图。'],
|
||||
<String>['我要导出 drawio', '流程图视图专用:顶部「导出」→「导出 drawio」,输出 diagrams.net(draw.io)可继续编辑的工程文件。'],
|
||||
<String>['我要保存 / 恢复', '「保存」写入 .seq.json 并生成 .bak;每 5 秒自动快照(异常退出可恢复);F2 文档设置中可开启「自动保存」(默认每 10 分钟一次,需先手动保存过一次路径)。'],
|
||||
<String>['我要保存 / 恢复', '「保存」按时序 / 架构模块分别写入 .seq.json / .arch.json 并生成 .bak;每 5 秒自动快照(异常退出可恢复);「软件设置」中可开启「自动保存」(默认每 10 分钟一次,需先手动保存过一次路径)。'],
|
||||
]),
|
||||
// 目标:调整界面与使用快捷键。
|
||||
_section(t, <List<String>>[
|
||||
@@ -2222,10 +2669,10 @@ class HelpDialog extends StatelessWidget {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
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,'
|
||||
'可在保存对话框中更改位置)。'),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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<HomeView> createState() => _HomeViewState();
|
||||
}
|
||||
|
||||
/// 首页状态:异步加载最近打开列表。
|
||||
class _HomeViewState extends State<HomeView> {
|
||||
List<RecentDoc> _recent = const <RecentDoc>[];
|
||||
|
||||
/// 初始化:加载最近打开。
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadRecent();
|
||||
}
|
||||
|
||||
Future<void> _loadRecent() async {
|
||||
final List<RecentDoc> list = await RecentStore.load();
|
||||
if (!mounted) return;
|
||||
setState(() => _recent = list);
|
||||
}
|
||||
|
||||
Future<void> _clearRecent() async {
|
||||
await RecentStore.clear();
|
||||
if (!mounted) return;
|
||||
setState(() => _recent = const <RecentDoc>[]);
|
||||
}
|
||||
|
||||
Future<void> _removeRecent(RecentDoc doc) async {
|
||||
await RecentStore.remove(doc.path);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_recent = <RecentDoc>[
|
||||
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: <Widget>[
|
||||
_header(t),
|
||||
const SizedBox(height: 22),
|
||||
_sectionTitle(t, '新建文档', '选择要设计的文档类型'),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 14,
|
||||
runSpacing: 14,
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
const AppLogo(size: 46),
|
||||
const SizedBox(width: 14),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
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: <Widget>[
|
||||
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: <Widget>[
|
||||
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';
|
||||
}
|
||||
@@ -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 =>
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
///
|
||||
/// 应用内更新检查用它判断服务器发布的版本是否更新;
|
||||
/// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。
|
||||
const String kAppVersion = '1.3.4';
|
||||
const String kAppVersion = '1.3.5';
|
||||
|
||||
/// 是否要求授权(License)才能导出。
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user