Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
598 lines (520 loc) · 20.3 KB
/
Copy pathcli.py
File metadata and controls
598 lines (520 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
"""InkMoon CLI 控制客户端
通过 Socket IPC 实时控制 InkMoon 软件。
用法:
交互式 REPL:
python cli.py --port 6100
> open d:/a.png
> ls
> opacity 0 50
> undo
> help
> exit
单次命令:
python cli.py --port 6100 ls
python cli.py --port 6100 open d:/a.png
终端启动并进入 REPL(自动拉起 GUI):
python cli.py --launch
python cli.py --launch d:/a.png # 启动 GUI 并打开图片后进入 REPL
参数语法:
- 数组字面量:多参数命令用 [元素1, 元素2, ...],如 select.rect [10, 10, 200, 150]
- 单值命令:裸值便捷写法,如 open d:/a.png、app.theme dark
- 别名:如 open==file.image.load、ls==layer.list、undo==canvas.undo
- 类型自动收窄:int/float/bool/color/opacity,如颜色 white 或 #fff,透明度 50 视为 0.5
"""
from __future__ import annotations
import argparse
import json
import os
import select
import socket
import subprocess
import sys
import struct
import threading
import time
from typing import Any, Optional
_HEADER = struct.Struct(">I")
_HEADER_SIZE = _HEADER.size
MAX_FRAME_SIZE = 64 * 1024 * 1024
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 6100
def find_gui_exe(app_path: Optional[str] = None) -> list[str]:
"""定位 GUI 可执行文件路径。
Returns:
list: 要启动的命令列表(用于 subprocess.Popen)
"""
if app_path is not None:
# 用户指定
if app_path.endswith(".py"):
return [sys.executable, app_path]
return [app_path]
# 打包环境:sys.executable 是 InkMoon.exe,同目录就是可执行文件
exe_dir = os.path.dirname(sys.executable)
gui_exe = os.path.join(exe_dir, "InkMoon.exe")
if os.path.exists(gui_exe):
return [gui_exe]
# 开发环境:当前目录下 main.py
main_py = os.path.join(os.getcwd(), "main.py")
if os.path.exists(main_py):
return [sys.executable, main_py]
raise RuntimeError("无法找到 InkMoon GUI 可执行文件,请使用 --app 指定路径")
def can_connect(host: str, port: int) -> bool:
"""测试是否能连接到服务器"""
try:
sock = socket.create_connection((host, port), timeout=1.0)
sock.close()
return True
except (socket.error, ConnectionRefusedError):
return False
def ensure_server_ready(cmd: list[str], host: str, port: int, timeout: float) -> None:
"""确保控制服务器就绪;若无法连接,启动 GUI 并轮询直到就绪。
Raises:
TimeoutError: 超时仍未就绪
"""
# 先试直接连接
if can_connect(host, port):
return
# 连接失败,启动 GUI
print(f"正在启动 InkMoon...")
# 启动后台进程,不继承 stdout/stderr,不等待
if sys.platform == "win32":
# Windows:创建独立进程,不显示新窗口
creationflags = subprocess.CREATE_NO_WINDOW
subprocess.Popen(cmd, creationflags=creationflags, close_fds=True)
else:
subprocess.Popen(cmd, close_fds=True)
# 轮询直到就绪或超时
deadline = time.time() + timeout
while not can_connect(host, port):
if time.time() >= deadline:
raise TimeoutError(f"等待控制服务器就绪超时({timeout}秒),请检查端口或增加 --wait 参数")
time.sleep(0.5)
print(f"InkMoon 已就绪")
def encode_frame(obj: Any) -> bytes:
payload = json.dumps(obj, ensure_ascii=False).encode("utf-8")
return _HEADER.pack(len(payload)) + payload
def _read_frame(sock: socket.socket) -> Optional[dict]:
"""读取一帧;连接关闭返回 None"""
header = _recv_exact(sock, _HEADER_SIZE)
if header is None:
return None
(length,) = _HEADER.unpack(header)
if length > MAX_FRAME_SIZE:
raise ValueError(f"frame too large: {length}")
payload = _recv_exact(sock, length)
if payload is None:
return None
return json.loads(payload.decode("utf-8"))
def _recv_exact(sock: socket.socket, n: int) -> Optional[bytes]:
buf = bytearray()
sock.settimeout(5.0)
while len(buf) < n:
try:
chunk = sock.recv(n - len(buf))
except socket.timeout:
raise TimeoutError("timed out waiting for response")
if not chunk:
return None
buf.extend(chunk)
return bytes(buf)
class Client:
def __init__(self, host: str, port: int, token: str = ""):
self._host = host
self._port = port
self._token = token
self._sock: Optional[socket.socket] = None
self._next_id = 1
def connect(self) -> None:
self._sock = socket.create_connection((self._host, self._port), timeout=10.0)
if self._token:
self.request("auth", {"token": self._token})
def close(self) -> None:
if self._sock is not None:
try:
self._sock.close()
except OSError:
pass
self._sock = None
def request(self, cmd: str, params: Optional[dict] = None) -> dict:
if self._sock is None:
raise RuntimeError("not connected")
req_id = self._next_id
self._next_id += 1
self._sock.sendall(encode_frame({"id": req_id, "cmd": cmd, "params": params or {}}))
while True:
msg = _read_frame(self._sock)
if msg is None:
raise ConnectionError("connection closed by server")
if msg.get("id") == req_id:
return msg
# 忽略事件推送(id=0)
def wait_event(self, event: str, predicate=None, timeout: float = 30.0) -> Optional[dict]:
"""等待服务器推送的指定事件;返回匹配事件的 data,超时返回 None。
predicate: 可选回调,传入 data,返回 True 才匹配。
"""
if self._sock is None:
raise RuntimeError("not connected")
deadline = time.time() + timeout
while True:
try:
msg = _read_frame(self._sock)
except TimeoutError:
if time.time() >= deadline:
return None
continue
except ConnectionError:
raise
if msg is None:
raise ConnectionError("connection closed by server")
if msg.get("id") != 0:
continue # 忽略响应帧
if msg.get("event") == event:
if predicate is None or predicate(msg.get("data")):
return msg.get("data")
def _format_result(msg: dict) -> str:
if msg.get("ok"):
return json.dumps(msg.get("result"), ensure_ascii=False, indent=2)
return f"ERROR: {msg.get('error')}"
def _parse_args(tokens: list) -> dict:
"""把 token 列表解析为 params 字典(数组字面量语法)。
- 数组字面量:`[元素1, 元素2, ...]`,元素用逗号分隔,允许跨空格 token 重组;
字符串元素可用引号包裹(允许含空格/逗号)。
- 单值命令保留裸值便捷写法:`open d:/a.png` → ["d:/a.png"]。
- 统一返回 `{"$args": [元素字符串...]}`。
Raises:
ValueError: 数组字面量未闭合(缺少 `]`)。
"""
if not tokens:
return {}
if tokens[0].startswith("["):
# 收集数组 token 直到以 `]` 结尾
array_tokens = []
in_array = False
for tok in tokens:
if tok.startswith("["):
in_array = True
rest = tok.lstrip("[")
if "]" in rest: # 同一 token 内既开又闭,如 [red]
array_tokens.append(rest.rstrip("]"))
in_array = False
break
array_tokens.append(rest)
elif in_array:
if "]" in tok:
array_tokens.append(tok.rstrip("]"))
in_array = False
break
array_tokens.append(tok)
else:
break
if in_array:
raise ValueError("参数数组未闭合,请使用 [ ] 包裹参数")
# 合并数组 token,按逗号切分(忽略引号内逗号)
array_str = " ".join(array_tokens)
elements = []
current = []
in_quote = False
for c in array_str:
if c == "," and not in_quote:
if current:
elements.append("".join(current).strip())
current = []
elif c in ('"', "'"):
in_quote = not in_quote
else:
current.append(c)
if current:
elements.append("".join(current).strip())
return {"$args": [e.strip('"\'') for e in elements if e]}
# 单值命令裸写法
return {"$args": list(tokens)}
def _build_async_map(schema: Optional[dict]) -> dict:
"""构建 命令名/别名 -> 异步 task 名 的映射"""
async_map: dict = {}
if schema:
for meta in schema.values():
task = meta.get("async_task")
if not task:
continue
async_map[meta["name"]] = task
for alias in meta.get("aliases") or []:
async_map[alias] = task
return async_map
def _wait_task(client: Client, task: str, timeout: float = 60.0) -> int:
"""等待指定异步任务完成,返回进程退出码(0 成功 / 1 失败 / 2 超时)"""
data = client.wait_event(
"task.done", predicate=lambda d: d.get("task") == task, timeout=timeout
)
if data is None:
print(f"✘ 等待任务 {task} 完成超时")
return 2
ok = data.get("ok")
msg = data.get("message")
if ok:
print(f"✔ 任务完成: {task} {msg}")
return 0
print(f"✘ 任务失败: {task} {msg}")
return 1
def _run_single(client: Client, cmd: str, params: Optional[dict]) -> int:
schema = _fetch_schema(client)
async_map = _build_async_map(schema)
# 会关闭 GUI 进程/连接的命令:进程退出时连接被关闭属正常,可能收不到响应,无需等待
if cmd in ("app.shutdown", "shutdown", "app.quit", "quit", "exit"):
try:
client.request(cmd, params)
except Exception:
pass
print("软件已关闭")
return 0
try:
msg = client.request(cmd, params)
except ConnectionError:
print("连接已被服务器关闭", file=sys.stderr)
return 1
print(_format_result(msg))
if not msg.get("ok"):
return 1
task = async_map.get(cmd)
if task:
try:
return _wait_task(client, task)
except ConnectionError:
print("连接已被服务器关闭", file=sys.stderr)
return 1
return 0
def _fetch_schema(client: Client) -> Optional[dict]:
"""拉取完整命令 schema;失败返回 None"""
try:
msg = client.request("commands.schema")
if msg.get("ok"):
return msg.get("result")
except Exception:
pass
return None
# 常用主要命令(help 优先展示,按此顺序)
_COMMON_COMMANDS = (
"open", # 打开图片
"save", # 保存
"scan", # 扫描文件夹
"layer.list", # ls
"layer.select", # sel
"layer.create", # new
"layer.remove", # rm
"canvas.undo", # undo
"canvas.redo", # redo
"canvas.set_tool", # tool
"matte", # 抠图去背景
"canvas.zoom", # zoom
"canvas.set_brush", # brush
"select.rect",
"select.move",
"select.commit",
"app.status",
"app.shutdown",
)
# 其余命令按功能前缀分组
_GROUP_TITLES = (
("layer.", "图层"),
("canvas.", "画布 / 工具"),
("select.", "选区"),
("app.", "应用"),
("commands.", "系统"),
)
def _arg_suffix(meta: dict) -> str:
"""根据 args/params 生成参数占位串:<必填> / [可选]"""
parts = []
for aname in meta.get("args") or []:
p = meta.get("params", {}).get(aname, {})
if p.get("required"):
parts.append(f"<{aname}>")
else:
parts.append(f"[{aname}]")
return " ".join(parts)
def _format_help(schema: Optional[dict]) -> str:
"""格式化命令帮助:常用主要命令优先,其余按功能分组,命令/参数/说明对齐展示"""
if not schema:
return "可用命令:\n (无法获取 schema,请确认服务器已启动)"
# 分组:常用主要命令 → 其余按前缀分组
groups = [("常用命令", [n for n in _COMMON_COMMANDS if n in schema])]
rest = [n for n in schema if n not in _COMMON_COMMANDS]
for prefix, title in _GROUP_TITLES:
names = [n for n in rest if n.startswith(prefix)]
if names:
groups.append((title, names))
rest = [n for n in rest if not n.startswith(prefix)]
if rest:
groups.append(("其他", rest))
lines = ["可用命令(<> 必填参数,[] 可选参数):", ""]
for title, names in groups:
if not names:
continue
lines.append(f" ◆ {title}")
rows = []
for name in names:
meta = schema[name]
arg_s = _arg_suffix(meta)
cmd = name + (" " + arg_s if arg_s else "")
rows.append((cmd, meta))
width = max(len(c[0]) for c in rows)
for cmd, meta in rows:
line = f" {cmd:<{width}} {meta.get('desc', '')}"
aliases = "、".join(meta.get("aliases") or [])
if aliases:
line += f" [别名: {aliases}]"
lines.append(line)
lines.append("")
lines.append(" exit 退出")
return "\n".join(lines)
def _start_conn_monitor(client: Client) -> threading.Event:
"""后台线程监控服务器存活;若 GUI 进程关闭(socket EOF)则退出 REPL。
使用一条专用于监控的独立连接探测服务器,避免与主线程共享主 socket:
主线程 request() 的 _read_frame 会消费响应数据,若监控线程用同一 socket
做 recv(MSG_PEEK),两者存在竞态——主线程刚读完响应、socket 缓冲区为空时,
PEEK 会返回 b'',被误判为服务端 EOF,导致 REPL 误报"主程序已退出"并退出。
监控连接从不发送命令,仅通过 select + recv(MSG_PEEK) 探测 EOF:
服务器关闭(GUI 退出 / 控制服务器关闭)时该连接被关闭,读到 EOF 即退出。
返回一个 stop 事件:REPL 正常退出(exit/EOF)时由调用方置位,
监控线程据此停止,避免把本地 client.close() 误判为服务器断开。
"""
stop = threading.Event()
def _watch() -> None:
try:
mon = socket.create_connection((client._host, client._port), timeout=5.0)
except OSError:
return
mon.settimeout(0.5)
try:
while not stop.is_set():
try:
r, _, _ = select.select([mon], [], [], 0.5)
except (OSError, ValueError):
break
if not r:
continue
try:
peek = mon.recv(1, socket.MSG_PEEK)
except OSError:
break
if not peek: # 服务端已关闭监控连接(GUI 退出)
break
finally:
mon.close()
# 仅当确属服务器关闭连接(而非本地正常退出)时才强制退出 REPL
if not stop.is_set():
print("主程序已退出,REPL 结束", flush=True)
os._exit(0)
threading.Thread(target=_watch, daemon=True).start()
return stop
def _run_repl(client: Client) -> None:
print("InkMoon CLI (输入 help 查看命令, exit 退出)")
schema = _fetch_schema(client)
async_map = _build_async_map(schema)
stop_monitor = _start_conn_monitor(client)
try:
while True:
try:
line = input(">>> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not line:
continue
if line in ("exit", "quit"):
break
if line in ("help", "?"):
print(_format_help(schema))
continue
tokens = line.split()
cmd = tokens[0]
try:
params = _parse_args(tokens[1:])
except ValueError as e:
print(f"ERROR: {e}")
continue
# 关闭指令:发送后端命令关闭主程序,随后退出 REPL。
# 进程退出时服务端会关闭连接,可能收不到响应,连接关闭即视为关闭成功。
if cmd in ("app.shutdown", "shutdown", "app.quit"):
try:
client.request(cmd, params)
except Exception:
pass
print("软件已关闭")
break
try:
msg = client.request(cmd, params)
except ConnectionError:
# 连接被服务器关闭(如 GUI 退出),不必再尝试,结束 REPL
print("连接已断开,REPL 结束")
break
print(_format_result(msg))
if not msg.get("ok"):
continue
task = async_map.get(cmd)
if task:
try:
_wait_task(client, task)
except ConnectionError:
print("连接已断开,REPL 结束")
break
finally:
# 正常退出 REPL:通知监控线程停止,避免误报"主程序已退出"
stop_monitor.set()
def run_repl(host: str = DEFAULT_HOST, port: int = DEFAULT_PORT, token: str = "") -> int:
"""连接服务器并进入交互式 REPL;返回退出码。
供 main.py 在 GUI 主进程的 REPL 线程、以及单实例已运行时的第二实例中调用。
"""
client = Client(host, port, token)
try:
client.connect()
except Exception as e:
print(f"连接失败: {e}", file=sys.stderr)
return 1
try:
_run_repl(client)
return 0
finally:
client.close()
def main() -> int:
parser = argparse.ArgumentParser(description="InkMoon CLI control client")
parser.add_argument("--host", default=DEFAULT_HOST, help="服务器地址")
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="服务器端口")
parser.add_argument("--token", default="", help="鉴权令牌")
parser.add_argument("--launch", action="store_true", help="若服务器未运行则自动启动 GUI")
parser.add_argument("--app", default=None, help="指定 GUI 可执行文件路径(--launch 时使用)")
parser.add_argument("--wait", type=float, default=30.0, help="等待服务器就绪超时(秒)")
parser.add_argument("command", nargs="?", default=None, help="单次命令")
parser.add_argument("params", nargs="*", help="命令参数")
args = parser.parse_args()
if args.launch:
# 位置参数视为要打开的图片路径,传给 GUI
paths = []
if args.command:
paths.append(args.command)
paths.extend(args.params)
cmd = find_gui_exe(args.app)
cmd = cmd + paths
try:
ensure_server_ready(cmd, args.host, args.port, args.wait)
except (TimeoutError, RuntimeError) as e:
print(f"启动失败: {e}", file=sys.stderr)
return 1
client = Client(args.host, args.port, args.token)
try:
client.connect()
except Exception as e:
print(f"连接失败: {e}", file=sys.stderr)
return 1
try:
if args.command and not args.launch:
if args.command == "agent":
# 对话式智能体:子参数拼成自然语言指令
instruction = (" ".join(args.params)).strip() or None
from src.agent.agent import run_agent
return run_agent(client, instruction)
params = _parse_args(args.params)
return _run_single(client, args.command, params)
finally:
client.close()
return run_repl(args.host, args.port, args.token)
if __name__ == "__main__":
sys.exit(main())