acad-mcp 0.2.0__py3-none-any.whl
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.
- acad_mcp/__init__.py +7 -0
- acad_mcp/__main__.py +6 -0
- acad_mcp/acad/__init__.py +1 -0
- acad_mcp/acad/capture.py +128 -0
- acad_mcp/acad/commands.py +302 -0
- acad_mcp/acad/errors.py +7 -0
- acad_mcp/acad/fastpath.py +169 -0
- acad_mcp/acad/msgfilter.py +105 -0
- acad_mcp/acad/util.py +498 -0
- acad_mcp/acad/winutil.py +112 -0
- acad_mcp/acad/worker.py +142 -0
- acad_mcp/config.py +69 -0
- acad_mcp/i18n.py +19 -0
- acad_mcp/lisp/mcp_core.lsp +124 -0
- acad_mcp/lisp/routines/_common.lsp +50 -0
- acad_mcp/lisp/routines/count_blocks.lsp +20 -0
- acad_mcp/lisp/routines/export_attributes.lsp +23 -0
- acad_mcp/lisp/routines/fill_title_block.lsp +23 -0
- acad_mcp/lisp/routines/find_replace_text.lsp +34 -0
- acad_mcp/lisp/routines/layer_standard.lsp +38 -0
- acad_mcp/lisp/routines/plot_pdf.lsp +18 -0
- acad_mcp/lisp/routines/purge_audit.lsp +12 -0
- acad_mcp/selftest.py +36 -0
- acad_mcp/server.py +128 -0
- acad_mcp/standards/example.json +22 -0
- acad_mcp/tools/__init__.py +25 -0
- acad_mcp/tools/advanced.py +120 -0
- acad_mcp/tools/batch.py +351 -0
- acad_mcp/tools/common.py +85 -0
- acad_mcp/tools/documents.py +214 -0
- acad_mcp/tools/draw.py +595 -0
- acad_mcp/tools/edit.py +401 -0
- acad_mcp/tools/extract.py +196 -0
- acad_mcp/tools/files.py +337 -0
- acad_mcp/tools/layers.py +226 -0
- acad_mcp/tools/query.py +327 -0
- acad_mcp/tools/recreate.py +298 -0
- acad_mcp/tools/routines.py +164 -0
- acad_mcp/tools/standards.py +310 -0
- acad_mcp/tools/view.py +98 -0
- acad_mcp-0.2.0.dist-info/METADATA +173 -0
- acad_mcp-0.2.0.dist-info/RECORD +44 -0
- acad_mcp-0.2.0.dist-info/WHEEL +4 -0
- acad_mcp-0.2.0.dist-info/entry_points.txt +3 -0
acad_mcp/__init__.py
ADDED
acad_mcp/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""AutoCAD access through COM (single thread), commands, fast LISP reads and screen capture."""
|
acad_mcp/acad/capture.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Image of the AutoCAD drawing area (PrintWindow; works even when the window is covered)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes
|
|
6
|
+
import io
|
|
7
|
+
import math
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import win32gui
|
|
11
|
+
import win32ui
|
|
12
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
13
|
+
|
|
14
|
+
from ..i18n import t as tr
|
|
15
|
+
from . import commands
|
|
16
|
+
from .errors import AcadError
|
|
17
|
+
from .winutil import active_view_hwnd, is_minimized
|
|
18
|
+
|
|
19
|
+
PW_RENDERFULLCONTENT = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def capture_view_png(app: Any, max_width: int = 1600, crop_to_view: bool = True,
|
|
23
|
+
grid: dict[str, Any] | None = None) -> tuple[bytes, dict]:
|
|
24
|
+
"""grid = {"center": VIEWCTR, "view_height": VIEWSIZE} to overlay coordinates."""
|
|
25
|
+
main = int(app.HWND)
|
|
26
|
+
if is_minimized(main):
|
|
27
|
+
if not commands.AUTO_RESTORE:
|
|
28
|
+
raise AcadError(tr(
|
|
29
|
+
"The AutoCAD window is minimized, so no image can be captured. "
|
|
30
|
+
"Ask the user to restore it (it may stay behind other windows).",
|
|
31
|
+
"A janela do AutoCAD está minimizada; não dá para capturar a imagem. "
|
|
32
|
+
"Peça ao usuário para restaurar a janela (pode ficar atrás de outras).",
|
|
33
|
+
))
|
|
34
|
+
commands.restore_behind(main)
|
|
35
|
+
l, t, r, b = win32gui.GetWindowRect(main)
|
|
36
|
+
w, h = r - l, b - t
|
|
37
|
+
hdc = win32gui.GetWindowDC(main)
|
|
38
|
+
mfc = win32ui.CreateDCFromHandle(hdc)
|
|
39
|
+
mem = mfc.CreateCompatibleDC()
|
|
40
|
+
bmp = win32ui.CreateBitmap()
|
|
41
|
+
try:
|
|
42
|
+
bmp.CreateCompatibleBitmap(mfc, w, h)
|
|
43
|
+
mem.SelectObject(bmp)
|
|
44
|
+
if not ctypes.windll.user32.PrintWindow(main, mem.GetSafeHdc(), PW_RENDERFULLCONTENT):
|
|
45
|
+
raise AcadError(tr("Could not capture the AutoCAD window (PrintWindow).",
|
|
46
|
+
"Falha ao capturar a janela do AutoCAD (PrintWindow)."))
|
|
47
|
+
info = bmp.GetInfo()
|
|
48
|
+
img = Image.frombuffer(
|
|
49
|
+
"RGB", (info["bmWidth"], info["bmHeight"]), bmp.GetBitmapBits(True), "raw", "BGRX", 0, 1
|
|
50
|
+
)
|
|
51
|
+
finally:
|
|
52
|
+
win32gui.DeleteObject(bmp.GetHandle())
|
|
53
|
+
mem.DeleteDC()
|
|
54
|
+
mfc.DeleteDC()
|
|
55
|
+
win32gui.ReleaseDC(main, hdc)
|
|
56
|
+
|
|
57
|
+
meta: dict[str, Any] = {"window_size": [w, h]}
|
|
58
|
+
cropped = False
|
|
59
|
+
if crop_to_view:
|
|
60
|
+
view = active_view_hwnd(main)
|
|
61
|
+
if view:
|
|
62
|
+
vl, vt, vr, vb = win32gui.GetWindowRect(view)
|
|
63
|
+
box = (max(vl - l, 0), max(vt - t, 0), min(vr - l, w), min(vb - t, h))
|
|
64
|
+
if box[2] - box[0] > 50 and box[3] - box[1] > 50:
|
|
65
|
+
img = img.crop(box)
|
|
66
|
+
cropped = True
|
|
67
|
+
meta["cropped_to_drawing_area"] = True
|
|
68
|
+
if grid is not None and cropped:
|
|
69
|
+
meta["coordinates"] = draw_grid(img, grid["center"], grid["view_height"])
|
|
70
|
+
scale = 1.0
|
|
71
|
+
if img.width > max_width:
|
|
72
|
+
scale = max_width / img.width
|
|
73
|
+
img = img.resize((max_width, int(img.height * scale)), Image.LANCZOS)
|
|
74
|
+
if "coordinates" in meta:
|
|
75
|
+
c = meta["coordinates"]
|
|
76
|
+
c["units_per_pixel"] = c["units_per_pixel"] / scale
|
|
77
|
+
meta["image_size"] = [img.width, img.height]
|
|
78
|
+
buf = io.BytesIO()
|
|
79
|
+
img.save(buf, format="PNG", optimize=True)
|
|
80
|
+
return buf.getvalue(), meta
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _nice_step(span: float, target_lines: int = 8) -> float:
|
|
84
|
+
raw = span / max(target_lines, 1)
|
|
85
|
+
mag = 10 ** math.floor(math.log10(raw)) if raw > 0 else 1
|
|
86
|
+
for m in (1, 2, 5, 10):
|
|
87
|
+
if raw <= m * mag:
|
|
88
|
+
return m * mag
|
|
89
|
+
return 10 * mag
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def draw_grid(img: Image.Image, center: list[float], view_height: float) -> dict[str, Any]:
|
|
93
|
+
"""Draw a labelled coordinate grid on the image (plan view in WCS assumed).
|
|
94
|
+
|
|
95
|
+
Returns the pixel <-> drawing mapping so the model can read coordinates off the picture.
|
|
96
|
+
"""
|
|
97
|
+
W, H = img.size
|
|
98
|
+
upp = view_height / H # drawing units per pixel
|
|
99
|
+
x0 = center[0] - W / 2 * upp
|
|
100
|
+
y_top = center[1] + H / 2 * upp
|
|
101
|
+
step = _nice_step(max(W, H) * upp)
|
|
102
|
+
d = ImageDraw.Draw(img, "RGBA")
|
|
103
|
+
font = ImageFont.load_default()
|
|
104
|
+
color, label = (0, 200, 255, 90), (0, 220, 255, 255)
|
|
105
|
+
|
|
106
|
+
def fmt(v: float) -> str:
|
|
107
|
+
return f"{v:.0f}" if step >= 1 else f"{v:.3g}"
|
|
108
|
+
|
|
109
|
+
gx = math.ceil(x0 / step) * step
|
|
110
|
+
while gx <= x0 + W * upp:
|
|
111
|
+
px = (gx - x0) / upp
|
|
112
|
+
d.line([(px, 0), (px, H)], fill=color, width=1)
|
|
113
|
+
d.text((px + 2, H - 12), fmt(gx), fill=label, font=font)
|
|
114
|
+
gx += step
|
|
115
|
+
y_bottom = y_top - H * upp
|
|
116
|
+
gy = math.ceil(y_bottom / step) * step
|
|
117
|
+
while gy <= y_top:
|
|
118
|
+
py = (y_top - gy) / upp
|
|
119
|
+
d.line([(0, py), (W, py)], fill=color, width=1)
|
|
120
|
+
d.text((2, py + 2), fmt(gy), fill=label, font=font)
|
|
121
|
+
gy += step
|
|
122
|
+
return {
|
|
123
|
+
"grid_step": step,
|
|
124
|
+
"units_per_pixel": upp,
|
|
125
|
+
"top_left": [x0, y_top],
|
|
126
|
+
"how_to_read": tr("x = top_left.x + px * units_per_pixel; y = top_left.y - py * units_per_pixel",
|
|
127
|
+
"x = top_left.x + px * units_per_pixel; y = top_left.y - py * units_per_pixel"),
|
|
128
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Command line and AutoLISP via SendCommand, with a watchdog against hangs.
|
|
2
|
+
|
|
3
|
+
SendCommand blocks until the command finishes. If the command keeps waiting for input
|
|
4
|
+
(e.g. '_.LINE 0,0' with no more points) or opens a dialog, the call would hang forever.
|
|
5
|
+
The watchdog (Timer) closes dialogs and sends ESC to the drawing area after `timeout`
|
|
6
|
+
seconds, which releases the call.
|
|
7
|
+
|
|
8
|
+
Measured on AutoCAD 2027:
|
|
9
|
+
- With the window minimized, SendCommand is queued and AutoCAD freezes when restored.
|
|
10
|
+
Restoring BEFORE sending works, but AutoCAD grabs keyboard focus, so auto-restore is
|
|
11
|
+
opt-in (ACAD_MCP_AUTO_RESTORE=1).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import tempfile
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import uuid
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import pywintypes
|
|
25
|
+
import win32con
|
|
26
|
+
import win32gui
|
|
27
|
+
|
|
28
|
+
from ..i18n import t
|
|
29
|
+
from .errors import AcadError
|
|
30
|
+
from .winutil import cancel_everything, is_minimized
|
|
31
|
+
|
|
32
|
+
AUTO_RESTORE = False # set by server.build() from Config
|
|
33
|
+
|
|
34
|
+
MINIMIZED_MSG = t(
|
|
35
|
+
"The AutoCAD window is minimized. While minimized, commands get stuck in a queue and AutoCAD "
|
|
36
|
+
"freezes when restored. Ask the user to restore the AutoCAD window (it may stay behind other "
|
|
37
|
+
"windows, just not minimized) and try again. (Or start the server with ACAD_MCP_AUTO_RESTORE=1.)",
|
|
38
|
+
"A janela do AutoCAD está minimizada. Com ela minimizada, comandos ficam presos na fila "
|
|
39
|
+
"e o AutoCAD trava ao ser restaurado. Peça ao usuário para restaurar a janela do AutoCAD "
|
|
40
|
+
"(pode ficar atrás de outras janelas, só não minimizada) e tente de novo. "
|
|
41
|
+
"(Ou inicie o servidor com ACAD_MCP_AUTO_RESTORE=1.)",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def restore_behind(hwnd: int) -> None:
|
|
46
|
+
"""Restore without activating and push behind all other windows."""
|
|
47
|
+
win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)
|
|
48
|
+
win32gui.SetWindowPos(hwnd, win32con.HWND_BOTTOM, 0, 0, 0, 0,
|
|
49
|
+
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE)
|
|
50
|
+
time.sleep(1.0)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def require_visible(app: Any) -> int:
|
|
54
|
+
hwnd = int(app.HWND)
|
|
55
|
+
if is_minimized(hwnd):
|
|
56
|
+
if not AUTO_RESTORE:
|
|
57
|
+
raise AcadError(MINIMIZED_MSG)
|
|
58
|
+
restore_behind(hwnd)
|
|
59
|
+
return hwnd
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def wait_idle(doc: Any, timeout: float = 10.0) -> bool:
|
|
63
|
+
t0 = time.monotonic()
|
|
64
|
+
while time.monotonic() - t0 < timeout:
|
|
65
|
+
try:
|
|
66
|
+
if doc.GetVariable("CMDACTIVE") == 0:
|
|
67
|
+
return True
|
|
68
|
+
except pywintypes.com_error:
|
|
69
|
+
pass
|
|
70
|
+
time.sleep(0.1)
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def send(app: Any, doc: Any, text: str, timeout: float) -> dict[str, Any]:
|
|
75
|
+
"""Send text to the command line under a watchdog. Returns execution info."""
|
|
76
|
+
hwnd = require_visible(app)
|
|
77
|
+
if doc.GetVariable("CMDACTIVE") != 0:
|
|
78
|
+
raise AcadError(t(
|
|
79
|
+
"A command is already running in AutoCAD ({c}). Use cancel_command or ask the user to finish it.",
|
|
80
|
+
"Já existe um comando em andamento no AutoCAD ({c}). Use cancel_command ou peça ao usuário para terminar.",
|
|
81
|
+
c=doc.GetVariable("CMDNAMES"),
|
|
82
|
+
))
|
|
83
|
+
started = threading.Event()
|
|
84
|
+
actions: list[str] = []
|
|
85
|
+
|
|
86
|
+
def watchdog() -> None:
|
|
87
|
+
started.set()
|
|
88
|
+
actions.extend(cancel_everything(hwnd))
|
|
89
|
+
|
|
90
|
+
timer = threading.Timer(timeout, watchdog)
|
|
91
|
+
timer.daemon = True
|
|
92
|
+
t0 = time.monotonic()
|
|
93
|
+
timer.start()
|
|
94
|
+
try:
|
|
95
|
+
doc.SendCommand(text)
|
|
96
|
+
finally:
|
|
97
|
+
timer.cancel()
|
|
98
|
+
if started.is_set():
|
|
99
|
+
timer.join(timeout=3) # let the watchdog finish before reading results
|
|
100
|
+
wait_idle(doc, 5)
|
|
101
|
+
info: dict[str, Any] = {"seconds": round(time.monotonic() - t0, 2)}
|
|
102
|
+
if started.is_set():
|
|
103
|
+
info["cancelled_after_timeout"] = True
|
|
104
|
+
info["cancel_actions"] = actions
|
|
105
|
+
info["note"] = t(
|
|
106
|
+
"The command kept waiting for input and was cancelled (ESC). Send every answer the command asks for.",
|
|
107
|
+
"O comando ficou esperando entrada e foi cancelado (ESC). Envie todas as respostas do comando.",
|
|
108
|
+
)
|
|
109
|
+
return info
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ------------------------------------------------------------------ commands
|
|
113
|
+
|
|
114
|
+
_TOKEN = re.compile(r"[\s\n]+")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def normalize_command(cmd: str) -> str:
|
|
118
|
+
cmd = cmd.replace("\r\n", "\n")
|
|
119
|
+
if not cmd.endswith((" ", "\n")):
|
|
120
|
+
cmd += "\n"
|
|
121
|
+
return cmd
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def check_command(cmd: str, blocked: set[str]) -> None:
|
|
125
|
+
for tok in _TOKEN.split(cmd):
|
|
126
|
+
name = tok.strip().lstrip("_.-+'").upper()
|
|
127
|
+
if name in blocked:
|
|
128
|
+
raise AcadError(t(
|
|
129
|
+
"The command '{n}' is blocked for safety by this MCP server "
|
|
130
|
+
"(it starts programs, loads code or closes AutoCAD).",
|
|
131
|
+
"O comando '{n}' está bloqueado por segurança neste servidor MCP "
|
|
132
|
+
"(abre programas, carrega código ou fecha o AutoCAD).",
|
|
133
|
+
n=name,
|
|
134
|
+
))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def check_lisp(code: str, blocked: set[str]) -> None:
|
|
138
|
+
low = code.lower()
|
|
139
|
+
for b in blocked:
|
|
140
|
+
if b in low:
|
|
141
|
+
raise AcadError(t("'{b}' is blocked for safety in run_lisp.",
|
|
142
|
+
"Uso de '{b}' bloqueado por segurança em run_lisp.", b=b))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def run_command(app: Any, doc: Any, command: str, timeout: float) -> dict[str, Any]:
|
|
146
|
+
cmd = normalize_command(command)
|
|
147
|
+
ms = doc.ModelSpace
|
|
148
|
+
before = ms.Count
|
|
149
|
+
last_before = ms.Item(before - 1).Handle if before else None
|
|
150
|
+
old = {}
|
|
151
|
+
for var in ("FILEDIA", "CMDDIA"):
|
|
152
|
+
try:
|
|
153
|
+
old[var] = doc.GetVariable(var)
|
|
154
|
+
doc.SetVariable(var, 0)
|
|
155
|
+
except pywintypes.com_error:
|
|
156
|
+
pass
|
|
157
|
+
try:
|
|
158
|
+
info = send(app, doc, cmd, timeout)
|
|
159
|
+
try:
|
|
160
|
+
info["last_prompt"] = doc.GetVariable("LASTPROMPT")
|
|
161
|
+
except pywintypes.com_error:
|
|
162
|
+
pass
|
|
163
|
+
finally:
|
|
164
|
+
for var, val in old.items():
|
|
165
|
+
try:
|
|
166
|
+
doc.SetVariable(var, val)
|
|
167
|
+
except pywintypes.com_error:
|
|
168
|
+
pass
|
|
169
|
+
info["modelspace_entities_before"] = before
|
|
170
|
+
info["modelspace_entities_after"] = ms.Count
|
|
171
|
+
if ms.Count:
|
|
172
|
+
try:
|
|
173
|
+
last = ms.Item(ms.Count - 1).Handle
|
|
174
|
+
if last != last_before:
|
|
175
|
+
info["last_entity"] = last
|
|
176
|
+
except pywintypes.com_error:
|
|
177
|
+
pass
|
|
178
|
+
return info
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ------------------------------------------------------------------ LISP
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def lisp_str(s: str) -> str:
|
|
185
|
+
"""Python string -> AutoLISP string literal."""
|
|
186
|
+
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def lisp_path(p: str) -> str:
|
|
190
|
+
return lisp_str(str(p).replace("\\", "/"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
INLINE_LIMIT = 600 # measured: the command line rejects expressions between 1,000 and 2,000 chars
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def strip_lisp_comments(code: str) -> str:
|
|
197
|
+
"""Remove ; and ;|...|; comments outside strings (AutoLISP `read` does not skip comments)."""
|
|
198
|
+
out: list[str] = []
|
|
199
|
+
i, n, in_str = 0, len(code), False
|
|
200
|
+
while i < n:
|
|
201
|
+
c = code[i]
|
|
202
|
+
if in_str:
|
|
203
|
+
out.append(c)
|
|
204
|
+
if c == "\\" and i + 1 < n:
|
|
205
|
+
out.append(code[i + 1])
|
|
206
|
+
i += 2
|
|
207
|
+
continue
|
|
208
|
+
if c == '"':
|
|
209
|
+
in_str = False
|
|
210
|
+
elif c == '"':
|
|
211
|
+
in_str = True
|
|
212
|
+
out.append(c)
|
|
213
|
+
elif code.startswith(";|", i):
|
|
214
|
+
end = code.find("|;", i + 2)
|
|
215
|
+
i = n if end < 0 else end + 2
|
|
216
|
+
continue
|
|
217
|
+
elif c == ";":
|
|
218
|
+
end = code.find("\n", i)
|
|
219
|
+
i = n if end < 0 else end
|
|
220
|
+
continue
|
|
221
|
+
else:
|
|
222
|
+
out.append(c)
|
|
223
|
+
i += 1
|
|
224
|
+
return "".join(out)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def write_lisp_file(code: str, path: str | None = None) -> str:
|
|
228
|
+
"""Write code as ONE (progn ...) form, comments stripped, to be read back by eval_file_expr."""
|
|
229
|
+
path = path or os.path.join(tempfile.gettempdir(), f"acad_mcp_src_{uuid.uuid4().hex}.lsp")
|
|
230
|
+
body = strip_lisp_comments(code).replace("\r\n", "\n")
|
|
231
|
+
with open(path, "w", encoding="mbcs", errors="replace") as fh:
|
|
232
|
+
fh.write("(progn " + body + "\n)")
|
|
233
|
+
return path
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def eval_file_expr(path: str) -> str:
|
|
237
|
+
"""Short expression that reads a file as TEXT and evaluates it. Reading text is not 'loading code',
|
|
238
|
+
so AutoCAD's SECURELOAD dialog is not triggered (unlike (load ...))."""
|
|
239
|
+
return (
|
|
240
|
+
f"(progn (setq #mcp-sf (open {lisp_path(path)} \"r\") #mcp-s \"\")"
|
|
241
|
+
"(while (setq #mcp-l (read-line #mcp-sf)) (setq #mcp-s (strcat #mcp-s #mcp-l \"\\n\")))"
|
|
242
|
+
"(close #mcp-sf) (setq #mcp-sf nil) (eval (read #mcp-s)))"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _code_expr(code: str) -> tuple[str, str | None]:
|
|
247
|
+
"""Short code goes inline; long code goes to a temp file read and evaluated by a small bootstrap."""
|
|
248
|
+
if len(code) <= INLINE_LIMIT:
|
|
249
|
+
return f"(progn {code})", None
|
|
250
|
+
src = write_lisp_file(code)
|
|
251
|
+
return eval_file_expr(src), src
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def run_lisp(app: Any, doc: Any, code: str, timeout: float) -> dict[str, Any]:
|
|
255
|
+
res_path = os.path.join(tempfile.gettempdir(), f"acad_mcp_{uuid.uuid4().hex}.txt")
|
|
256
|
+
expr, src_file = _code_expr(code)
|
|
257
|
+
try:
|
|
258
|
+
return _run_lisp(app, doc, expr, res_path, timeout)
|
|
259
|
+
finally:
|
|
260
|
+
if src_file:
|
|
261
|
+
try:
|
|
262
|
+
os.remove(src_file)
|
|
263
|
+
except OSError:
|
|
264
|
+
pass
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _run_lisp(app: Any, doc: Any, expr: str, res_path: str, timeout: float) -> dict[str, Any]:
|
|
268
|
+
wrapped = (
|
|
269
|
+
"(progn (vl-load-com)"
|
|
270
|
+
f"(setq #mcp-r (vl-catch-all-apply (function (lambda () {expr}))))"
|
|
271
|
+
f"(setq #mcp-f (open {lisp_path(res_path)} \"w\"))"
|
|
272
|
+
"(write-line (if (vl-catch-all-error-p #mcp-r)"
|
|
273
|
+
' (strcat "ERR:" (vl-catch-all-error-message #mcp-r))'
|
|
274
|
+
" (vl-prin1-to-string #mcp-r)) #mcp-f)"
|
|
275
|
+
"(close #mcp-f) (setq #mcp-r nil #mcp-f nil) (princ))\n"
|
|
276
|
+
)
|
|
277
|
+
info = send(app, doc, wrapped, timeout)
|
|
278
|
+
t0 = time.monotonic()
|
|
279
|
+
while not os.path.exists(res_path) and time.monotonic() - t0 < 3:
|
|
280
|
+
time.sleep(0.05)
|
|
281
|
+
if not os.path.exists(res_path):
|
|
282
|
+
info["result"] = None
|
|
283
|
+
info["error"] = t(
|
|
284
|
+
"The code returned nothing (syntax error, unbalanced parentheses or cancelled command). Check the code.",
|
|
285
|
+
"O código não devolveu resultado (erro de sintaxe, parênteses desbalanceados ou comando cancelado). "
|
|
286
|
+
"Confira o código.",
|
|
287
|
+
)
|
|
288
|
+
return info
|
|
289
|
+
try:
|
|
290
|
+
with open(res_path, encoding="mbcs", errors="replace") as f:
|
|
291
|
+
out = f.read().rstrip("\r\n")
|
|
292
|
+
finally:
|
|
293
|
+
try:
|
|
294
|
+
os.remove(res_path)
|
|
295
|
+
except OSError:
|
|
296
|
+
pass
|
|
297
|
+
if out.startswith("ERR:"):
|
|
298
|
+
info["error"] = out[4:]
|
|
299
|
+
info["result"] = None
|
|
300
|
+
else:
|
|
301
|
+
info["result"] = out
|
|
302
|
+
return info
|
acad_mcp/acad/errors.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Fast in-process reading through the mcp_core.lsp library.
|
|
2
|
+
|
|
3
|
+
Measured on AutoCAD 2027 with 50,000 entities: COM out-of-process needs ~71 s just to select
|
|
4
|
+
and ~26 ms per entity to read details (~22 min); in-process LISP reads everything in about a
|
|
5
|
+
minute or less. The library is sent as inline code (not (load ...)), because loading a .lsp
|
|
6
|
+
from an untrusted folder raises AutoCAD's SECURELOAD dialog.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import tempfile
|
|
15
|
+
import uuid
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Sequence
|
|
18
|
+
|
|
19
|
+
from ..i18n import t
|
|
20
|
+
from . import commands as C
|
|
21
|
+
from .errors import AcadError
|
|
22
|
+
from .util import dxf_types, rnd
|
|
23
|
+
|
|
24
|
+
CORE_PATH = Path(__file__).resolve().parent.parent / "lisp" / "mcp_core.lsp"
|
|
25
|
+
CORE_VERSION = "0.4"
|
|
26
|
+
|
|
27
|
+
TYPE_NAMES = {
|
|
28
|
+
"LINE": "Line", "LWPOLYLINE": "Polyline", "POLYLINE": "2dPolyline", "CIRCLE": "Circle", "ARC": "Arc",
|
|
29
|
+
"TEXT": "Text", "MTEXT": "MText", "INSERT": "BlockReference", "DIMENSION": "Dimension", "HATCH": "Hatch",
|
|
30
|
+
"POINT": "Point", "ELLIPSE": "Ellipse", "SPLINE": "Spline", "MULTILEADER": "MLeader", "ACAD_TABLE": "Table",
|
|
31
|
+
"LEADER": "Leader", "REGION": "Region", "SOLID": "Solid", "IMAGE": "RasterImage", "ATTDEF": "AttributeDefinition",
|
|
32
|
+
"VIEWPORT": "Viewport", "3DSOLID": "3dSolid", "XLINE": "Xline", "RAY": "Ray", "WIPEOUT": "Wipeout",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _core_code() -> str:
|
|
37
|
+
"""Library source (comments removed by run_lisp; long code goes through a temp file)."""
|
|
38
|
+
return CORE_PATH.read_text(encoding="utf-8")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def ensure_loaded(app: Any, doc: Any, timeout: float) -> None:
|
|
42
|
+
r = C.run_lisp(app, doc, f'(if (and (boundp (quote mcp:version)) (= mcp:version "{CORE_VERSION}")) "ok" "no")', timeout)
|
|
43
|
+
if r.get("result") == '"ok"':
|
|
44
|
+
return
|
|
45
|
+
r = C.run_lisp(app, doc, _core_code() + ' "loaded"', timeout)
|
|
46
|
+
if r.get("result") != '"loaded"':
|
|
47
|
+
raise AcadError(t("Could not load the fast-read library in AutoCAD: {e}",
|
|
48
|
+
"Não consegui carregar a biblioteca de leitura rápida no AutoCAD: {e}",
|
|
49
|
+
e=r.get("error")))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def lisp_filter(types: Sequence[str] | None = None, layers: Sequence[str] | None = None, space: str = "model",
|
|
53
|
+
text_contains: str | None = None, color: int | None = None) -> str:
|
|
54
|
+
parts: list[str] = []
|
|
55
|
+
dt = dxf_types(types)
|
|
56
|
+
if dt:
|
|
57
|
+
parts.append(f"(cons 0 {C.lisp_str(dt)})")
|
|
58
|
+
if layers:
|
|
59
|
+
parts.append(f"(cons 8 {C.lisp_str(','.join(layers))})")
|
|
60
|
+
s = (space or "model").lower()
|
|
61
|
+
if s.startswith("model"):
|
|
62
|
+
parts.append('(cons 410 "Model")')
|
|
63
|
+
elif s.startswith("paper") or s == "layout":
|
|
64
|
+
parts += ['(cons -4 "<NOT")', '(cons 410 "Model")', '(cons -4 "NOT>")']
|
|
65
|
+
if text_contains:
|
|
66
|
+
parts.append(f"(cons 1 {C.lisp_str('*' + text_contains + '*')})")
|
|
67
|
+
if color is not None:
|
|
68
|
+
parts.append(f"(cons 62 {int(color)})")
|
|
69
|
+
return f"(list {' '.join(parts)})" if parts else "nil"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _color(rec: dict) -> Any:
|
|
73
|
+
if "rgb" in rec:
|
|
74
|
+
v = int(rec["rgb"])
|
|
75
|
+
return f"{(v >> 16) & 255},{(v >> 8) & 255},{v & 255}"
|
|
76
|
+
c = rec.get("c")
|
|
77
|
+
if c is None or c == 256:
|
|
78
|
+
return "ByLayer"
|
|
79
|
+
if c == 0:
|
|
80
|
+
return "ByBlock"
|
|
81
|
+
return c
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def to_entity(rec: dict) -> dict[str, Any]:
|
|
85
|
+
"""Compact LISP record -> same keys as util.entity_info."""
|
|
86
|
+
typ = TYPE_NAMES.get(rec["t"], rec["t"].title())
|
|
87
|
+
d: dict[str, Any] = {"handle": rec["h"], "type": typ, "layer": rec["l"], "color": _color(rec)}
|
|
88
|
+
if "lay" in rec:
|
|
89
|
+
d["layout"] = rec["lay"]
|
|
90
|
+
if "n" in rec:
|
|
91
|
+
d["name"] = rec.get("en") or rec["n"]
|
|
92
|
+
if rec.get("en"):
|
|
93
|
+
d["anonymous_name"] = rec["n"]
|
|
94
|
+
m = {"a": "start", "b": "end", "ctr": "center", "v": "vertices", "x": "text", "att": "attributes",
|
|
95
|
+
"m": "measurement", "pat": "pattern", "nv": "vertex_count", "cl": "closed"}
|
|
96
|
+
for k, name in m.items():
|
|
97
|
+
if k in rec:
|
|
98
|
+
d[name] = rec[k]
|
|
99
|
+
if "r" in rec:
|
|
100
|
+
d["radius"] = rnd(rec["r"])
|
|
101
|
+
if "p" in rec:
|
|
102
|
+
d["position" if typ == "Point" else "insertion"] = rec["p"]
|
|
103
|
+
if "ht" in rec:
|
|
104
|
+
d["height"] = rnd(rec["ht"])
|
|
105
|
+
if "rot" in rec:
|
|
106
|
+
d["rotation_deg"] = rnd(math.degrees(rec["rot"]) % 360)
|
|
107
|
+
if "sc" in rec:
|
|
108
|
+
d["scale"] = rnd(rec["sc"])
|
|
109
|
+
if "a0" in rec:
|
|
110
|
+
d["start_angle_deg"] = rnd(math.degrees(rec["a0"]) % 360)
|
|
111
|
+
d["end_angle_deg"] = rnd(math.degrees(rec["a1"]) % 360)
|
|
112
|
+
if "len" in rec:
|
|
113
|
+
d["length"] = rnd(rec["len"])
|
|
114
|
+
if "ar" in rec:
|
|
115
|
+
d["area"] = rnd(rec["ar"])
|
|
116
|
+
return d
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def approx_bbox(e: dict) -> list[list[float]] | None:
|
|
120
|
+
"""Box from the fields we have (text and blocks: insertion point only)."""
|
|
121
|
+
pts: list[list[float]] = []
|
|
122
|
+
if "start" in e:
|
|
123
|
+
pts += [e["start"], e["end"]]
|
|
124
|
+
if "center" in e and "radius" in e:
|
|
125
|
+
c, r = e["center"], e["radius"]
|
|
126
|
+
pts += [[c[0] - r, c[1] - r], [c[0] + r, c[1] + r]]
|
|
127
|
+
if "vertices" in e:
|
|
128
|
+
pts += e["vertices"]
|
|
129
|
+
for k in ("insertion", "position"):
|
|
130
|
+
if k in e:
|
|
131
|
+
pts.append(e[k])
|
|
132
|
+
if not pts:
|
|
133
|
+
return None
|
|
134
|
+
return [[min(p[0] for p in pts), min(p[1] for p in pts)], [max(p[0] for p in pts), max(p[1] for p in pts)]]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def query(app: Any, doc: Any, flt: str, mode: str = "full", skip: int = 0, limit: int = 0,
|
|
138
|
+
timeout: float = 600.0) -> tuple[int, list[dict[str, Any]]]:
|
|
139
|
+
"""Run mcp:query in AutoCAD. Returns (total matched, records converted)."""
|
|
140
|
+
ensure_loaded(app, doc, timeout)
|
|
141
|
+
out = os.path.join(tempfile.gettempdir(), f"acad_mcp_q_{uuid.uuid4().hex}.jsonl")
|
|
142
|
+
try:
|
|
143
|
+
r = C.run_lisp(app, doc, f"(mcp:query {flt} {C.lisp_path(out)} \"{mode}\" {int(skip)} {int(limit)})", timeout)
|
|
144
|
+
if r.get("error") or r.get("cancelled_after_timeout"):
|
|
145
|
+
raise AcadError(t("Fast read failed: {e}", "A leitura rápida falhou: {e}",
|
|
146
|
+
e=r.get("error") or r.get("note")))
|
|
147
|
+
total = int(r["result"])
|
|
148
|
+
recs: list[dict[str, Any]] = []
|
|
149
|
+
if os.path.exists(out):
|
|
150
|
+
with open(out, "rb") as fh:
|
|
151
|
+
for raw in fh:
|
|
152
|
+
line = raw.decode("utf-8", errors="strict") if _is_utf8(raw) else raw.decode("mbcs", "replace")
|
|
153
|
+
line = line.strip()
|
|
154
|
+
if line:
|
|
155
|
+
recs.append(to_entity(json.loads(line)))
|
|
156
|
+
return total, recs
|
|
157
|
+
finally:
|
|
158
|
+
try:
|
|
159
|
+
os.remove(out)
|
|
160
|
+
except OSError:
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _is_utf8(b: bytes) -> bool:
|
|
165
|
+
try:
|
|
166
|
+
b.decode("utf-8")
|
|
167
|
+
return True
|
|
168
|
+
except UnicodeDecodeError:
|
|
169
|
+
return False
|