128 lines
6.0 KiB
Python
128 lines
6.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Run the installed Freerouting 1.9.0 without interactive startup dialogs.
|
|
|
|
This is a process/argument adapter, not a PCB design or routing algorithm.
|
|
"""
|
|
import argparse
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
|
|
# Version-specific CLI contract. Never pass unknown/help/input/dialog switches
|
|
# through to Java: 1.9.0 silently ignores some of them and opens an idle GUI.
|
|
VALUE_OPTIONS = {'-mp', '-mt', '-oit', '-us', '-hr', '-is', '-inc', '-dr', '-l'}
|
|
FLAG_OPTIONS = {'-im', '-da'}
|
|
|
|
|
|
def router_options(values):
|
|
values = list(values)
|
|
if values[:1] == ['--']:
|
|
values.pop(0)
|
|
result = []
|
|
while values:
|
|
option = values.pop(0)
|
|
if option in FLAG_OPTIONS:
|
|
result.append(option)
|
|
elif option in VALUE_OPTIONS:
|
|
if not values or values[0].startswith('-'):
|
|
raise ValueError(f'{option} requires a value')
|
|
result.extend([option, values.pop(0)])
|
|
else:
|
|
raise ValueError(f'Unsupported router option: {option}; use wrapper --help')
|
|
return result
|
|
|
|
|
|
def stop_process(process):
|
|
# Java and the private Xvfb belong to this process group only.
|
|
try:
|
|
os.killpg(process.pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
return
|
|
try:
|
|
process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
pass
|
|
try:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
except ProcessLookupError:
|
|
pass
|
|
process.wait()
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--input', required=True, type=Path, help='Existing DSN input')
|
|
parser.add_argument('--output', required=True, type=Path, help='New SES output; existing files are refused')
|
|
root = Path(os.environ.get('PCB_SESSION_ROOT') or Path.home() / '.local/share/vibemake-pcb').expanduser().resolve()
|
|
default_jar = root / 'resources/freerouting.jar'
|
|
parser.add_argument('--jar', type=Path, default=os.environ.get('PCB_FREEROUTING_JAR', str(default_jar)))
|
|
parser.add_argument('--timeout', type=float, default=900, help='Maximum process seconds (default 900); partial output is not accepted')
|
|
parser.add_argument('--visible', action='store_true', help='Diagnostic only: use the current desktop instead of private Xvfb')
|
|
parser.add_argument('router_args', nargs=argparse.REMAINDER, help='After --: Freerouting options, e.g. -mp 30 -mt 1')
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
options = router_options(args.router_args)
|
|
source, target, jar = args.input.resolve(), args.output.resolve(), args.jar.expanduser().resolve()
|
|
if not math.isfinite(args.timeout) or args.timeout <= 0:
|
|
raise ValueError('--timeout must be a positive finite number')
|
|
if not source.is_file() or source.suffix.lower() != '.dsn':
|
|
raise ValueError('--input must be an existing .dsn file')
|
|
if target.suffix.lower() != '.ses' or target.exists() or args.output.is_symlink():
|
|
raise ValueError('--output must be a new .ses file (choose a new name for each attempt)')
|
|
if not jar.is_file():
|
|
raise ValueError(f'Freerouting JAR not found: {jar}')
|
|
java = shutil.which('java')
|
|
if not java:
|
|
raise ValueError('Java is not installed or not on PATH')
|
|
xvfb = shutil.which('xvfb-run')
|
|
if not args.visible and (not xvfb or not shutil.which('Xvfb') or not shutil.which('xauth')):
|
|
raise ValueError('Install xvfb and xauth for unattended routing; --visible is diagnostic only')
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(prefix='.freerouting-', dir=target.parent) as temporary:
|
|
temporary = Path(temporary)
|
|
home = temporary / 'home'
|
|
home.mkdir()
|
|
# Do not auto-load an adjacent old .rules/.bin snapshot and prompt
|
|
# for confirmation. Explicit -dr remains available to the agent.
|
|
isolated_source = temporary / 'board.dsn'
|
|
shutil.copyfile(source, isolated_source)
|
|
pending = temporary / 'result.ses'
|
|
command = [java, f'-Duser.home={home}', f'-Djava.io.tmpdir={temporary}', '-jar', str(jar),
|
|
'-de', str(isolated_source), '-do', str(pending), *options, '-dct', '0', '-da']
|
|
if not args.visible:
|
|
command = [xvfb, '-a', '-f', str(temporary / 'Xauthority'), '-s', '-screen 0 1280x1024x24 -nolisten tcp', *command]
|
|
env = dict(os.environ, TMPDIR=str(temporary))
|
|
print(f'Freerouting: {source} -> {target}; confirmation disabled; timeout={args.timeout:g}s', flush=True)
|
|
process = subprocess.Popen(command, env=env, start_new_session=True)
|
|
try:
|
|
code = process.wait(timeout=args.timeout)
|
|
except subprocess.TimeoutExpired:
|
|
stop_process(process)
|
|
print('Freerouting timed out; no output published. Inspect the log before choosing another attempt.', file=sys.stderr)
|
|
return 124
|
|
except KeyboardInterrupt:
|
|
stop_process(process)
|
|
return 130
|
|
if code:
|
|
print(f'Freerouting exited with {code}; no output published', file=sys.stderr)
|
|
return code if code > 0 else 1
|
|
if not pending.is_file() or pending.stat().st_size < 20 or not pending.read_bytes().lstrip().startswith(b'(session'):
|
|
raise ValueError('Freerouting did not produce a valid SES session file')
|
|
# Same filesystem, no overwrite race and no stale/partial SES success.
|
|
os.link(pending, target)
|
|
print(f'Saved {target} ({target.stat().st_size} bytes). Import and run native DRC; process success is not board validation.', flush=True)
|
|
return 0
|
|
except (ValueError, OSError) as error:
|
|
print(f'Freerouting launcher: {error}', file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|