Files
opu/tools/qmp.py
T
yann64andClaude Opus 5.5 b2ca454d44
CI / Linux arm64 (push) Waiting to run
CI / Linux x86_64 (push) Waiting to run
CI / ASan + UBSan (push) Waiting to run
haiku: USB backend (Storage Kit), bundled doctest, VM sync tooling
- usb_haiku.cpp: lists /dev/disk/usb/* drives (never the boot volume),
  formats MBR + FAT32 at 1 MiB through BDiskDevice/BPartition, mounts,
  unmounts and ejects; modifications are cancelled on failure
- third_party/doctest (MIT single header) used when no system package
  exists (HaikuPorts has none)
- tools/haiku-vm.sh: sync command, dedicated SSH key; tools/qmp.py:
  typefile command and slower key pacing
- builds on Haiku R1/beta6 x86_64; usb-list sees the virtual stick.
  Known issue: some unit tests still fail on Haiku (to investigate).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
2026-11-28 20:20:43 +01:00

175 lines
6.0 KiB
Python

# SPDX-License-Identifier: MIT
"""Drive a headless QEMU VM through QMP: screenshots, absolute clicks, typing, power-off.
usage: python3 tools/qmp.py [--socket PATH] COMMAND...
shot OUT.png screenshot (PNG, no external dependency)
click X Y [right|double] click at screen pixel X,Y (needs a usb-tablet device)
move X Y move the pointer
type TEXT type text with a US keyboard layout
typefile FILE type the content of FILE (newlines press Return)
key COMBO... press key combos, e.g. ret, tab, ctrl-alt-delete, alt-f4
powerdown ACPI power button
hmp COMMAND human monitor command (prints the answer)
"""
import json
import os
import socket
import struct
import sys
import time
import zlib
class Qmp:
def __init__(self, path):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
self.buf = b""
self._read() # greeting
self.cmd("qmp_capabilities")
def _read(self):
while b"\n" not in self.buf:
chunk = self.sock.recv(65536)
if not chunk:
raise RuntimeError("QMP connection closed")
self.buf += chunk
line, self.buf = self.buf.split(b"\n", 1)
return json.loads(line)
def cmd(self, name, **args):
self.sock.sendall(json.dumps({"execute": name, "arguments": args}).encode() + b"\n")
while True:
msg = self._read()
if "return" in msg:
return msg["return"]
if "error" in msg:
raise RuntimeError(f"{name}: {msg['error'].get('desc')}")
# asynchronous events are ignored
def ppm_to_png(ppm, png):
data = open(ppm, "rb").read()
fields, pos = [], 0
while len(fields) < 4: # P6, width, height, maxval
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b"#":
pos = data.index(b"\n", pos) + 1
continue
end = pos
while not data[end:end + 1].isspace():
end += 1
fields.append(data[pos:end])
pos = end
width, height = int(fields[1]), int(fields[2])
pixels = data[pos + 1:]
stride = width * 3
raw = b"".join(b"\x00" + pixels[y * stride:(y + 1) * stride] for y in range(height))
def chunk(kind, payload):
body = kind + payload
return struct.pack(">I", len(payload)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
with open(png, "wb") as f:
f.write(b"\x89PNG\r\n\x1a\n")
f.write(chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)))
f.write(chunk(b"IDAT", zlib.compress(raw, 6)))
f.write(chunk(b"IEND", b""))
return width, height
def screen_size(q):
tmp = f"/tmp/qmp-size-{os.getpid()}.ppm"
q.cmd("screendump", filename=tmp)
with open(tmp, "rb") as f:
head = f.read(64).split()
os.unlink(tmp)
return int(head[1]), int(head[2])
def move(q, x, y):
w, h = screen_size(q)
q.cmd("input-send-event", events=[
{"type": "abs", "data": {"axis": "x", "value": int(x * 32767 / max(1, w - 1))}},
{"type": "abs", "data": {"axis": "y", "value": int(y * 32767 / max(1, h - 1))}},
])
def click(q, x, y, mode="left"):
move(q, x, y)
button = "right" if mode == "right" else "left"
for _ in range(2 if mode == "double" else 1):
for down in (True, False):
q.cmd("input-send-event", events=[{"type": "btn", "data": {"down": down, "button": button}}])
time.sleep(0.05)
SHIFTED = {"_": "minus", ":": "semicolon", "\"": "apostrophe", "<": "comma", ">": "dot", "?": "slash",
"!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9",
")": "0", "+": "equal", "{": "bracket_left", "}": "bracket_right", "|": "backslash", "~": "grave_accent"}
PLAIN = {" ": "spc", "-": "minus", ".": "dot", "/": "slash", ",": "comma", ";": "semicolon", "'": "apostrophe",
"=": "equal", "[": "bracket_left", "]": "bracket_right", "\\": "backslash", "`": "grave_accent",
"\n": "ret", "\t": "tab"}
def keys_for(ch):
if ch.isalpha() and ch.isascii():
return (["shift"] if ch.isupper() else []) + [ch.lower()]
if ch.isdigit():
return [ch]
if ch in PLAIN:
return [PLAIN[ch]]
if ch in SHIFTED:
return ["shift", SHIFTED[ch]]
raise ValueError(f"cannot type {ch!r}")
def press(q, names):
# send-key returns before QEMU replays the keys: wait longer than the hold time, or
# consecutive keys overlap (and a held shift leaks into the next characters).
q.cmd("send-key", keys=[{"type": "qcode", "data": n} for n in names], **{"hold-time": 30})
time.sleep(0.08)
def main():
args = sys.argv[1:]
path = os.path.expanduser("~/openpu-vm/qmp.sock")
if args[:1] == ["--socket"]:
path, args = args[1], args[2:]
if not args:
print(__doc__, file=sys.stderr)
sys.exit(2)
q = Qmp(path)
cmd, rest = args[0], args[1:]
if cmd == "shot":
tmp = os.path.abspath(rest[0]) + ".ppm"
q.cmd("screendump", filename=tmp)
w, h = ppm_to_png(tmp, rest[0])
os.unlink(tmp)
print(f"{rest[0]} {w}x{h}")
elif cmd == "click":
click(q, int(rest[0]), int(rest[1]), rest[2] if len(rest) > 2 else "left")
elif cmd == "move":
move(q, int(rest[0]), int(rest[1]))
elif cmd == "type":
for ch in " ".join(rest):
press(q, keys_for(ch))
elif cmd == "typefile":
with open(rest[0], encoding="utf-8") as f:
for ch in f.read():
press(q, keys_for(ch))
elif cmd == "key":
for combo in rest:
press(q, combo.split("-"))
elif cmd == "powerdown":
q.cmd("system_powerdown")
elif cmd == "hmp":
print(q.cmd("human-monitor-command", **{"command-line": " ".join(rest)}))
else:
print(__doc__, file=sys.stderr)
sys.exit(2)
main()