62 lines
3.2 KiB
Python
62 lines
3.2 KiB
Python
"""Read only the task-owned EDA canvas; never focus, save, open or edit a document."""
|
|
import base64
|
|
import fcntl
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
CODE = r'''const doc = await eda.dmt_SelectControl.getCurrentDocumentInfo();
|
|
if (!doc || ![1,3,12,15].includes(doc.documentType)) return {available:false};
|
|
const image = await eda.dmt_EditorControl.getCurrentRenderedAreaImage(doc.tabId);
|
|
if (!image || !image.size || image.size > 8*1024*1024) return {available:false};
|
|
const data = await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(image);});
|
|
return {available:true,kind:doc.documentType===1?'schematic':doc.documentType===15?'3d':'layout',image:data};'''
|
|
|
|
def capture(tid):
|
|
if not re.fullmatch(r'pcb-[0-9a-f]{24}', tid):
|
|
return {'available': False, 'reason': 'invalid_task'}
|
|
root = Path(os.environ.get('PCB_SESSION_ROOT', '/home/wpz/auto_pcb_2/persistent-runtime'))
|
|
task = json.loads((root / 'tasks' / tid / 'state.json').read_text())
|
|
session = task.get('eda_session', '')
|
|
if not task.get('approval') or not re.fullmatch(r'[0-9a-f-]{36}', session):
|
|
return {'available': False, 'reason': 'waiting_for_canvas'}
|
|
# Same host lock as generation, acquired without waiting. Production takes priority.
|
|
lock = Path.home()/'.local/state/ai-pcb-eda/locks/host.lock'
|
|
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
with lock.open('a+') as fd:
|
|
try:
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
return {'available': False, 'reason': 'eda_busy'}
|
|
env = dict(os.environ, DISPLAY=os.environ.get('DISPLAY', ':0'), XDG_RUNTIME_DIR=f'/run/user/{os.getuid()}')
|
|
if not env.get('XAUTHORITY'):
|
|
auth = list(Path(env['XDG_RUNTIME_DIR']).glob('.mutter-Xwaylandauth.*'))
|
|
if auth:
|
|
env['XAUTHORITY'] = str(auth[0])
|
|
result = subprocess.run(['/usr/local/bin/lceda-pro', 'invoke', '--session', session,
|
|
'--ext-uuid', 'eda', '--code-file', '-', '--timeout', '3000', '--no-sandbox'],
|
|
input=CODE, capture_output=True, text=True, env=env, timeout=5)
|
|
reply = json.loads(result.stdout)
|
|
if result.returncode or reply.get('ok') is not True:
|
|
return {'available': False, 'reason': 'canvas_unavailable'}
|
|
value = reply.get('value') or {}
|
|
image = value.get('image', '')
|
|
if not value.get('available'):
|
|
return {'available': False, 'reason': 'waiting_for_canvas'}
|
|
if not image.startswith('data:image/png;base64,'):
|
|
return {'available': False, 'reason': 'unsupported_image'}
|
|
raw = base64.b64decode(image.split(',', 1)[1], validate=True)
|
|
if not raw.startswith(b'\x89PNG\r\n\x1a\n') or len(raw) > 8*1024*1024:
|
|
return {'available': False, 'reason': 'invalid_image'}
|
|
return {'available': True, 'kind': value['kind'], 'image': image}
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
answer = capture(sys.argv[1])
|
|
except Exception:
|
|
answer = {'available': False, 'reason': 'canvas_unavailable'}
|
|
print(json.dumps(answer))
|