dsh-cad-studio 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -1
  2. package/index.js +413 -0
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -16,7 +16,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
16
16
  | 工程文件 | `cad_studio_doc` 存 `script` 或 `features` 两种模型;`cad_studio_features` 改一条特征→整表重算(0.2–0.6 s),失败整表回滚 |
17
17
  | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
- | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴) |
19
+ | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
20
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
21
21
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
22
22
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
@@ -24,6 +24,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
24
24
  | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
25
25
  | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
26
26
  | 面板改草图 | 特征抽屉里点「草图 N」展开:数值约束是可编辑输入框(`distance*`/`radius`/`angle` 按度),改完立刻重解并重建;解不出来就回滚并报错 |
27
+ | 撤销跨重启 | 文档级撤销栈(建/删/改名)写进 `<数据目录>/journal.json`,重启后仍可撤销;装配与视图的撤销只在本次会话内有效 |
27
28
  | 草图约束 | `equal`(等长)、`symmetric`(三点对称,需 `c` 点)、`angle`(**单位是度**,内部转弧度并在求解后重测);`distance` 是两点距离、`distance_x/y` 是该点的绝对坐标 |
28
29
  | 草图 + 放样/扫掠 | 草图存在文档里(`cad_studio_doc {action:"create", kind:"features", sketches:{S1:{geometry:[…],constraints:[…]}}, features:[{kind:"extrude",sketch:"S1",h:10}]}`);`loft` 用 `sections:[{sketch:"S1"},{sketch:"S2",at:[0,0,40]}]`,`sweep` 用 `path:[[x,y,z],…]`。改草图会重建(草图进了缓存哈希,不会命中旧 BREP) |
29
30
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
package/index.js CHANGED
@@ -919,6 +919,39 @@ class FreeCadBridge {
919
919
  this.sessionUndo.push({ at: new Date().toISOString(), ...entry })
920
920
  if (this.sessionUndo.length > 50) this.sessionUndo.shift()
921
921
  this.sessionRedo = []
922
+ // Only entries carrying a serialisable `record` survive a restart: a raw
923
+ // closure cannot be written to disk, so those stay session-only.
924
+ if (entry && entry.record) this.persistJournal()
925
+ }
926
+
927
+ /** Write the replayable slice of the undo stack (newest 20) to journal.json. */
928
+ persistJournal() {
929
+ const rows = this.sessionUndo
930
+ .filter((e) => e && e.record)
931
+ .slice(-20)
932
+ .map((e) => ({ at: e.at, kind: e.kind, label: e.label, record: e.record }))
933
+ writeFile(join(FreeCadBridge.dataDir, 'journal.json'), JSON.stringify({ version: 1, entries: rows }, null, 2)).catch(() => {})
934
+ }
935
+
936
+ /**
937
+ * Rebuild undo entries from journal.json. `makeEntry(record)` supplies the
938
+ * closures (it needs the document helpers, which live in the plugin scope),
939
+ * so the bridge itself stays free of FreeCAD knowledge.
940
+ */
941
+ async loadJournal(makeEntry) {
942
+ let raw = null
943
+ try { raw = JSON.parse(await readFile(join(FreeCadBridge.dataDir, 'journal.json'), 'utf8')) } catch { return 0 }
944
+ const rows = Array.isArray(raw && raw.entries) ? raw.entries : []
945
+ let restored = 0
946
+ for (const row of rows) {
947
+ let built = null
948
+ try { built = makeEntry(row.record) } catch { built = null }
949
+ if (!built) continue
950
+ this.sessionUndo.push({ at: row.at, kind: row.kind, label: row.label, ...built, restored: true })
951
+ restored += 1
952
+ }
953
+ if (restored) this.sessionUndo = this.sessionUndo.slice(-50)
954
+ return restored
922
955
  }
923
956
 
924
957
  async applyAssemblySnapshot(snapshot) {
@@ -931,6 +964,7 @@ class FreeCadBridge {
931
964
  }
932
965
 
933
966
  async undoSession(kind) {
967
+ if (this.journalReady) { try { await this.journalReady } catch {} }
934
968
  const stack = kind ? this.sessionUndo.filter((e) => e.kind === kind) : this.sessionUndo
935
969
  const entry = stack[stack.length - 1]
936
970
  if (!entry) return null
@@ -2380,6 +2414,291 @@ else:
2380
2414
  },
2381
2415
  })
2382
2416
 
2417
+ tool({
2418
+ name: 'cad_studio_sheet',
2419
+ description: 'Write a drawing sheet you can hand to a shop: sheet frame, title block, arranged HLR views (first- or third-angle), overall dimensions in mm, SVG (and optional DXF). Views are oriented to the usual convention (front = width x height, top = width x depth, right = depth x height) by measuring the projection basis instead of assuming it.',
2420
+ parameters: {
2421
+ type: 'object',
2422
+ properties: {
2423
+ target: { type: 'string', description: 'Absolute .svg output path.' },
2424
+ source: { type: 'string', description: 'Existing BRep model file (STEP/IGES/BREP).' },
2425
+ code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
2426
+ model: { type: 'string', description: 'Draw a saved model document by name instead of a file or a script.' },
2427
+ size: { type: 'string', description: 'Sheet size: A4, A3 or A2 (landscape). Default A3.' },
2428
+ projection: { type: 'string', description: 'first (GB/ISO, default) or third (ASME).' },
2429
+ views: { type: 'array', items: { type: 'string' }, description: 'Subset of ["front","top","right"]. Default all three.' },
2430
+ scale: { type: 'number', description: 'Drawing scale factor, e.g. 0.5 for 1:2. Omit to fit the sheet.' },
2431
+ title: { type: 'string', description: 'Part name for the title block.' },
2432
+ number: { type: 'string', description: 'Drawing number for the title block.' },
2433
+ material: { type: 'string', description: 'Material text for the title block.' },
2434
+ dims: { type: 'boolean', description: 'Draw overall dimension lines (default true).' },
2435
+ dxf: { type: 'boolean', description: 'Also write a sidecar .dxf next to the SVG.' },
2436
+ },
2437
+ required: ['target'],
2438
+ additionalProperties: false,
2439
+ },
2440
+ output: {
2441
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, scale: { type: 'number' } } },
2442
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2443
+ },
2444
+ execute: async ({ target, source, code, model, size, projection, views, scale, title, number, material, dims, dxf }) => {
2445
+ if (!target || extOf(target) !== 'svg') return { ok: false, error: 'target must be a .svg path' }
2446
+ let src = ''
2447
+ if (typeof model === 'string' && model) {
2448
+ src = await modelShapes(model)
2449
+ if (!src) return { ok: false, error: `没有这个模型:${model}` }
2450
+ } else {
2451
+ const x = shapesFrom({ source, code })
2452
+ if (!x) return { ok: false, error: 'pass either source (a model file), model (a saved document) or code' }
2453
+ src = x
2454
+ }
2455
+ const wanted = Array.isArray(views) && views.length ? views : ['front', 'top', 'right']
2456
+ const py = `${PRELUDE}
2457
+ ${src}
2458
+ import os, re, TechDraw
2459
+ _SIZES = {"A4": (297.0, 210.0), "A3": (420.0, 297.0), "A2": (594.0, 420.0)}
2460
+ # (view direction, horizontal model axis, vertical model axis) — the pair is what
2461
+ # a reader expects: front shows width x height, top shows width x depth.
2462
+ _WANT = {"front": ("X", "Z"), "top": ("X", "Y"), "right": ("Y", "Z")}
2463
+ _CAND = {"front": ((0, -1, 0), (0, 1, 0)), "top": ((0, 0, 1), (0, 0, -1)), "right": ((1, 0, 0), (-1, 0, 0))}
2464
+ _M = 10.0
2465
+ _TBW, _TBH = 180.0, 40.0
2466
+ _GAP = 26.0
2467
+ _PL = 10.0 # probe segment length (mm)
2468
+
2469
+ def _seg(vec):
2470
+ return Part.makeLine(FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(*vec))
2471
+
2472
+ def _nums(d):
2473
+ return [float(x) for x in re.findall(r'-?[0-9]+(?:[.][0-9]+)?(?:[eE]-?[0-9]+)?', d)]
2474
+
2475
+ def _axis_vectors(dv):
2476
+ """Fragment-space image of each model axis, as a unit vector (+-1, 0).
2477
+
2478
+ One 10 mm edge per axis, projected on its own: an axis pointing along the
2479
+ view direction collapses to nothing, the other two give their direction in
2480
+ the fragment. Probing beats guessing — TechDraw's basis is not the naive
2481
+ "front shows X-Z" one.
2482
+ """
2483
+ out = {}
2484
+ for name, vec in (("X", (_PL, 0, 0)), ("Y", (0, _PL, 0)), ("Z", (0, 0, _PL))):
2485
+ frag = TechDraw.projectToSVG(_seg(vec), FreeCAD.Vector(*dv))
2486
+ ds = re.findall(r'd="([^"]+)"', frag)
2487
+ if not ds:
2488
+ continue
2489
+ ns = _nums(ds[0])
2490
+ if len(ns) < 4:
2491
+ continue
2492
+ dx, dy = ns[-2] - ns[0], ns[-1] - ns[1]
2493
+ ln = math.hypot(dx, dy)
2494
+ if ln < 1e-6:
2495
+ continue # this axis is the view direction
2496
+ out[name] = (round(dx / ln), round(dy / ln))
2497
+ return out
2498
+
2499
+ def _solve(view):
2500
+ """Pick a projection direction whose fragment basis is a rotation.
2501
+
2502
+ F maps read-space (u', v') to fragment-space (u, v): its columns are the
2503
+ fragment images of the two read axes. det(F) < 0 means the drawing would be
2504
+ mirrored (a reader would see the part the wrong way round), so the opposite
2505
+ candidate direction wins instead.
2506
+ """
2507
+ pa, pb = _WANT[view]
2508
+ for dv in _CAND[view]:
2509
+ vec = _axis_vectors(dv)
2510
+ if pa not in vec or pb not in vec:
2511
+ continue
2512
+ fu, fv = vec[pa], vec[pb]
2513
+ det = fu[0] * fv[1] - fu[1] * fv[0]
2514
+ if det <= 0:
2515
+ continue
2516
+ inv = (fv[1] / det, -fv[0] / det, -fu[1] / det, fu[0] / det)
2517
+ return {"dir": dv, "inv": inv}
2518
+ return None
2519
+
2520
+ def _remap(frag, inv):
2521
+ """Rewrite the fragment paths in read-space, y flipped for SVG."""
2522
+ ia, ib, ic, id_ = inv
2523
+ out = []
2524
+ for d in re.findall(r'd="([^"]+)"', frag):
2525
+ ns = _nums(d)
2526
+ pts = [(ns[i], ns[i + 1]) for i in range(0, len(ns) - 1, 2)]
2527
+ if not pts:
2528
+ continue
2529
+ q = [(ia * x + ib * y, -(ic * x + id_ * y)) for x, y in pts]
2530
+ out.append("M " + " L ".join("%r %r" % p for p in q))
2531
+ return out
2532
+
2533
+ if not _shapes:
2534
+ __out = {"ok": False, "error": "nothing to draw: pass a source path, a model, or bind scene / export_shapes"}
2535
+ else:
2536
+ _shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
2537
+ _SW, _SH = _SIZES.get(str(${JSON.stringify(String(size || 'A3').toUpperCase())}).upper(), _SIZES["A3"])
2538
+ _wanted = [v for v in ${JSON.stringify(wanted)} if v in _WANT] or ["front", "top", "right"]
2539
+ _views = {}
2540
+ _missing = []
2541
+ for _v in _wanted:
2542
+ _sol = _solve(_v)
2543
+ if not _sol:
2544
+ _missing.append(_v)
2545
+ continue
2546
+ _paths = _remap(TechDraw.projectToSVG(_shape, FreeCAD.Vector(*_sol["dir"])), _sol["inv"])
2547
+ _pts = []
2548
+ for _d in _paths:
2549
+ _ns = _nums(_d)
2550
+ _pts += [(_ns[i], _ns[i + 1]) for i in range(0, len(_ns) - 1, 2)]
2551
+ if not _pts:
2552
+ _missing.append(_v)
2553
+ continue
2554
+ _xs = [p[0] for p in _pts]; _ys = [p[1] for p in _pts]
2555
+ _views[_v] = {"paths": _paths, "dir": _sol["dir"],
2556
+ "box": (min(_xs), min(_ys), max(_xs), max(_ys))}
2557
+ if _missing:
2558
+ __out = {"ok": False, "error": "无法为这些视图找到保持手性的投影方向:" + ", ".join(_missing)}
2559
+ else:
2560
+ _need_w = max(_views[v]["box"][2] - _views[v]["box"][0] for v in _wanted) + _GAP
2561
+ _need_h = max(_views[v]["box"][3] - _views[v]["box"][1] for v in _wanted) + _GAP
2562
+ _avail_w = _SW - 2 * _M
2563
+ _avail_h = _SH - 2 * _M - _TBH - 6.0
2564
+ _fit = min(_avail_w / max(_need_w, 1e-6), _avail_h / max(_need_h, 1e-6))
2565
+ _given = float(${Number.isFinite(scale) && Number(scale) > 0 ? Number(scale) : 0})
2566
+ if _given > 0:
2567
+ _scale = _given
2568
+ else:
2569
+ _scale = 0.0
2570
+ for _cand in (2.0, 1.5, 1.0, 0.5, 0.4, 0.25, 0.2, 0.1, 0.05):
2571
+ if _cand <= _fit:
2572
+ _scale = _cand
2573
+ break
2574
+ if _scale <= 0:
2575
+ _scale = _fit
2576
+
2577
+ def _size(view):
2578
+ _bx = _views[view]["box"]
2579
+ return ((_bx[2] - _bx[0]) * _scale, (_bx[3] - _bx[1]) * _scale)
2580
+
2581
+ _first = str(${JSON.stringify(String(projection || 'first').toLowerCase())}).lower() != "third"
2582
+ _cells = {}
2583
+ _fw, _fh = _size("front") if "front" in _views else (0.0, 0.0)
2584
+ for _v in _wanted:
2585
+ _w, _h = _size(_v)
2586
+ if _v == "front":
2587
+ _cells[_v] = (0.0, 0.0, _w, _h)
2588
+ elif _v == "top":
2589
+ _cells[_v] = (0.0, (_fh + _GAP) if _first else -(_h + _GAP), _w, _h)
2590
+ else:
2591
+ _cells[_v] = ((_fw + _GAP) if not _first else -(_w + _GAP), 0.0, _w, _h)
2592
+ _minx = min(c[0] for c in _cells.values()); _miny = min(c[1] for c in _cells.values())
2593
+ _maxx = max(c[0] + c[2] for c in _cells.values()); _maxy = max(c[1] + c[3] for c in _cells.values())
2594
+ _offx = _M + (_avail_w - (_maxx - _minx)) / 2.0 - _minx
2595
+ _offy = _M + (_avail_h - (_maxy - _miny)) / 2.0 - _miny
2596
+
2597
+ _views_svg = []; _dims_svg = []; _labels = []; _dim_list = []
2598
+ _draw_dims = bool(${dims === false ? 'False' : 'True'})
2599
+ for _v in _wanted:
2600
+ _vv = _views[_v]
2601
+ _n0x, _n0y, _n1x, _n1y = _vv["box"]
2602
+ _bw = _n1x - _n0x; _bh = _n1y - _n0y
2603
+ _cx, _cy, _w, _h = _cells[_v]
2604
+ _px = _cx + _offx; _py = _cy + _offy
2605
+ # The paths are already in read-space (y down); place the bbox corner
2606
+ # at the cell corner and scale.
2607
+ _views_svg.append('<g fill="none" stroke="#111" stroke-width="0.25" stroke-linejoin="round" stroke-linecap="round" '
2608
+ 'transform="translate(%r %r) scale(%r)">%s</g>' % (
2609
+ _px - _n0x * _scale, _py - _n0y * _scale, _scale,
2610
+ "".join('<path d="%s"/>' % _d for _d in _vv["paths"])))
2611
+ _labels.append('<text x="%r" y="%r" font-size="3.0" fill="#555" font-family="sans-serif" text-anchor="middle">%s</text>' % (
2612
+ _px + _w / 2.0, _py - 3.0, {"front": "主视图", "top": "俯视图", "right": "左视图"}.get(_v, _v)))
2613
+ _wm = round(_bw, 2); _hm = round(_bh, 2)
2614
+ _dim_list.append({"view": _v, "width_mm": _wm, "height_mm": _hm})
2615
+ if _draw_dims and _w > 1e-6 and _h > 1e-6:
2616
+ _yd = _py + _h + 9.0
2617
+ _xd = _px + _w + 9.0
2618
+ _dims_svg.append('<g stroke="#111" stroke-width="0.25" fill="none">'
2619
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2620
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2621
+ '<path d="M %r %r L %r %r"/>'
2622
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2623
+ '<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
2624
+ '<path d="M %r %r L %r %r"/></g>' % (
2625
+ _px, _py + _h, _px, _yd + 2.0, _px + _w, _py + _h, _px + _w, _yd + 2.0,
2626
+ _px, _yd, _px + _w, _yd,
2627
+ _px + _w, _py, _xd + 2.0, _py, _px + _w, _py + _h, _xd + 2.0, _py + _h,
2628
+ _xd, _py, _xd, _py + _h))
2629
+ _dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif">%s</text>' % (
2630
+ _px + _w / 2.0, _yd + 4.2, _wm))
2631
+ _dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif" transform="rotate(90 %r %r)">%s</text>' % (
2632
+ _xd + 7.0, _py + _h / 2.0, _xd + 7.0, _py + _h / 2.0, _hm))
2633
+
2634
+ _frame = ('<g stroke="#111" fill="none" stroke-width="0.5">'
2635
+ '<rect x="%r" y="%r" width="%r" height="%r"/>'
2636
+ '<rect x="%r" y="%r" width="%r" height="%r"/></g>' % (
2637
+ _M, _M, _SW - 2 * _M, _SH - 2 * _M,
2638
+ _M + 2.0, _M + 2.0, _SW - 2 * _M - 4.0, _SH - 2 * _M - 4.0))
2639
+ _tb_x = _SW - _M - _TBW
2640
+ _tb_y = _SH - _M - _TBH
2641
+ _title = str(${JSON.stringify(typeof title === 'string' ? title : '')}) or os.path.splitext(os.path.basename(${JSON.stringify(target)}))[0]
2642
+ _number = str(${JSON.stringify(typeof number === 'string' ? number : '')})
2643
+ _material = str(${JSON.stringify(typeof material === 'string' ? material : '')})
2644
+ _scale_txt = ("1:%g" % round(1.0 / _scale, 4)) if _scale < 1.0 else (("%g:1" % _scale) if _scale > 1.0 else "1:1")
2645
+ _tb = ['<g stroke="#111" fill="none" stroke-width="0.4">'
2646
+ '<rect x="%r" y="%r" width="%r" height="%r"/>'
2647
+ '<path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/></g>' % (
2648
+ _tb_x, _tb_y, _TBW, _TBH,
2649
+ _tb_x, _tb_y + 12.0, _tb_x + _TBW, _tb_y + 12.0,
2650
+ _tb_x, _tb_y + 24.0, _tb_x + _TBW, _tb_y + 24.0,
2651
+ _tb_x + 100.0, _tb_y + 12.0, _tb_x + 100.0, _tb_y + _TBH)]
2652
+ _tb.append('<text x="%r" y="%r" font-size="4.4" font-weight="600" fill="#111" font-family="sans-serif">%s</text>' % (
2653
+ _tb_x + 3.0, _tb_y + 8.4, _title.replace("&", "&amp;").replace("<", "&lt;")))
2654
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图号 %s</text>' % (
2655
+ _tb_x + 3.0, _tb_y + 19.4, (_number or "-")))
2656
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">材料 %s</text>' % (
2657
+ _tb_x + 3.0, _tb_y + 31.4, (_material or "-")))
2658
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">比例 %s</text>' % (
2659
+ _tb_x + 103.0, _tb_y + 19.4, _scale_txt))
2660
+ _tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图幅 %s · 单位 mm</text>' % (
2661
+ _tb_x + 103.0, _tb_y + 31.4, str(${JSON.stringify(String(size || 'A3').toUpperCase())})))
2662
+ _tb.append('<text x="%r" y="%r" font-size="2.8" fill="#666" font-family="sans-serif">%s</text>' % (
2663
+ _tb_x + 103.0, _tb_y + 8.4, __import__("datetime").date.today().isoformat()))
2664
+ _svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="%rmm" height="%rmm" viewBox="0 0 %r %r">'
2665
+ '<rect width="100%%" height="100%%" fill="white"/>%s%s%s%s%s</svg>') % (
2666
+ _SW, _SH, _SW, _SH, _frame, "".join(_views_svg), "".join(_dims_svg), "".join(_labels), "".join(_tb))
2667
+ os.makedirs(os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
2668
+ open(${JSON.stringify(target)}, "w").write(_svg)
2669
+ __out = {"ok": True, "path": ${JSON.stringify(target)}, "bytes": os.path.getsize(${JSON.stringify(target)}),
2670
+ "sheet_mm": [_SW, _SH], "scale": round(_scale, 4), "views": _wanted,
2671
+ "projection": "first" if _first else "third", "dimensions": _dim_list,
2672
+ "directions": {v: list(_views[v]["dir"]) for v in _wanted}}
2673
+ `
2674
+ const out = await bridge.run(py, { title: `sheet → ${target}`, publishHint: false })
2675
+ if (out && out.ok && dxf) {
2676
+ const side = target.replace(/\.svg$/i, '.dxf')
2677
+ const py2 = `${PRELUDE}
2678
+ ${src}
2679
+ import os, TechDraw
2680
+ _doc = FreeCAD.newDocument("sheet")
2681
+ _obj = _doc.addObject("Part::Feature", "S")
2682
+ _obj.Shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
2683
+ _page = _doc.addObject("TechDraw::DrawPage", "Page")
2684
+ for _v, _dir in (("front", (0, -1, 0)), ("top", (0, 0, 1)), ("right", (1, 0, 0))):
2685
+ _view = _doc.addObject("TechDraw::DrawViewPart", "V" + _v)
2686
+ _page.addView(_view)
2687
+ _view.Source = [_obj]
2688
+ _view.Direction = _dir
2689
+ _doc.recompute()
2690
+ _side = ${JSON.stringify(side)}
2691
+ os.makedirs(os.path.dirname(_side) or ".", exist_ok=True)
2692
+ TechDraw.writeDXFPage(_page, _side)
2693
+ __out = {"ok": True, "path": _side, "bytes": os.path.getsize(_side)}
2694
+ `
2695
+ const d = await bridge.run(py2, { title: `sheet dxf → ${side}`, publishHint: false })
2696
+ if (d && d.ok) out.dxf = { path: d.path, bytes: d.bytes }
2697
+ }
2698
+ return out
2699
+ },
2700
+ })
2701
+
2383
2702
  tool({
2384
2703
  name: 'cad_studio_measure',
2385
2704
  description: 'Measure a model: volume, surface area, bounding box, centroid, face/edge counts, and optionally the distance between two points.',
@@ -3483,6 +3802,7 @@ if _TARGET:
3483
3802
  bridge.journal({
3484
3803
  kind: 'doc',
3485
3804
  label: `create ${key}`,
3805
+ record: { op: 'doc-create', model: key, dir, sceneId: sceneRow ? sceneRow.id : '' },
3486
3806
  undo: async () => {
3487
3807
  await unlink(file).catch(() => {})
3488
3808
  if (sceneRow) { try { await bridge.removeScene(sceneRow.id, { journal: false }) } catch {} }
@@ -3497,6 +3817,83 @@ if _TARGET:
3497
3817
  })
3498
3818
  }
3499
3819
 
3820
+ /**
3821
+ * Rebuild one undo entry from a persisted journal record. Only document-level
3822
+ * operations are replayable: they are data (a name, a file, bytes). Assembly
3823
+ * and view journal entries are closures over live objects and stay
3824
+ * session-only — after a restart they are not in the stack at all, which is
3825
+ * honest: the panel then says there is nothing to undo instead of undoing
3826
+ * something else.
3827
+ */
3828
+ const restoredEntry = (record) => {
3829
+ const r = record || {}
3830
+ const retitle = async (target, other) => {
3831
+ const row = bridge.history.find((h) => h.docKey === `model:${other}` || h.title === other)
3832
+ if (row) {
3833
+ row.title = target
3834
+ if (row.docKey) row.docKey = `model:${target}`
3835
+ await bridge.persist()
3836
+ }
3837
+ }
3838
+ if (r.op === 'doc-create') {
3839
+ const file = modelFile(r.model, r.dir)
3840
+ return {
3841
+ undo: async () => {
3842
+ await unlink(file).catch(() => {})
3843
+ if (r.sceneId) { try { await bridge.removeScene(r.sceneId, { journal: false }) } catch {} }
3844
+ return { model: r.model }
3845
+ },
3846
+ redo: async () => {
3847
+ // Re-creating needs the emitter to publish again; let the caller do it.
3848
+ throw new Error('重启后不能「重做创建」:请用 cad_studio_doc create 重新发布')
3849
+ },
3850
+ }
3851
+ }
3852
+ if (r.op === 'doc-delete') {
3853
+ const file = modelFile(r.model, r.dir)
3854
+ const bytes = Buffer.from(String(r.b64 || ''), 'base64')
3855
+ return {
3856
+ undo: async () => {
3857
+ await writeFile(file, bytes)
3858
+ try {
3859
+ const doc = await readModel(r.model, r.dir)
3860
+ await rebuild(doc, r.dir, { note: 'undo delete (restored journal)' })
3861
+ } catch {}
3862
+ return { model: r.model }
3863
+ },
3864
+ redo: async () => {
3865
+ await unlink(file).catch(() => {})
3866
+ return { model: r.model }
3867
+ },
3868
+ }
3869
+ }
3870
+ if (r.op === 'doc-rename') {
3871
+ const from = modelFile(r.from, r.dir)
3872
+ const to = modelFile(r.to, r.dir)
3873
+ const move = async (src, dst, name) => {
3874
+ const doc = JSON.parse(await readFile(src, 'utf8'))
3875
+ doc.name = name
3876
+ await writeModel(doc, r.dir)
3877
+ await unlink(dst).catch(() => {})
3878
+ return { model: name }
3879
+ }
3880
+ return {
3881
+ undo: async () => { const out = await move(to, from, r.from); await retitle(r.from, r.to); return out },
3882
+ redo: async () => { const out = await move(from, to, r.to); await retitle(r.to, r.from); return out },
3883
+ }
3884
+ }
3885
+ return null
3886
+ }
3887
+
3888
+ // Restore the replayable journal once per plugin start (a hot reload keeps the
3889
+ // same bridge, so guard against stacking duplicates).
3890
+ if (bridge && !bridge.journalLoaded) {
3891
+ bridge.journalLoaded = true
3892
+ // Keep the promise: an undo issued before the file has been read would
3893
+ // otherwise see an empty stack and report "nothing to undo".
3894
+ bridge.journalReady = bridge.loadJournal(restoredEntry).catch(() => 0)
3895
+ }
3896
+
3500
3897
  const runFeatureAction = async (args, dir) => {
3501
3898
  bridge.noteModelsDir(dir)
3502
3899
  const action = String(args.action ?? 'list')
@@ -3709,6 +4106,18 @@ if _TARGET:
3709
4106
  * the emitter. A feature model runs its own `featuresScript` (which already
3710
4107
  * knows how to export); a script model gets three extra lines appended.
3711
4108
  */
4109
+ /** Python source that rebuilds a saved model's shapes into `_shapes`. */
4110
+ async function modelShapes(name) {
4111
+ const dirs = bridge.modelsCandidates()
4112
+ const dir = dirs.find((d) => existsSync(join(d, `${name}.json`))) || dirs[0]
4113
+ if (!existsSync(join(dir, `${name}.json`))) return ''
4114
+ const doc = await readModel(name, dir)
4115
+ bridge.noteModelsDir(dir)
4116
+ return doc.kind === 'features'
4117
+ ? featuresScript(featureOps(doc), '', { sketches: doc.sketches })
4118
+ : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
4119
+ }
4120
+
3712
4121
  async function exportModelStep(doc, target) {
3713
4122
  if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
3714
4123
  await mkdir(dirname(target), { recursive: true })
@@ -3879,6 +4288,9 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3879
4288
  bridge.journal({
3880
4289
  kind: 'doc',
3881
4290
  label: `delete ${key}`,
4291
+ // The bytes live in journal.json so "undo delete" still works after a
4292
+ // restart; models are small JSON documents.
4293
+ record: { op: 'doc-delete', model: key, dir, b64: bytes.toString('base64') },
3882
4294
  undo: async () => {
3883
4295
  await writeFile(file, bytes)
3884
4296
  const doc = await readModel(key, dir)
@@ -3924,6 +4336,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3924
4336
  bridge.journal({
3925
4337
  kind: 'doc',
3926
4338
  label: `rename ${key} → ${to}`,
4339
+ record: { op: 'doc-rename', dir, from: key, to },
3927
4340
  undo: async () => {
3928
4341
  const back = await readModel(to, dir)
3929
4342
  back.name = key
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {