Files

2269 lines
75 KiB
Dart
Raw Permalink Normal View History

/// 架构图画布:手绘识别(笔迹一律识别为标准图形)、选择与框选多选、
/// 批量移动 / 缩放、网格吸附、连线(直线 / 正交 / 极轴)、文字编辑与
/// 「墨迹 → 标准图形」转化动画。
///
/// 与 `CanvasView`(时序图画布)并列:只服务架构图模块;手势走原始指针事件
/// (鼠标 / 触屏 / 手写笔一致),双指捏合缩放平移,触屏长按进入框选。
library;
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart';
import 'package:sequence_diagram/modules/architecture/domain/arch_painter.dart';
import 'package:sequence_diagram/modules/architecture/domain/arch_recognizer.dart';
import 'package:sequence_diagram/modules/architecture/domain/arch_symbol_recognizer.dart';
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart';
import 'package:sequence_diagram/modules/architecture/sketch/sketch_painter.dart';
import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart';
import 'package:sequence_diagram/state/app_controller.dart';
import 'package:sequence_diagram/theme/tokens.dart';
import 'package:sequence_diagram/ui/dialogs.dart';
/// 连线拖拽吸附结果:吸附后的坐标 + 对齐导引(null = 该轴无对齐)。
typedef ConnSnap = ({double x, double y, double? gx, double? gy});
/// 架构图画布组件。
class ArchView extends StatefulWidget {
/// 构造画布;[controller] 为全局应用控制器。
const ArchView({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
/// 创建状态对象。
@override
State<ArchView> createState() => _ArchViewState();
}
/// 画布状态:指针跟踪、草稿、选择操作、转化动画与识别演示。
class _ArchViewState extends State<ArchView>
with SingleTickerProviderStateMixin {
/// 控制器快捷访问。
AppController get c => widget.controller;
// ---- 指针跟踪(支持双指捏合) ----
final Map<int, Offset> _pointers = <int, Offset>{};
int? _primaryPointer;
Offset _downScreen = Offset.zero;
// ---- 手绘草稿 ----
List<Offset>? _draft;
// ---- 连线草稿(按住左键画路径) ----
String? _connFromId;
// ---- 连线拖拽编辑(端点 / 折点 / 线段三种模式) ----
ArchConnector? _connVertexOrigin;
ArchConnector? _connVertexUpdated;
/// 拖动模式:endpoint(端点)/ corner(折点)/ segment(线段)。
String? _connDragMode;
/// 端点模式:几何端点序号(0 = 起点,末位 = 终点)。
int _connVertexIndex = 0;
/// 折点模式:折点序号([ArchConnector.mids] 下标)。
int _connMidIndex = 0;
/// 线段模式:拖动轴('x' / 'y')与初始坐标(同坐标折点一起移动)。
String? _connSegAxis;
double? _connSegSeed;
/// 端点拖拽中的候选吸附目标(实时预览;null = 脱离为自由端点)。
String? _connDragTargetId;
/// 鼠标悬停在连线上(显示抓取光标)。
bool _hoverConn = false;
// ---- 平移 ----
bool _panning = false;
Offset _panStartScreen = Offset.zero;
Offset _panStartPan = Offset.zero;
// ---- 触屏长按框选 ----
bool _touchEmpty = false;
DateTime _touchDownAt = DateTime.now();
Offset _touchDownPos = Offset.zero;
// ---- 框选 ----
bool _marquee = false;
Offset? _mqStart;
Offset? _mqEnd;
// ---- 双指捏合 ----
bool _pinching = false;
double _pinchStartDist = 1;
double _pinchStartZoom = 1;
Offset _pinchStartFocal = Offset.zero;
Offset _pinchStartPan = Offset.zero;
// ---- 移动 / 缩放(支持多选批量) ----
List<String> _moveIds = <String>[];
Map<String, Offset>? _moveDeltas;
Offset _moveStartWorld = Offset.zero;
List<double> _guideXs = const <double>[];
List<double> _guideYs = const <double>[];
int? _resizeHandle;
Rect? _resizeRect;
ArchShape? _resizeOrigin;
// ---- 折点拖动(折线 / 曲线 / 直线端点) ----
int _vertexIndex = 0;
List<Offset>? _vertexPts;
ArchShape? _vertexOrigin;
// ---- 鼠标位置(四边标尺滑动虚线用) ----
Offset? _cursorWorld;
// ---- 点击 / 双击 ----
int _lastClickMs = 0;
Offset _lastClickPos = Offset.zero;
// ---- 文字编辑 ----
String? _editId;
TextEditingController? _editCtrl;
FocusNode? _editFocus;
// ---- 转化动画 ----
final List<ArchConversion> _conversions = <ArchConversion>[];
late final Ticker _ticker;
double _nowMs = 0;
// ---- 识别演示 ----
int _seenPlayToken = 0;
bool _playing = false;
// ---- 转化回溯(图元库多笔组合) ----
String? _lastConvId;
List<Offset> _lastConvPts = const <Offset>[];
DateTime? _lastConvAt;
// ---- 橡皮擦 ----
bool _erasing = false;
int _eraseCount = 0;
// ---- 组合识别缓存(两笔绘图 / 圆柱拼接) ----
String? _lastInkId;
DateTime? _lastInkAt;
String? _lastPartId;
ArchRecognition? _lastPartRec;
DateTime? _lastPartAt;
// ---- 参数化草图交互 ----
SketchSnap? _skLiveSnap;
final List<SketchSnap> _skClicks = <SketchSnap>[];
String? _skDragPointId;
String? _skDragEntityId;
Offset _skDragStartWorld = Offset.zero;
final Map<String, Offset> _skDragOrigPts = <String, Offset>{};
String? _skDragRadiusId;
/// 已弹出过数值编辑框的尺寸 id(防止监听重复弹窗)。
String? _seenDimEdit;
/// 初始化:创建动画 Ticker,监听控制器的「识别演示」触发信号。
@override
void initState() {
super.initState();
_ticker = createTicker(_onTick);
c.addListener(_onController);
_seenPlayToken = c.archPlayToken;
}
/// 释放资源。
@override
void dispose() {
c.removeListener(_onController);
_ticker.dispose();
_editCtrl?.dispose();
_editFocus?.dispose();
super.dispose();
}
/// 控制器变化:识别演示令牌变化时启动演示;新标注尺寸弹出数值编辑框。
void _onController() {
if (c.archPlayToken != _seenPlayToken) {
_seenPlayToken = c.archPlayToken;
_startPlay();
}
final String? dimId = c.sketchDimToEdit;
if (dimId != null && dimId != _seenDimEdit) {
_seenDimEdit = dimId;
final SketchDim? dd = c.sketch.dimById(dimId);
c.clearSketchDimToEdit();
if (dd != null) _editSketchDim(dd);
}
}
// ===================== 转化动画 =====================
/// 动画帧:推进转化进度,完成的写入文档。
void _onTick(Duration _) {
_nowMs = DateTime.now().millisecondsSinceEpoch.toDouble();
final List<ArchConversion> done = <ArchConversion>[];
for (final ArchConversion cv in _conversions) {
if (cv.progress(_nowMs) >= 1) done.add(cv);
}
for (final ArchConversion cv in done) {
_conversions.remove(cv);
c.commitArchConversion(
cv.shape,
removeIds: cv.removeIds,
undo: cv.undo,
);
}
if (mounted) setState(() {});
if (_conversions.isEmpty) _ticker.stop();
}
/// 启动一次「墨迹 → 图形」的转化动画。
void _startConversion(
List<Offset> pts,
ArchShape shape, {
Set<String> removeIds = const <String>{},
bool undo = true,
}) {
// 记录本次转化:2.5 秒内新笔迹可与之组合成「图元库符号」
//(如 圆 先被识别成圆,紧接着画的叉会合并成「指示灯」)。
_lastConvId = shape.id;
_lastConvPts = List<Offset>.of(pts);
_lastConvAt = DateTime.now();
_conversions.add(ArchConversion(
pts: pts,
shape: shape,
startMs: DateTime.now().millisecondsSinceEpoch.toDouble(),
undo: undo,
removeIds: removeIds,
));
if (!_ticker.isActive) _ticker.start();
setState(() {});
}
/// 播放「识别」:把当前墨迹逐条识别(图元库单笔 → 内置 → 与前一条组合),
/// 串行播放转化动画。手动确认识别模式与「识别 N」按钮共用。
Future<void> _startPlay() async {
if (_playing) return;
_playing = true;
final int token = _seenPlayToken;
final List<String> ids = <String>[
for (final ArchStroke s in c.arch.strokes) s.id,
];
void convert(ArchShape shape, List<Offset> pts, Set<String> removeIds) {
_conversions.add(ArchConversion(
pts: pts,
shape: shape,
startMs: DateTime.now().millisecondsSinceEpoch.toDouble(),
undo: false,
removeIds: removeIds,
));
if (!_ticker.isActive) _ticker.start();
setState(() {});
}
Future<void> waitTick() =>
Future<void>.delayed(const Duration(milliseconds: 230));
ArchStroke? prev;
ArchRecognition? prevBuiltin;
Future<void> flushPrev() async {
final ArchStroke? p = prev;
final ArchRecognition? r0 = prevBuiltin;
prev = null;
prevBuiltin = null;
if (p == null || r0 == null) return;
convert(
_snapShapeToGrid(archShapeFromRecognition(r0,
id: archNewId('S', c.arch.allIds), color: c.archColor)),
p.pts,
<String>{p.id},
);
await waitTick();
}
for (final String id in ids) {
if (!mounted || !_playing || _seenPlayToken != token) break;
final ArchStroke? st = c.arch.strokeById(id);
if (st == null) continue;
// 1) 图元库单笔。
final ArchSymbolMatch? m1 =
recognizeArchSymbol(<List<Offset>>[st.pts], SymbolCache.all);
if (m1 != null) {
await flushPrev();
convert(
_symbolShapeFor(m1.symbol, _ptsBounds(st.pts)),
st.pts,
<String>{id},
);
await waitTick();
continue;
}
final ArchRecognition? r = recognizeArchStroke(st.pts);
final bool weak = r == null ||
r.type == ArchShapeType.curve ||
r.type == ArchShapeType.polyline;
// 2) 内置强结果:直接转化。
if (!weak) {
await flushPrev();
convert(
_snapShapeToGrid(archShapeFromRecognition(r,
id: archNewId('S', c.arch.allIds), color: c.archColor)),
st.pts,
<String>{id},
);
await waitTick();
continue;
}
// 3) 弱结果 / 未识别:先与上一条尝试组合(图元库 → 内置两笔)。
if (prev != null) {
final ArchStroke p = prev!;
final ArchSymbolMatch? m2 = recognizeArchSymbol(
<List<Offset>>[p.pts, st.pts], SymbolCache.all);
if (m2 != null) {
prev = null;
prevBuiltin = null;
convert(
_symbolShapeFor(
m2.symbol,
_ptsBounds(p.pts).expandToInclude(_ptsBounds(st.pts)),
),
st.pts,
<String>{p.id, id},
);
await waitTick();
continue;
}
final ArchRecognition? r2 =
recognizeArchStrokes(<List<Offset>>[p.pts, st.pts]);
if (r2 != null && r2.type != ArchShapeType.line) {
prev = null;
prevBuiltin = null;
convert(
_snapShapeToGrid(archShapeFromRecognition(r2,
id: archNewId('S', c.arch.allIds), color: c.archColor)),
st.pts,
<String>{p.id, id},
);
await waitTick();
continue;
}
await flushPrev();
}
prev = st;
prevBuiltin = r;
}
await flushPrev();
_playing = false;
}
// ===================== 坐标与命中 =====================
/// 屏幕坐标 → 世界坐标。
Offset _toWorld(Offset screen) => Offset(
(screen.dx - c.arch.panX) / c.arch.zoom,
(screen.dy - c.arch.panY) / c.arch.zoom,
);
/// 命中测试:返回 (id, 图形?)。优先图形 → 连线 → 墨迹(后者在上层);
/// 隐藏图层与锁定图层的对象不可选中。[connTol] > 0 时覆盖连线的命中宽容
/// (平板 / 手指选中连线时放大)。
(String?, ArchShape?) _hitTest(Offset world, {double connTol = 0}) {
final ArchDoc doc = c.arch;
for (int i = doc.shapes.length - 1; i >= 0; i--) {
final ArchShape s = doc.shapes[i];
if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) {
continue;
}
if (s.hitTest(world)) return (s.id, s);
}
final ArchConnector? cn = _connAt(
world,
connTol > 0 ? connTol : (8 / c.arch.zoom + 4),
);
if (cn != null) return (cn.id, null);
for (int i = doc.strokes.length - 1; i >= 0; i--) {
final ArchStroke s = doc.strokes[i];
if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) {
continue;
}
if (s.hitTest(world)) return (s.id, null);
}
return (null, null);
}
/// 命中连线(最上层优先;隐藏 / 锁定图层跳过)。
ArchConnector? _connAt(Offset world, double tol) {
final ArchDoc doc = c.arch;
for (int i = doc.connectors.length - 1; i >= 0; i--) {
final ArchConnector cn = doc.connectors[i];
if (!doc.isLayerVisible(cn.layerId) || doc.isLayerLocked(cn.layerId)) {
continue;
}
final ArchConnGeometry g = archConnectorGeometry(doc, cn);
for (int k = 0; k < g.pts.length - 1; k++) {
if (archDistToSegment(world, g.pts[k], g.pts[k + 1]) <= tol) {
return cn;
}
}
}
return null;
}
/// 命中的图形(宽容 [pad],用于手绘箭头端点与连线自动吸附;
/// 锁定图层仍可作为吸附参照,隐藏图层不可)。
ArchShape? _shapeAt(Offset world, {double pad = 6}) {
final ArchDoc doc = c.arch;
for (int i = doc.shapes.length - 1; i >= 0; i--) {
if (!doc.isLayerVisible(doc.shapes[i].layerId)) continue;
if (doc.shapes[i].hitTest(world, pad: pad)) return doc.shapes[i];
}
return null;
}
// ---- 连线拖拽辅助(端点 / 折点 / 线段 + 吸附导引) ----
/// 开始连线拖拽(端点 / 折点模式)。
void _beginConnDrag(ArchConnector conn, String mode) {
_connVertexOrigin = conn;
_connVertexUpdated = null;
_connDragMode = mode;
_connDragTargetId = null;
_connSegAxis = null;
_connSegSeed = null;
_guideXs = const <double>[];
_guideYs = const <double>[];
setState(() {});
}
/// 开始连线线段拖动:把路径中间台阶物化为折点,整体平移该段。
void _beginConnSegmentDrag(
ArchConnector conn,
ArchConnGeometry g,
Offset world,
int k,
bool hasA,
bool hasB,
) {
final List<Offset> pts = g.pts;
final int last = pts.length - 1;
final Offset d = pts[k + 1] - pts[k];
final bool segH = d.dx.abs() >= d.dy.abs();
List<Offset> mids;
String axis;
double seed;
if (conn.mids.isNotEmpty) {
mids = List<Offset>.of(conn.mids);
axis = segH ? 'y' : 'x';
seed = segH ? pts[k].dy : pts[k].dx;
} else {
// 无折点:优先取路径中间的可移动台阶(其两端均为折点)。
final int lo = hasA ? 2 : 1;
final int hi = hasB ? last - 2 : last - 1;
final List<Offset>? found = lo < hi ? <Offset>[pts[lo], pts[lo + 1]] : null;
if (found != null) {
mids = found;
final Offset fd = found[1] - found[0];
final bool fh = fd.dx.abs() >= fd.dy.abs();
axis = fh ? 'y' : 'x';
seed = fh ? found[0].dy : found[0].dx;
} else if (segH) {
// 直线:在抓取处生成竖台阶(之后随手指左右平移)。
axis = 'x';
seed = world.dx;
mids = <Offset>[
Offset(seed, pts.first.dy),
Offset(seed, pts.last.dy),
];
} else {
// 直线:在抓取处生成横台阶(之后随手指上下平移)。
axis = 'y';
seed = world.dy;
mids = <Offset>[
Offset(pts.first.dx, seed),
Offset(pts.last.dx, seed),
];
}
}
_connVertexOrigin = conn.copyWith(mids: mids);
_connVertexUpdated = _connVertexOrigin;
_connDragMode = 'segment';
_connDragTargetId = null;
_connSegAxis = axis;
_connSegSeed = seed;
_guideXs = const <double>[];
_guideYs = const <double>[];
setState(() {});
}
/// 连线拖拽吸附:磁力对齐(图元边 / 中心、其它连线折点、自身折点、
/// 图纸中心)+ 网格回退;返回导引虚线坐标(虚线由画笔统一绘制)。
ConnSnap _snapConnCoord(
Offset p,
ArchConnector? self, {
bool onlyX = false,
bool onlyY = false,
}) {
final double tol = 6 / c.arch.zoom;
double bx = p.dx;
double by = p.dy;
double? gx;
double? gy;
if (!onlyY) {
double best = tol + 0.0001;
double? val;
for (final double cx in _alignCandidates(self, x: true)) {
final double d = (cx - p.dx).abs();
if (d < best) {
best = d;
val = cx;
}
}
if (val != null) {
bx = val;
gx = val;
}
}
if (!onlyX) {
double best = tol + 0.0001;
double? val;
for (final double cy in _alignCandidates(self, x: false)) {
final double d = (cy - p.dy).abs();
if (d < best) {
best = d;
val = cy;
}
}
if (val != null) {
by = val;
gy = val;
}
}
if (c.arch.gridSnap) {
final Offset s = archSnapPoint(c.arch, Offset(bx, by));
if (gx == null && !onlyY) bx = s.dx;
if (gy == null && !onlyX) by = s.dy;
}
return (x: bx, y: by, gx: gx, gy: gy);
}
/// 对齐候补坐标:图元左 / 中 / 右(或上 / 中 / 下)、其它连线折点、
/// 自身折点、图纸中心。
Iterable<double> _alignCandidates(
ArchConnector? self, {
required bool x,
}) sync* {
for (final ArchShape s in c.arch.shapes) {
if (!c.arch.isLayerVisible(s.layerId)) continue;
final Rect r = s.rect;
yield x ? r.left : r.top;
yield x ? r.center.dx : r.center.dy;
yield x ? r.right : r.bottom;
}
for (final ArchConnector o in c.arch.connectors) {
if (self != null && o.id == self.id) continue;
final ArchConnGeometry g = archConnectorGeometry(c.arch, o);
for (final Offset q in g.pts) {
yield x ? q.dx : q.dy;
}
}
if (self != null) {
for (final Offset m in self.mids) {
yield x ? m.dx : m.dy;
}
}
yield x ? kArchPageSize.width / 2 : kArchPageSize.height / 2;
}
/// 鼠标样式:拖拽连线时抓取,手绘精确,悬停连线显示可抓取。
MouseCursor _mouseCursor() {
if (_connVertexOrigin != null) return SystemMouseCursors.grabbing;
if (c.archTool == ArchTool.pen) return SystemMouseCursors.precise;
if (c.archTool == ArchTool.select && _hoverConn) {
return SystemMouseCursors.grab;
}
return SystemMouseCursors.basic;
}
// ===================== 参数化草图:交互 =====================
/// 草图按下:选择 / 拖拽(约束求解)/ 绘制 / 修剪。
void _sketchDown(Offset world, PointerDownEvent e) {
final SketchDoc d = c.sketch;
final double z = c.arch.zoom <= 0 ? 1 : c.arch.zoom;
if (c.sketchTool == SketchTool.select) {
final SketchHit hit = sketchHitTest(
d,
world,
pointTol: 9 / z,
entityTol: 6 / z,
dimTol: 10 / z,
);
// 命令模式(约束 / 尺寸命令):点选优先交给命令状态机消费。
if (c.sketchPendingCons != null || c.sketchPendingDim != null) {
c.sketchCommandPick(hit);
setState(() {});
return;
}
if (hit.dimId != null) {
final int now = DateTime.now().millisecondsSinceEpoch;
final bool dbl = now - _lastClickMs < 400 &&
(e.localPosition - _lastClickPos).distance < 28;
c.selectSketchIds(<String>[hit.dimId!]);
if (dbl) {
_lastClickMs = 0;
_editSketchDim(d.dimById(hit.dimId!)!);
}
setState(() {});
return;
}
if (hit.pointId != null) {
c.selectSketchIds(<String>[hit.pointId!]);
_skDragPointId = hit.pointId;
c.beginSketchUndo();
c.dragSketch(points: <String, Offset>{hit.pointId!: world});
setState(() {});
return;
}
if (hit.entityId != null) {
final bool shift = HardwareKeyboard.instance.isShiftPressed;
if (shift) {
c.toggleSketchId(hit.entityId!);
} else if (!c.sketchSelIds.contains(hit.entityId)) {
c.selectSketchIds(<String>[hit.entityId!]);
}
final SketchEntity en = d.entityById(hit.entityId!)!;
final Offset? center = d.pointById(en.p1)?.pos;
final bool nearCenter =
center != null && (world - center).distance <= 9 / z;
if (en.kind != SketchKind.line && !nearCenter && center != null) {
final bool hasRDim = d.dims.any((SketchDim dd) =>
dd.type == SketchDimType.radius && dd.a == en.id);
if (!hasRDim) {
// 拖动圆 / 弧轮廓 → 调整半径(有半径尺寸时改为平移)。
_skDragRadiusId = en.id;
c.beginSketchUndo();
c.dragSketch(radii: <String, double>{
en.id: (world - center).distance,
});
setState(() {});
return;
}
}
// 平移:所有引用点同步位移(圆弧端点随行,保持刚性)。
_skDragEntityId = en.id;
_skDragStartWorld = world;
_skDragOrigPts.clear();
final List<String> pts =
en.kind == SketchKind.line ? <String>[en.p1, en.p2] : d.entityPointIds(en);
for (final String pid in pts) {
_skDragOrigPts[pid] = d.pointById(pid)?.pos ?? world;
}
c.beginSketchUndo();
setState(() {});
return;
}
// 空白:框选(复用画布框选状态)。
c.selectSketchIds(const <String>[]);
_marquee = true;
_mqStart = world;
_mqEnd = world;
setState(() {});
return;
}
// 绘制工具 / 修剪:逐个点击落点(自动捕捉)。
final SketchSnap snap = sketchSnap(
d,
world,
gridSnap: c.arch.gridSnap,
grid: c.arch.gridSize,
pointTol: 11 / z,
entityTol: 8 / z,
);
if (c.sketchTool == SketchTool.trim) {
final SketchHit hit =
sketchHitTest(d, world, pointTol: 2, entityTol: 7 / z, dimTol: 2);
final String? eid = hit.entityId;
if (eid == null) {
c.setStatus('修剪:请点击要删除的线段');
return;
}
final SketchDoc? out = sketchTrimLine(d, eid, world);
if (out == null) {
c.setStatus('修剪:仅支持直线(无交点时整条删除)');
return;
}
c.changeSketch((_) => out, status: '修剪直线');
return;
}
_skClicks.add(snap);
_skLiveSnap = snap;
if (c.sketchTool == SketchTool.line && _skClicks.length >= 2) {
final List<SketchSnap> cl = List<SketchSnap>.of(_skClicks);
_skClicks.clear();
_commitSketchLine(cl[0], cl[1]);
} else if (c.sketchTool == SketchTool.circle && _skClicks.length >= 2) {
final List<SketchSnap> cl = List<SketchSnap>.of(_skClicks);
_skClicks.clear();
_commitSketchCircle(cl[0], cl[1]);
} else if (c.sketchTool == SketchTool.arc && _skClicks.length >= 3) {
final List<SketchSnap> cl = List<SketchSnap>.of(_skClicks);
_skClicks.clear();
_commitSketchArc(cl[0], cl[1], cl[2]);
} else if (c.sketchTool == SketchTool.rect && _skClicks.length >= 2) {
final List<SketchSnap> cl = List<SketchSnap>.of(_skClicks);
_skClicks.clear();
_commitSketchRect(cl[0], cl[1]);
}
setState(() {});
}
/// 草图拖动:拖点 / 拖实体 / 改半径 → 实时约束求解;绘制中更新捕捉与预览。
void _sketchMove(Offset world) {
if (_skDragPointId != null) {
c.dragSketch(points: <String, Offset>{_skDragPointId!: world});
return;
}
if (_skDragEntityId != null && _skDragOrigPts.isNotEmpty) {
final Offset delta = world - _skDragStartWorld;
c.dragSketch(points: <String, Offset>{
for (final MapEntry<String, Offset> e in _skDragOrigPts.entries)
e.key: e.value + delta,
});
return;
}
if (_skDragRadiusId != null) {
final Offset? center =
c.sketch.pointById(c.sketch.entityById(_skDragRadiusId!)?.p1)?.pos;
if (center != null) {
c.dragSketch(radii: <String, double>{
_skDragRadiusId!: (world - center).distance,
});
}
return;
}
if (_marquee) {
_mqEnd = world;
setState(() {});
return;
}
final double z = c.arch.zoom <= 0 ? 1 : c.arch.zoom;
final SketchSnap snap = sketchSnap(
c.sketch,
world,
gridSnap: c.arch.gridSnap,
grid: c.arch.gridSize,
pointTol: 11 / z,
entityTol: 8 / z,
);
_skLiveSnap = snap;
setState(() {});
}
/// 草图抬起:结束拖拽 / 提交框选。
void _sketchUp(Offset world, bool moved) {
if (_skDragPointId != null ||
_skDragEntityId != null ||
_skDragRadiusId != null) {
_skDragPointId = null;
_skDragEntityId = null;
_skDragRadiusId = null;
_skDragOrigPts.clear();
return;
}
if (_marquee) {
final Rect r = Rect.fromPoints(_mqStart ?? world, _mqEnd ?? world);
_marquee = false;
if (r.width < 3 && r.height < 3) {
setState(() {});
return;
}
final List<String> ids = <String>[];
for (final SketchPoint p in c.sketch.points) {
if (r.contains(p.pos)) ids.add(p.id);
}
for (final SketchEntity en in c.sketch.entities) {
final List<String> pts = c.sketch.entityPointIds(en);
if (pts.isNotEmpty &&
pts.every(
(String pid) => r.contains(c.sketch.pointById(pid)!.pos))) {
ids.add(en.id);
}
}
c.selectSketchIds(ids);
setState(() {});
}
}
/// 绘制预览(橡皮筋)。
SketchPreview? _skPreview() {
if (!c.sketchMode || _skClicks.isEmpty) return null;
final Offset first = _skClicks.first.pos;
final Offset last = _skLiveSnap?.pos ?? first;
if (c.sketchTool == SketchTool.line) {
return SketchPreview(pts: <Offset>[first, last]);
}
if (c.sketchTool == SketchTool.circle) {
return SketchPreview(
pts: <Offset>[first, last], kind: SketchKind.circle);
}
if (c.sketchTool == SketchTool.arc) {
if (_skClicks.length == 1) {
return SketchPreview(
pts: <Offset>[first, last], kind: SketchKind.circle);
}
return SketchPreview(
pts: <Offset>[first, _skClicks[1].pos, last],
kind: SketchKind.arc,
);
}
if (c.sketchTool == SketchTool.rect) {
return SketchPreview(
pts: <Offset>[
first,
Offset(last.dx, first.dy),
last,
Offset(first.dx, last.dy),
],
closed: true,
);
}
return null;
}
/// 新建点(若捕捉到已有点则复用)。
SketchPoint _skPoint(SketchSnap snap, List<String> fresh) {
final String id = sketchNewId('P', <String>[...c.sketch.allIds, ...fresh]);
return SketchPoint(id: id, x: snap.pos.dx, y: snap.pos.dy);
}
/// 提交直线(两端捕捉:已有 → 复用;实体上 → pointOnEntity;近轴 → 自动约束)。
void _commitSketchLine(SketchSnap a, SketchSnap b) {
SketchDoc d = c.sketch;
final List<SketchPoint> addPts = <SketchPoint>[];
final List<String> fresh = <String>[];
final List<SketchConstraint> extra = <SketchConstraint>[];
String idFor(SketchSnap snap, List<String> into, List<SketchPoint> pts,
List<SketchConstraint> cons) {
if (snap.pointId != null) return snap.pointId!;
final SketchPoint p = _skPoint(snap, <String>[...fresh, ...into]);
into.add(p.id);
pts.add(p);
if (snap.entityId != null) {
cons.add(SketchConstraint(
id: sketchNewId('K', <String>[
...d.allIds,
...fresh,
...cons.map((SketchConstraint x) => x.id),
]),
type: SketchConsType.pointOnEntity,
a: p.id,
b: snap.entityId!,
));
}
return p.id;
}
final List<String> ids = <String>[];
final String p1 = idFor(a, ids, addPts, extra);
final String p2 = idFor(b, ids, addPts, extra);
if (p1 == p2) return;
for (final SketchPoint p in addPts) {
d = d.upsertPoint(p);
}
final String eid = sketchNewId('E', <String>[...d.allIds, ...ids]);
d = d.upsertEntity(
SketchEntity(id: eid, kind: SketchKind.line, p1: p1, p2: p2));
final Offset pa = d.pointById(p1)!.pos;
final Offset pb = d.pointById(p2)!.pos;
final SketchConsType? axis = sketchAutoAxis(pa, pb);
if (axis != null) {
extra.add(SketchConstraint(
id: sketchNewId('K', <String>[
...d.allIds,
...extra.map((SketchConstraint x) => x.id),
]),
type: axis,
a: eid,
));
}
d = d.copyWith(constraints: <SketchConstraint>[...d.constraints, ...extra]);
final SketchSolveResult r = solveSketch(d);
c.changeSketch(
(_) => r.doc,
status: '草图:直线'
'${axis != null ? '(自动${sketchConsLabel(axis)})' : ''}',
);
}
/// 提交圆(圆心捕捉;第二点定半径)。
void _commitSketchCircle(SketchSnap a, SketchSnap b) {
SketchDoc d = c.sketch;
String center = a.pointId ?? '';
if (center.isEmpty) {
final SketchPoint p = _skPoint(a, const <String>[]);
d = d.upsertPoint(p);
center = p.id;
if (a.entityId != null) {
d = d.copyWith(constraints: <SketchConstraint>[
...d.constraints,
SketchConstraint(
id: sketchNewId('K', d.allIds),
type: SketchConsType.pointOnEntity,
a: center,
b: a.entityId!,
),
]);
}
}
final double r = (b.pos - d.pointById(center)!.pos).distance;
if (r < 2) return;
final String eid = sketchNewId('E', d.allIds);
d = d.upsertEntity(
SketchEntity(id: eid, kind: SketchKind.circle, p1: center, r: r));
c.changeSketch((_) => d, status: '草图:圆 R${r.round()}');
}
/// 提交圆弧(圆心 → 起点 → 终点;端点自动落在圆上)。
void _commitSketchArc(SketchSnap a, SketchSnap b, SketchSnap cc) {
SketchDoc d = c.sketch;
String center = a.pointId ?? '';
if (center.isEmpty) {
final SketchPoint p = _skPoint(a, const <String>[]);
d = d.upsertPoint(p);
center = p.id;
}
String ps = b.pointId ?? '';
if (ps.isEmpty) {
final SketchPoint p = _skPoint(b, <String>[center]);
d = d.upsertPoint(p);
ps = p.id;
}
String pe = cc.pointId ?? '';
if (pe.isEmpty) {
final SketchPoint p = _skPoint(cc, <String>[center, ps]);
d = d.upsertPoint(p);
pe = p.id;
}
final double r = (d.pointById(ps)!.pos - d.pointById(center)!.pos).distance;
if (r < 2 || ps == pe) return;
final String eid = sketchNewId('E', d.allIds);
d = d.upsertEntity(SketchEntity(
id: eid,
kind: SketchKind.arc,
p1: center,
p2: ps,
p3: pe,
r: r,
));
final SketchSolveResult res = solveSketch(d);
c.changeSketch((_) => res.doc, status: '草图:圆弧 R${r.round()}');
}
/// 提交矩形(对角两点;四边自动水平 / 竖直,共享角点)。
void _commitSketchRect(SketchSnap a, SketchSnap b) {
SketchDoc d = c.sketch;
final Offset tl = a.pos;
final Offset br = b.pos;
if ((br - tl).distance < 4) return;
final List<String> fresh = <String>[];
String pt(SketchSnap? snap, Offset pos) {
if (snap?.pointId != null) return snap!.pointId!;
final String id = sketchNewId('P', <String>[...d.allIds, ...fresh]);
fresh.add(id);
d = d.upsertPoint(SketchPoint(id: id, x: pos.dx, y: pos.dy));
return id;
}
final String p1 = pt(a, tl);
final String p2 = pt(null, Offset(br.dx, tl.dy));
final String p3 = pt(b, br);
final String p4 = pt(null, Offset(tl.dx, br.dy));
final String e1 = sketchNewId('E', <String>[...d.allIds, ...fresh]);
final String e2 = sketchNewId('E', <String>[...d.allIds, ...fresh, e1]);
final String e3 = sketchNewId('E', <String>[...d.allIds, ...fresh, e1, e2]);
final String e4 =
sketchNewId('E', <String>[...d.allIds, ...fresh, e1, e2, e3]);
d = d
.upsertEntity(SketchEntity(id: e1, kind: SketchKind.line, p1: p1, p2: p2))
.upsertEntity(SketchEntity(id: e2, kind: SketchKind.line, p1: p2, p2: p3))
.upsertEntity(SketchEntity(id: e3, kind: SketchKind.line, p1: p3, p2: p4))
.upsertEntity(
SketchEntity(id: e4, kind: SketchKind.line, p1: p4, p2: p1));
final List<SketchConstraint> cons = <SketchConstraint>[];
for (final (SketchConsType typ, String eid2) in <(SketchConsType, String)>[
(SketchConsType.horizontal, e1),
(SketchConsType.vertical, e2),
(SketchConsType.horizontal, e3),
(SketchConsType.vertical, e4),
]) {
cons.add(SketchConstraint(
id: sketchNewId('K', <String>[
...d.allIds,
...cons.map((SketchConstraint x) => x.id),
]),
type: typ,
a: eid2,
));
}
d = d.copyWith(constraints: <SketchConstraint>[...d.constraints, ...cons]);
final SketchSolveResult r = solveSketch(d);
c.changeSketch((_) => r.doc, status: '草图:矩形(自动水平 / 竖直)');
}
/// 编辑驱动尺寸(双击尺寸标签)。
Future<void> _editSketchDim(SketchDim d) async {
final String? input = await showTextEditDialog(
context,
title: '编辑${sketchDimLabel(d.type)}'
'(${d.type == SketchDimType.angle ? '度' : '像素'})',
initial: d.value.toStringAsFixed(1),
);
if (input == null || !mounted) return;
final double? v = double.tryParse(input.trim());
if (v == null || v <= 0) {
c.setStatus('数值无效:请输入正数');
return;
}
c.setSketchDimValue(d.id, v);
}
/// 橡皮擦:擦除 [world] 附近的图形 / 墨迹 / 连线(不删除锁定图层的对象)。
void _eraseAt(Offset world) {
final ArchDoc doc = c.arch;
final double z = c.arch.zoom <= 0 ? 1 : c.arch.zoom;
final Set<String> ids = <String>{};
for (final ArchStroke s in doc.strokes) {
if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) {
continue;
}
if (s.hitTest(world, pad: 10 / z)) ids.add(s.id);
}
for (final ArchShape s in doc.shapes) {
if (!doc.isLayerVisible(s.layerId) || doc.isLayerLocked(s.layerId)) {
continue;
}
if (s.hitTest(world, pad: 6 / z)) ids.add(s.id);
}
for (final ArchConnector cn in doc.connectors) {
if (!doc.isLayerVisible(cn.layerId) || doc.isLayerLocked(cn.layerId)) {
continue;
}
final ArchConnGeometry g = archConnectorGeometry(doc, cn);
final double tol = 10 / z + 4;
for (int k = 0; k < g.pts.length - 1; k++) {
if (archDistToSegment(world, g.pts[k], g.pts[k + 1]) <= tol) {
ids.add(cn.id);
break;
}
}
}
if (ids.isEmpty) return;
_eraseCount += c.eraseArchIds(ids);
setState(() {});
}
// ===================== 指针事件 =====================
/// 按下:进入捏合 / 平移 / 框选 / 手绘 / 连线 / 选择移动。
void _onPointerDown(PointerDownEvent e, Size size) {
_pointers[e.pointer] = e.localPosition;
if (_pointers.length >= 2) {
_cancelDrafts();
final List<Offset> ps = _pointers.values.toList();
_pinching = true;
_pinchStartDist = math.max(1, (ps[0] - ps[1]).distance);
_pinchStartZoom = c.arch.zoom;
_pinchStartFocal = (ps[0] + ps[1]) / 2;
_pinchStartPan = Offset(c.arch.panX, c.arch.panY);
_primaryPointer = null;
return;
}
_primaryPointer = e.pointer;
_downScreen = e.localPosition;
_touchDownAt = DateTime.now();
_touchDownPos = e.localPosition;
_touchEmpty = false;
final Offset world = _toWorld(e.localPosition);
final ArchTool tool = c.archTool;
final bool middle = (e.buttons & kMiddleMouseButton) != 0;
final bool secondary = (e.buttons & kSecondaryMouseButton) != 0;
final bool touch =
e.kind == PointerDeviceKind.touch || e.kind == PointerDeviceKind.stylus;
if (middle || secondary) {
_panning = true;
_panStartScreen = e.localPosition;
_panStartPan = Offset(c.arch.panX, c.arch.panY);
return;
}
if (c.sketchMode) {
_sketchDown(world, e);
return;
}
if (tool == ArchTool.pen) {
_draft = <Offset>[world];
setState(() {});
return;
}
if (tool == ArchTool.eraser) {
// 橡皮:按下即开始擦除;连续拖动 = 一次撤销快照。
_erasing = true;
_eraseCount = 0;
c.beginArchErase();
_eraseAt(world);
return;
}
if (tool == ArchTool.connect) {
// 按住左键画路径:松手后识别为直线 / 折线并吸附到图形边框。
_connFromId = _shapeAt(world)?.id;
_draft = <Offset>[world];
setState(() {});
return;
}
// 选择工具:手柄 → 图形 → 空白(鼠标框选 / 触屏平移)。
final bool ctrl = HardwareKeyboard.instance.isControlPressed;
final ArchShape? soleSel =
c.archSelIds.length == 1 ? c.arch.shapeById(c.archSelId) : null;
if (soleSel != null && !soleSel.isLinear) {
final List<Rect> hs = archHandleRects(soleSel.rect, c.arch.zoom);
for (int i = 0; i < hs.length; i++) {
if (hs[i].inflate((touch ? 12 : 4) / c.arch.zoom).contains(world)) {
_resizeHandle = i;
_resizeOrigin = soleSel;
_resizeRect = soleSel.rect;
_moveStartWorld = world;
return;
}
}
}
if (soleSel != null && soleSel.isLinear) {
// 折线 / 曲线 / 直线:允许拖动折点(先于整体命中,手柄优先)。
final List<Offset> vs = soleSel.type == ArchShapeType.line &&
soleSel.a != null &&
soleSel.b != null
? <Offset>[soleSel.a!, soleSel.b!]
: soleSel.pts;
final double tol = (touch ? 20 : 10) / c.arch.zoom;
for (int i = 0; i < vs.length; i++) {
if ((vs[i] - world).distance <= tol) {
_vertexIndex = i;
_vertexOrigin = soleSel;
_vertexPts = List<Offset>.of(vs);
setState(() {});
return;
}
}
}
// 连线拖拽编辑(选中单条连线时):端点 / 折点 / 线段三种拖动。
// 针对平板 / 手指:命中半径加大;路径任意一段可整体平移。
final ArchConnector? soleConn = c.archSelIds.length == 1
? c.arch.connectorById(c.archSelId)
: null;
if (soleConn != null &&
c.arch.isLayerVisible(soleConn.layerId) &&
!c.arch.isLayerLocked(soleConn.layerId)) {
final ArchDoc adoc = c.arch;
final bool hasA = adoc.shapeById(soleConn.fromId ?? '') != null;
final bool hasB = adoc.shapeById(soleConn.toId ?? '') != null;
final ArchConnGeometry g = archConnectorGeometry(adoc, soleConn);
final int last = g.pts.length - 1;
final double vTol = (touch ? 22 : 10) / c.arch.zoom;
for (int i = 0; i < g.pts.length; i++) {
if ((g.pts[i] - world).distance > vTol) continue;
if (i == 0 || i == last) {
// 端点:拖拽换吸附目标 / 脱离为自由端点(实时预览)。
_beginConnDrag(soleConn, 'endpoint');
_connVertexIndex = i;
return;
}
// 吸附端的固定短桩不单独拖动,交给线段拖动。
if ((hasA && i == 1) || (hasB && i == last - 1)) break;
// 折点:把路径拐点物化为折点后自由拖动(跳过两端固定短桩)。
final List<Offset> mids = <Offset>[];
int midIndex = 0;
for (int j = 1; j < last; j++) {
if (hasA && j == 1) continue;
if (hasB && j == last - 1) continue;
if (j < i) midIndex++;
mids.add(g.pts[j]);
}
_beginConnDrag(soleConn.copyWith(mids: mids), 'corner');
_connMidIndex = midIndex;
return;
}
// 线段拖动:命中路径任意一段 → 整体平移该段(磁力吸附 + 导引虚线)。
final double sTol = (touch ? 20 : 9) / c.arch.zoom;
for (int k = 0; k < last; k++) {
if (archDistToSegment(world, g.pts[k], g.pts[k + 1]) <= sTol) {
_beginConnSegmentDrag(soleConn, g, world, k, hasA, hasB);
return;
}
}
}
final (String?, ArchShape?) hit = _hitTest(
world,
connTol: touch ? 20 / c.arch.zoom : 0,
);
final String? id = hit.$1;
final ArchShape? shape = hit.$2;
if (id != null) {
final int now = DateTime.now().millisecondsSinceEpoch;
final bool dbl = now - _lastClickMs < 400 &&
(e.localPosition - _lastClickPos).distance < 28;
if (dbl) {
// 双击图形 / 折线曲线 / 连线:进入文字编辑(连线编辑标签)。
if (shape != null) {
_beginTextEdit(shape);
return;
}
final ArchConnector? cn = c.arch.connectorById(id);
if (cn != null) {
_beginConnLabelEdit(cn);
return;
}
}
if (!c.archSelIds.contains(id)) {
c.selectArch(id, toggle: ctrl);
} else if (ctrl) {
c.selectArch(id, toggle: true);
}
// 拖动已选中的图形 → 批量移动(只移动其中“可移动”的图形)。
final List<String> movables = <String>[
for (final String sid in c.archSelIds)
if (c.arch.shapeById(sid) != null) sid,
];
if (movables.isNotEmpty) {
_moveIds = movables;
_moveDeltas = null;
_moveStartWorld = world;
}
setState(() {});
return;
}
// 空白处双击 → 直接新建文本并进入输入(最直白的文字入口)。
{
final int now = DateTime.now().millisecondsSinceEpoch;
final bool dbl = now - _lastClickMs < 400 &&
(e.localPosition - _lastClickPos).distance < 28;
if (dbl) {
_lastClickMs = 0;
final ArchShape textShape = ArchShape(
id: archNewId('T', c.arch.allIds),
type: ArchShapeType.text,
rect: Rect.fromCenter(center: world, width: 180, height: 44),
fill: 0,
stroke: c.archColor,
sw: 0,
text: '',
);
c.addArchShape(textShape);
_beginTextEdit(textShape);
return;
}
}
// 空白处:鼠标 → 框选;触屏 → 平移(长按转框选)。
if (!touch) {
_marquee = true;
_mqStart = world;
_mqEnd = world;
setState(() {});
} else {
_panning = true;
_touchEmpty = true;
_panStartScreen = e.localPosition;
_panStartPan = Offset(c.arch.panX, c.arch.panY);
}
}
/// 移动:捏合 / 手绘 / 连线 / 移动 / 缩放 / 平移 / 框选。
void _onPointerMove(PointerMoveEvent e, Size size) {
if (!_pointers.containsKey(e.pointer)) return;
_pointers[e.pointer] = e.localPosition;
if (_pinching && _pointers.length >= 2) {
final List<Offset> ps = _pointers.values.toList();
final double dist = math.max(1, (ps[0] - ps[1]).distance);
final Offset focal = (ps[0] + ps[1]) / 2;
final double nz =
(_pinchStartZoom * dist / _pinchStartDist).clamp(0.15, 4.0).toDouble();
final Offset worldAtFocal =
(_pinchStartFocal - _pinchStartPan) / _pinchStartZoom;
c.archSetView(
zoom: nz,
panX: focal.dx - worldAtFocal.dx * nz,
panY: focal.dy - worldAtFocal.dy * nz,
);
return;
}
if (e.pointer != _primaryPointer) return;
final Offset world = _toWorld(e.localPosition);
if (c.sketchMode) {
_sketchMove(world);
return;
}
if (_erasing) {
_eraseAt(world);
return;
}
// 触屏长按(原地停顿)转为框选。
if (_panning && _touchEmpty && !_marquee) {
final bool still = (e.localPosition - _touchDownPos).distance < 10;
final bool held = DateTime.now().difference(_touchDownAt).inMilliseconds > 360;
if (still && held) {
_panning = false;
_marquee = true;
_mqStart = _toWorld(_touchDownPos);
_mqEnd = world;
setState(() {});
return;
}
}
if (_draft != null) {
if ((world - _draft!.last).distance > 1.1) {
_draft!.add(world);
setState(() {});
}
return;
}
if (_connVertexOrigin != null) {
final ArchConnector origin = _connVertexOrigin!;
final String mode = _connDragMode ?? 'corner';
if (mode == 'segment') {
// 线段拖动:沿垂直方向整体平移(磁力吸附 + 导引虚线)。
final bool axisX = _connSegAxis == 'x';
final ConnSnap snap = _snapConnCoord(
world,
origin,
onlyX: axisX,
onlyY: !axisX,
);
_guideXs = snap.gx == null ? const <double>[] : <double>[snap.gx!];
_guideYs = snap.gy == null ? const <double>[] : <double>[snap.gy!];
final double v = axisX ? snap.x : snap.y;
final double seed = _connSegSeed ?? v;
final List<Offset> mids = <Offset>[
for (final Offset m in origin.mids)
((axisX ? m.dx : m.dy) - seed).abs() < 0.75
? (axisX ? Offset(v, m.dy) : Offset(m.dx, v))
: m,
];
_connVertexUpdated = origin.copyWith(mids: mids);
setState(() {});
return;
}
if (mode == 'endpoint') {
// 端点:实时预览吸附(可换目标 / 脱离);空白处磁力吸附 + 网格回退。
final ArchShape? target = _shapeAt(
world,
pad: math.max(6, 10 / c.arch.zoom),
);
final bool isFrom = _connVertexIndex == 0;
Offset p;
String? targetId;
ConnSnap? snap;
if (target != null) {
p = archNearestBorderPoint(target, world);
targetId = target.id;
} else {
snap = _snapConnCoord(world, origin);
p = Offset(snap.x, snap.y);
targetId = null;
}
_connDragTargetId = targetId;
_guideXs =
snap?.gx == null ? const <double>[] : <double>[snap!.gx!];
_guideYs =
snap?.gy == null ? const <double>[] : <double>[snap!.gy!];
_connVertexUpdated = isFrom
? origin.copyWith(fromId: targetId, from: p)
: origin.copyWith(toId: targetId, to: p);
setState(() {});
return;
}
// 折点:磁力吸附(对齐虚线)+ 网格回退。
final ConnSnap snap = _snapConnCoord(world, origin);
_guideXs = snap.gx == null ? const <double>[] : <double>[snap.gx!];
_guideYs = snap.gy == null ? const <double>[] : <double>[snap.gy!];
final List<Offset> mids = List<Offset>.of(origin.mids);
if (_connMidIndex >= 0 && _connMidIndex < mids.length) {
mids[_connMidIndex] = Offset(snap.x, snap.y);
}
_connVertexUpdated = origin.copyWith(mids: mids);
setState(() {});
return;
}
if (_resizeHandle != null && _resizeOrigin != null) {
_resizeRect = _resizeFrom(_resizeOrigin!, _resizeHandle!, world);
setState(() {});
return;
}
if (_vertexPts != null && _vertexOrigin != null) {
_vertexPts![_vertexIndex] =
c.arch.gridSnap ? archSnapPoint(c.arch, world) : world;
setState(() {});
return;
}
if (_moveIds.isNotEmpty) {
Offset raw = world - _moveStartWorld;
// 正交 / 极轴:先把位移约束到主轴(正交)或极轴角度倍数(极轴)。
if (c.archOrtho || c.archPolar) {
raw = archConstrainDelta(
raw: raw,
ortho: c.archOrtho,
polar: c.archPolar,
polarDeg: c.archPolarDeg,
);
Offset delta = raw;
// 正交允许沿活动轴吸附网格;极轴保持角度不做二次吸附。
if (c.archOrtho && c.arch.gridSnap) {
final ArchShape? primary = c.arch.shapeById(_moveIds.first);
if (primary != null) {
final Offset snapped =
archSnapPoint(c.arch, primary.rect.topLeft + raw);
final Offset sd = snapped - primary.rect.topLeft;
delta = raw.dy == 0 ? Offset(sd.dx, 0) : Offset(0, sd.dy);
}
}
_guideXs = const <double>[];
_guideYs = const <double>[];
final Map<String, Offset> deltas = <String, Offset>{
for (final String id in _moveIds) id: delta,
};
_moveDeltas = deltas;
setState(() {});
return;
}
// 自由模式:磁力对齐线 + 网格回退。
Rect? union;
for (final String id in _moveIds) {
final ArchShape? sh = c.arch.shapeById(id);
if (sh == null) continue;
final Rect rr = sh.bounds.shift(raw);
union = union == null ? rr : union.expandToInclude(rr);
}
Offset delta = raw;
double? gx;
double? gy;
if (union != null) {
final ArchMoveSnap snap = archSnapMoveDelta(
doc: c.arch,
movingIds: _moveIds.toSet(),
union: union,
rawDelta: raw,
tol: 6 / c.arch.zoom,
gridSnap: c.arch.gridSnap,
);
delta = snap.delta;
gx = snap.guideX;
gy = snap.guideY;
}
_guideXs = gx == null ? const <double>[] : <double>[gx];
_guideYs = gy == null ? const <double>[] : <double>[gy];
final Map<String, Offset> deltas = <String, Offset>{};
for (final String id in _moveIds) {
deltas[id] = delta;
}
_moveDeltas = deltas;
setState(() {});
return;
}
if (_marquee) {
_mqEnd = world;
setState(() {});
return;
}
if (_panning) {
final Offset d = e.localPosition - _panStartScreen;
c.archSetView(panX: _panStartPan.dx + d.dx, panY: _panStartPan.dy + d.dy);
}
}
/// 抬起:提交草稿 / 移动 / 缩放 / 框选 / 点击。
void _onPointerUp(PointerEvent e, Size size) {
final Offset? upPos = _pointers.remove(e.pointer);
if (_pinching) {
if (_pointers.length < 2) _pinching = false;
return;
}
if (e.pointer != _primaryPointer) return;
_primaryPointer = null;
final Offset up = upPos ?? e.localPosition;
final bool moved = (up - _downScreen).distance > 6;
final Offset world = _toWorld(up);
// 干净点击(未拖动)时记录位置:供双击编辑文字 / 标签检测使用。
if (!moved) {
_lastClickMs = DateTime.now().millisecondsSinceEpoch;
_lastClickPos = up;
}
if (c.sketchMode) {
_sketchUp(world, moved);
return;
}
if (_erasing) {
_erasing = false;
if (_eraseCount > 0) {
c.setStatus('橡皮:已擦除 $_eraseCount 项(可一次撤销回退)');
}
setState(() {});
return;
}
if (_draft != null) {
final List<Offset> pts = _draft!;
_draft = null;
if (c.archTool == ArchTool.connect) {
_commitConnectorTrajectory(pts);
} else {
_commitInk(pts);
}
setState(() {});
return;
}
if (_connVertexOrigin != null) {
final ArchConnector? done = _connVertexUpdated;
final String mode = _connDragMode ?? 'corner';
final String? targetId = _connDragTargetId;
_connVertexOrigin = null;
_connVertexUpdated = null;
_connDragMode = null;
_connDragTargetId = null;
_connSegAxis = null;
_connSegSeed = null;
_guideXs = const <double>[];
_guideYs = const <double>[];
if (done != null) {
final String st = mode == 'endpoint'
? (targetId == null ? '连线端点:已脱离(自由端点)' : '连线端点:已吸附到图形')
: (mode == 'segment' ? '拖动连线路径' : '编辑连线折点');
c.updateArchConnector(done, status: st);
}
setState(() {});
return;
}
if (_resizeHandle != null && _resizeOrigin != null) {
final ArchShape origin = _resizeOrigin!;
final Rect? rect = _resizeRect;
_resizeHandle = null;
_resizeRect = null;
_resizeOrigin = null;
if (rect != null && rect != origin.rect) {
c.updateArchShape(origin.copyWith(rect: rect), status: '调整大小');
}
setState(() {});
return;
}
if (_vertexPts != null && _vertexOrigin != null) {
final ArchShape origin = _vertexOrigin!;
final List<Offset> pts = List<Offset>.of(_vertexPts!);
_vertexIndex = 0;
_vertexOrigin = null;
_vertexPts = null;
final ArchShape updated = origin.type == ArchShapeType.line
? origin.copyWith(
a: pts[0],
b: pts[1],
rect: Rect.fromPoints(pts[0], pts[1]),
)
: origin.copyWith(pts: pts, rect: _ptsBounds(pts));
c.updateArchShape(updated, status: '编辑折点');
setState(() {});
return;
}
if (_moveIds.isNotEmpty) {
final Map<String, Offset>? deltas = _moveDeltas;
_moveIds = <String>[];
_moveDeltas = null;
_guideXs = const <double>[];
_guideYs = const <double>[];
if (moved && deltas != null && deltas.isNotEmpty) {
c.moveArchShapes(deltas);
} else {
_lastClickMs = DateTime.now().millisecondsSinceEpoch;
_lastClickPos = up;
}
setState(() {});
return;
}
if (_marquee) {
final Offset? a = _mqStart;
_marquee = false;
_mqStart = null;
_mqEnd = null;
if (moved && a != null) {
_applyMarquee(Rect.fromPoints(a, world));
} else {
c.selectArch(null);
_lastClickMs = DateTime.now().millisecondsSinceEpoch;
_lastClickPos = up;
}
setState(() {});
return;
}
if (_panning) {
_panning = false;
_touchEmpty = false;
if (!moved && !_touchEmpty) {
c.selectArch(null);
_lastClickMs = DateTime.now().millisecondsSinceEpoch;
_lastClickPos = up;
}
}
}
/// 滚轮:以光标为锚缩放。
void _onScroll(PointerScrollEvent e, Size size) {
final double factor = math.exp(-e.scrollDelta.dy / 420);
c.archZoomAt(factor, e.localPosition);
}
/// 框选:选中与矩形相交的图形 / 连线 / 墨迹(隐藏 / 锁定图层跳过)。
void _applyMarquee(Rect r) {
final List<String> ids = <String>[];
for (final ArchShape s in c.arch.shapes) {
if (!c.arch.isLayerVisible(s.layerId) || c.arch.isLayerLocked(s.layerId)) {
continue;
}
if (s.bounds.overlaps(r)) ids.add(s.id);
}
for (final ArchConnector cn in c.arch.connectors) {
if (!c.arch.isLayerVisible(cn.layerId) ||
c.arch.isLayerLocked(cn.layerId)) {
continue;
}
final ArchConnGeometry g = archConnectorGeometry(c.arch, cn);
if (_ptsBounds(g.pts).overlaps(r)) ids.add(cn.id);
}
for (final ArchStroke s in c.arch.strokes) {
if (!c.arch.isLayerVisible(s.layerId) || c.arch.isLayerLocked(s.layerId)) {
continue;
}
if (s.bounds.overlaps(r)) ids.add(s.id);
}
c.selectArchIds(ids);
}
/// 点集外接矩形。
Rect _ptsBounds(List<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);
}
/// 取消所有进行中的草稿(进入捏合 / Esc)。
void _cancelDrafts() {
_draft = null;
_connFromId = null;
_connVertexOrigin = null;
_connVertexUpdated = null;
_connDragMode = null;
_connDragTargetId = null;
_connSegAxis = null;
_connSegSeed = null;
_moveIds = <String>[];
_moveDeltas = null;
_guideXs = const <double>[];
_guideYs = const <double>[];
_resizeHandle = null;
_resizeRect = null;
_resizeOrigin = null;
_vertexOrigin = null;
_vertexPts = null;
_panning = false;
_touchEmpty = false;
_marquee = false;
_mqStart = null;
_mqEnd = null;
setState(() {});
}
/// 键盘:Del 删除选中;Esc 取消;F8 正交;F10 极轴。
KeyEventResult _onKey(FocusNode node, KeyEvent e) {
if (e is! KeyDownEvent) return KeyEventResult.ignored;
if (e.logicalKey == LogicalKeyboardKey.f8) {
c.setArchOrtho(!c.archOrtho);
return KeyEventResult.handled;
}
if (e.logicalKey == LogicalKeyboardKey.f10) {
c.setArchPolar(!c.archPolar);
return KeyEventResult.handled;
}
if (e.logicalKey == LogicalKeyboardKey.delete ||
e.logicalKey == LogicalKeyboardKey.backspace) {
if (c.archSelIds.isNotEmpty && _editId == null) {
c.removeArchSelection();
return KeyEventResult.handled;
}
}
if (e.logicalKey == LogicalKeyboardKey.escape) {
_cancelDrafts();
if (_editId == null) c.selectArch(null);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
// ===================== 编辑操作 =====================
/// 提交手画连线轨迹:识别为直线 / 折线,端点吸附图形边框。
void _commitConnectorTrajectory(List<Offset> pts) {
if (pts.length < 2) return;
double len = 0;
for (int i = 1; i < pts.length; i++) {
len += (pts[i] - pts[i - 1]).distance;
}
if (len < 12) return;
// 优先用图形识别(直线 / 折线带近轴扶正);否则把轨迹简化为折线。
final ArchRecognition? r = recognizeArchStroke(pts);
List<Offset> v;
if (r != null && r.type == ArchShapeType.line) {
v = <Offset>[r.a ?? pts.first, r.b ?? pts.last];
} else if (r != null &&
r.type == ArchShapeType.polyline &&
(r.pts?.length ?? 0) >= 2) {
v = List<Offset>.of(r.pts!);
} else {
v = simplifyArchPolyline(pts);
}
if (v.length < 2) return;
final Offset p0 = v.first;
final Offset p1 = v.last;
// 端点吸附:起点优先用按下时命中的图形;终点按松手位置命中。
final ArchShape? sf = c.arch.shapeById(_connFromId) ?? _shapeAt(p0);
final ArchShape? st = _shapeAt(p1);
final bool snap = c.arch.gridSnap;
final Offset from = sf != null
? archNearestBorderPoint(sf, p0)
: (snap ? archSnapPoint(c.arch, p0) : p0);
final Offset to = st != null
? archNearestBorderPoint(st, p1)
: (snap ? archSnapPoint(c.arch, p1) : p1);
_connFromId = null;
if ((to - from).distance < 12) return;
// 连线一律正交:把手绘轨迹正交化(保留折点位置,所有段横平竖直)。
final List<Offset> ortho = orthoPolyline(<Offset>[
from,
...v.sublist(1, v.length - 1),
to,
]);
final List<Offset> mids = ortho.length > 2
? ortho.sublist(1, ortho.length - 1)
: const <Offset>[];
c.addArchConnector(ArchConnector(
id: archNewId('C', c.arch.allIds),
fromId: sf?.id,
from: from,
toId: st?.id,
to: to,
mids: mids,
route: ArchRoute.ortho,
));
}
/// 按目标外接框生成图元图形(保持图元自然纵横比)。
ArchShape _symbolShapeFor(LibSymbol sym, Rect b) {
final Rect nat = symbolNaturalBounds(sym);
double w = math.max(b.width, 24);
double h = nat.width <= 0 ? w : w * nat.height / nat.width;
if (b.height > h) {
h = b.height;
w = nat.height <= 0 ? w : h * nat.width / nat.height;
}
return ArchShape(
id: archNewId('S', c.arch.allIds),
type: ArchShapeType.symbol,
symbolId: sym.id,
rect: Rect.fromCenter(center: b.center, width: w, height: h),
fill: archFillOf(c.archColor),
stroke: c.archColor,
sw: 1.8,
);
}
/// 图元库识别命中:按笔迹外接框生成图元图形并播放转化动画。
void _commitSymbolConversion(
List<Offset> pts,
LibSymbol sym, {
required Set<String> removeIds,
}) {
final Rect b = _ptsBounds(pts);
_startConversion(pts, _symbolShapeFor(sym, b), removeIds: removeIds);
}
/// 提交手绘:统一按图形识别处理(识别失败保留墨迹),并尝试两笔组合识别。
void _commitInk(List<Offset> pts) {
if (pts.length < 5) return;
double len = 0;
for (int i = 1; i < pts.length; i++) {
len += (pts[i] - pts[i - 1]).distance;
}
if (len < 24) return;
// 手动确认识别(平板推荐):只保留墨迹,点顶部「识别 N」按钮统一处理。
if (!c.archAutoRecognize) {
final ArchStroke st = ArchStroke(
id: archNewId('K', c.arch.allIds),
pts: pts,
color: c.archColor,
);
c.addArchStroke(st);
c.setStatus('墨迹已保留(${c.arch.strokes.length} 笔待识别)· 点顶部「识别」确认');
return;
}
// 图元库组合(回溯):2.5 秒内新笔迹先尝试与「上一步刚生成的图形」
// 合成图元(如 圆 + 叉 = 指示灯)——即使第一笔已被即时识别成标准图形。
final String? convId = _lastConvId;
final DateTime? convAt = _lastConvAt;
if (convId != null &&
convAt != null &&
DateTime.now().difference(convAt).inMilliseconds <= 2500 &&
c.arch.shapeById(convId) != null) {
final ArchSymbolMatch? sm = recognizeArchSymbol(
<List<Offset>>[_lastConvPts, pts], SymbolCache.all);
if (sm != null) {
final Rect prevRect = c.arch.shapeById(convId)!.rect;
final Rect b = prevRect.expandToInclude(_ptsBounds(pts));
_lastConvId = null;
_startConversion(
pts,
_symbolShapeFor(sm.symbol, b),
removeIds: <String>{convId},
);
return;
}
}
final ArchRecognition? r = recognizeArchStroke(pts);
if (r == null) {
final ArchStroke st = ArchStroke(
id: archNewId('K', c.arch.allIds),
pts: pts,
color: c.archColor,
);
c.addArchStroke(st);
// 图元库识别(可扩展):内置识别不了的笔迹先匹配图元库(单笔)。
final ArchSymbolMatch? sm1 =
recognizeArchSymbol(<List<Offset>>[pts], SymbolCache.all);
if (sm1 != null) {
_commitSymbolConversion(pts, sm1.symbol, removeIds: <String>{st.id});
_lastInkId = null;
_lastInkAt = null;
return;
}
// 两笔组合:先按图元库匹配(如「圆 + 叉 = 指示灯」),再走内置组合。
final String? prevId = _lastInkId;
final DateTime? prevAt = _lastInkAt;
if (prevId != null &&
prevAt != null &&
DateTime.now().difference(prevAt).inSeconds <= 10) {
final ArchStroke? prev = c.arch.strokeById(prevId);
if (prev != null) {
final ArchSymbolMatch? sm2 = recognizeArchSymbol(
<List<Offset>>[prev.pts, pts], SymbolCache.all);
if (sm2 != null) {
_commitSymbolConversion(
pts,
sm2.symbol,
removeIds: <String>{prevId, st.id},
);
_lastInkId = null;
_lastInkAt = null;
return;
}
final ArchRecognition? r2 =
recognizeArchStrokes(<List<Offset>>[prev.pts, pts]);
if (r2 != null && r2.type != ArchShapeType.line) {
final ArchShape shape = _snapShapeToGrid(archShapeFromRecognition(
r2,
id: archNewId('S', c.arch.allIds),
color: c.archColor,
));
_startConversion(
pts,
shape,
removeIds: <String>{prevId, st.id},
);
_lastInkId = null;
_lastInkAt = null;
return;
}
}
}
_lastInkId = st.id;
_lastInkAt = DateTime.now();
return;
}
_lastInkId = null;
_lastInkAt = null;
// 规则:手绘模式只出图形——连线请用「连线」工具(不再从箭头自动生成连线)。
final ArchShape shape =
_snapShapeToGrid(archShapeFromRecognition(
r,
id: archNewId('S', c.arch.allIds),
color: c.archColor,
));
// 圆柱拼接:与上一段「部件」(顶盖 / 柱体)组合成圆柱。
final String? partId = _lastPartId;
final ArchRecognition? partRec = _lastPartRec;
final DateTime? partAt = _lastPartAt;
if (partId != null &&
partRec != null &&
partAt != null &&
DateTime.now().difference(partAt).inSeconds <= 10 &&
c.arch.shapeById(partId) != null) {
final ArchRecognition? cyl = archCylinderFromRecognitions(partRec, r) ??
archCylinderFromRecognitions(r, partRec);
if (cyl != null) {
final ArchShape cylShape = _snapShapeToGrid(archShapeFromRecognition(
cyl,
id: archNewId('S', c.arch.allIds),
color: c.archColor,
));
_startConversion(pts, cylShape, removeIds: <String>{partId});
_lastPartId = null;
_lastPartRec = null;
_lastPartAt = null;
return;
}
}
_startConversion(pts, shape);
_lastPartId = shape.id;
_lastPartRec = r;
_lastPartAt = DateTime.now();
}
/// 折点拖动的实时预览图形。
ArchShape? _vertexPreview() {
final ArchShape? origin = _vertexOrigin;
final List<Offset>? pts = _vertexPts;
if (origin == null || pts == null) return null;
if (origin.type == ArchShapeType.line) {
return origin.copyWith(
a: pts[0],
b: pts[1],
rect: Rect.fromPoints(pts[0], pts[1]),
);
}
return origin.copyWith(pts: List<Offset>.of(pts), rect: _ptsBounds(pts));
}
/// 识别后按网格吸附图形位置(用户偏好「优先吸附网格」)。
ArchShape _snapShapeToGrid(ArchShape s) {
if (!c.arch.gridSnap || s.isLinear) return s;
final Offset tl = archSnapPoint(c.arch, s.rect.topLeft);
return s.copyWith(
rect: Rect.fromLTWH(tl.dx, tl.dy, s.rect.width, s.rect.height),
);
}
/// 由手柄拖拽计算新外接矩形(圆保持正圆,最小 24px,可吸附网格)。
Rect _resizeFrom(ArchShape origin, int handle, Offset world) {
final Rect r = origin.rect;
const double minSize = 24;
double l = r.left;
double t = r.top;
double rt = r.right;
double b = r.bottom;
final Offset snapped =
c.arch.gridSnap ? archSnapPoint(c.arch, world) : world;
switch (handle) {
case 0:
l = snapped.dx;
t = snapped.dy;
break;
case 1:
t = snapped.dy;
break;
case 2:
rt = snapped.dx;
t = snapped.dy;
break;
case 3:
rt = snapped.dx;
break;
case 4:
rt = snapped.dx;
b = snapped.dy;
break;
case 5:
b = snapped.dy;
break;
case 6:
l = snapped.dx;
b = snapped.dy;
break;
default:
l = snapped.dx;
}
if ((rt - l) < minSize) {
if (snapped.dx > r.center.dx) {
rt = l + minSize;
} else {
l = rt - minSize;
}
}
if ((b - t) < minSize) {
if (snapped.dy > r.center.dy) {
b = t + minSize;
} else {
t = b - minSize;
}
}
Rect nr = Rect.fromLTRB(l, t, rt, b);
if (origin.type == ArchShapeType.circle) {
final double side = math.max(nr.width, nr.height);
nr = Rect.fromCenter(center: r.center, width: side, height: side);
}
return nr;
}
/// 开始编辑图形文字(画布内联输入框)。
void _beginTextEdit(ArchShape s) => _beginEdit(s.id, s.text);
/// 开始编辑连线标签(画布内联输入框,定位在标签锚点处)。
void _beginConnLabelEdit(ArchConnector cn) => _beginEdit(cn.id, cn.label);
/// 开始内联编辑(图形文字 / 连线标签共用)。
void _beginEdit(String id, String initial) {
_editCtrl?.dispose();
_editCtrl = TextEditingController(text: initial);
_editFocus?.dispose();
_editFocus = FocusNode();
_editFocus!.addListener(() {
if (_editFocus?.hasFocus == false) _commitTextEdit();
});
_editId = id;
c.selectArch(id);
setState(() {});
WidgetsBinding.instance.addPostFrameCallback((_) {
_editFocus?.requestFocus();
});
}
/// 提交文字编辑(图形文字或连线标签)。
void _commitTextEdit() {
final String? id = _editId;
final TextEditingController? ctrl = _editCtrl;
if (id == null || ctrl == null) return;
_editId = null;
final ArchShape? s = c.arch.shapeById(id);
if (s != null) {
if (s.text != ctrl.text) {
c.updateArchShape(s.copyWith(text: ctrl.text), status: '编辑文字');
}
} else {
final ArchConnector? cn = c.arch.connectorById(id);
if (cn != null && cn.label != ctrl.text) {
c.updateArchConnector(cn.copyWith(label: ctrl.text),
status: '编辑连线标签');
}
}
setState(() {});
}
// ===================== 构建 =====================
/// 构建画布(含内联文字编辑与空状态提示)。
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return LayoutBuilder(
builder: (BuildContext ctx, BoxConstraints cons) {
final Size size = Size(cons.maxWidth, cons.maxHeight);
c.setArchViewport(size);
final ArchDoc doc = c.arch;
final Rect? mq = _marquee && _mqStart != null && _mqEnd != null
? Rect.fromPoints(_mqStart!, _mqEnd!)
: null;
return Focus(
autofocus: true,
onKeyEvent: _onKey,
child: MouseRegion(
cursor: _mouseCursor(),
onHover: (PointerHoverEvent e) {
final Offset w = _toWorld(e.localPosition);
final bool hover = c.archTool == ArchTool.select &&
_connVertexOrigin == null &&
_connAt(w, 10 / c.arch.zoom) != null;
final Offset? cur = _cursorWorld;
if (hover != _hoverConn ||
cur == null ||
(cur - w).distance > 0.4) {
setState(() {
_cursorWorld = w;
_hoverConn = hover;
});
}
},
onExit: (_) {
if (_cursorWorld != null) {
setState(() => _cursorWorld = null);
}
},
child: Listener(
onPointerDown: (PointerDownEvent e) => _onPointerDown(e, size),
onPointerMove: (PointerMoveEvent e) => _onPointerMove(e, size),
onPointerUp: (PointerUpEvent e) => _onPointerUp(e, size),
onPointerCancel: (PointerCancelEvent e) => _onPointerUp(e, size),
onPointerSignal: (PointerSignalEvent e) {
if (e is PointerScrollEvent) _onScroll(e, size);
},
// 裁剪到画布范围内:避免缩小 / 平移后内容(图形、栅格点、标尺线)
// 溢出到左侧边栏与顶部工具栏(CustomPaint 默认不裁剪)。
child: ClipRect(
child: Stack(
children: <Widget>[
Positioned.fill(
child: CustomPaint(
painter: ArchPainter(
doc: doc,
t: t,
selectedIds: c.archSelIds.toSet(),
conversions: _conversions,
nowMs: _nowMs,
draft: _draft,
penColor: c.archColor,
previewConnector: _connVertexUpdated,
guideXs: _guideXs,
guideYs: _guideYs,
cursorWorld: _cursorWorld,
showRulers: c.archRulers,
moveDeltas: _moveDeltas,
resizeId:
_resizeHandle != null ? _resizeOrigin?.id : null,
resizeRect: _resizeRect,
marquee: mq,
previewShape: _vertexPreview(),
sketchMode: c.sketchMode,
sketchSel: <String>{
...c.sketchSelIds,
...c.sketchPendingIds,
},
sketchPreview: _skPreview(),
sketchSnap: _skLiveSnap?.pos,
),
),
),
if (_editId != null) _textEditorOverlay(t),
if (c.sketchMode
? c.sketch.isEmpty && _skClicks.isEmpty
: doc.isEmpty && _draft == null)
_emptyHint(t),
],
),
),
),
),
);
},
);
}
/// 内联文字编辑框(覆盖在被编辑图形 / 连线标签锚点上)。
Widget _textEditorOverlay(Tokens t) {
if (_editId == null) return const SizedBox.shrink();
final TextEditingController? ctrl = _editCtrl;
if (ctrl == null) return const SizedBox.shrink();
final double z = c.arch.zoom;
Rect r;
final ArchShape? s = c.arch.shapeById(_editId);
if (s != null) {
r = s.rect;
} else {
final ArchConnector? cn = c.arch.connectorById(_editId);
if (cn == null) return const SizedBox.shrink();
final ArchConnGeometry g = archConnectorGeometry(c.arch, cn);
r = Rect.fromCenter(center: g.label, width: 170, height: 34);
}
return Positioned(
left: r.left * z + c.arch.panX,
top: r.top * z + c.arch.panY,
width: math.max(90, r.width * z),
height: math.max(30, r.height * z),
child: Material(
color: t.panel,
elevation: 3,
borderRadius: BorderRadius.circular(6),
child: TextField(
controller: ctrl,
focusNode: _editFocus,
autofocus: true,
textAlign: TextAlign.center,
maxLines: null,
style: TextStyle(
color: t.text,
fontSize: 12.5 * z.clamp(0.8, 1.4),
fontWeight: FontWeight.w600,
fontFamily: 'Microsoft YaHei UI',
fontFamilyFallback: const <String>[
'Microsoft YaHei',
'Segoe UI',
'sans-serif',
],
),
decoration: const InputDecoration(
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 6),
),
onSubmitted: (_) => _commitTextEdit(),
),
),
);
}
/// 空画布提示(不拦截指针)。
Widget _emptyHint(Tokens t) {
return IgnorePointer(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(Icons.gesture, size: 46, color: t.dim),
const SizedBox(height: 10),
Text(
c.sketchMode
? '参数化草图:左侧选「直线 / 圆 / 弧 / 矩形」点两下绘制;'
'选中对象加约束 / 尺寸,拖动实时求解'
: '按住拖动,随手画一个矩形 / 圆 / 箭头 / 折线 / 曲线,松手自动识别',
style: TextStyle(color: t.sub, fontSize: 13),
),
const SizedBox(height: 6),
Text(
'文字:双击空白处或图形直接输入;也可以从左侧「图形库」插入',
style: TextStyle(color: t.dim, fontSize: 11.5),
),
],
),
),
);
}
}