test-lab/probes/gnome_vm_input.py

70 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""Native QMP keyboard/pointer input and a screenshot for a lab GNOME VM."""
import argparse
import json
from pathlib import Path
import socket
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('run', type=Path)
parser.add_argument('--click', nargs=2, type=int, metavar=('X', 'Y'))
parser.add_argument('--keys', nargs='+')
parser.add_argument('--text')
parser.add_argument('--select-all', action='store_true', help='Select the focused field before replacing its text')
parser.add_argument('--text-file', type=Path, help='Private credential file; contents are never logged')
parser.add_argument('--screen', default='interaction.png')
args = parser.parse_args()
with socket.socket(socket.AF_UNIX) as connection:
connection.settimeout(15)
connection.connect(str(args.run / 'qmp.sock'))
with connection.makefile('rwb') as stream:
json.loads(stream.readline())
def call(command, arguments=None):
stream.write((json.dumps({'execute': command, 'arguments': arguments or {}}) + '\n').encode())
stream.flush()
while True:
response = json.loads(stream.readline())
if 'error' in response:
raise RuntimeError(response['error'])
if 'return' in response:
return response['return']
def key(code):
call('send-key', {'keys': [{'type': 'qcode', 'data': code}], 'hold-time': 50})
time.sleep(0.2)
call('qmp_capabilities')
if args.click:
# Target VM uses a 1280x800 display and an absolute USB tablet.
x, y = args.click
if not 0 <= x < 1280 or not 0 <= y < 800:
raise ValueError('Click outside 1280x800 display')
call('input-send-event', {'events': [
{'type': 'abs', 'data': {'axis': 'x', 'value': round(x * 32767 / 1279)}},
{'type': 'abs', 'data': {'axis': 'y', 'value': round(y * 32767 / 799)}},
{'type': 'btn', 'data': {'down': True, 'button': 'left'}}]})
call('input-send-event', {'events': [
{'type': 'btn', 'data': {'down': False, 'button': 'left'}}]})
# Allow the compositor to deliver focus before sending text.
time.sleep(0.5)
if args.select_all:
call('send-key', {'keys': [{'type': 'qcode', 'data': code} for code in ('ctrl', 'a')], 'hold-time': 50})
time.sleep(0.3)
text = args.text_file.read_text().strip() if args.text_file else args.text
if text:
if any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789 -.' for c in text):
raise ValueError('Text input supports lowercase US ASCII only')
for char in text:
key({' ': 'spc', '-': 'minus', '.': 'dot'}.get(char, char))
for code in args.keys or []:
key(code)
time.sleep(2)
call('screendump', {'filename': str(args.run / args.screen), 'format': 'png'})
if __name__ == '__main__':
main()