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