|
|
1.1 root 1: #!/usr/bin/env python
2: #
3: # Hatari console:
4: # Allows using Hatari shortcuts & debugger, changing paths, toggling
5: # devices and changing Hatari command line options (even for things you
6: # cannot change from the UI) from the console while Hatari is running.
7: #
1.1.1.6 root 8: # Copyright (C) 2008-2014 by Eero Tamminen
1.1 root 9: #
10: # This program is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # This program is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19:
20: import os
21: import sys
22: import time
23: import signal
24: import socket
25: import readline
26:
27: # Python v2:
28: # - lacks Python v3 encoding arg for bytes()
29: # - input() evaluates given string and fails on empty one
30: if str is bytes:
31: def bytes(s, encoding):
32: return s
33: def input(prompt):
34: return raw_input(prompt)
35:
36: class Scancode:
1.1.1.4 root 37: "Atari scancodes for keys without alphanumeric characters"
38: # US keyboard scancode mapping for characters which need shift
39: Shifted = {
40: '!': "0x2",
41: '@': "0x3",
42: '#': "0x4",
43: '$': "0x5",
44: '%': "0x6",
45: '^': "0x7",
46: '&': "0x8",
47: '*': "0x9",
48: '(': "10",
49: ')': "11",
50: '_': "12",
51: '+': "13",
52: '~': "41",
53: '{': "26",
54: '}': "27",
55: ':': "39",
56: '"': "40",
57: '|': "43",
58: '<': "51",
59: '>': "52",
60: '?': "53"
61: }
62: # US keyboard scancode mapping for characters which don't need shift
63: UnShifted = {
64: '-': "12",
65: '=': "13",
66: '[': "26",
67: ']': "27",
68: ';': "39",
69: "'": "40",
70: '\\': "43",
71: '",': "51",
72: '.': "52",
73: '/': "53"
74: }
75: # special keys without corresponding character
1.1 root 76: Tab = "15"
77: Return = "28"
78: Enter = "114"
79: Space = "57"
80: Delete = "83"
81: Backspace = "14"
82: Escape = "0x1"
83: Control = "29"
84: Alternate = "56"
85: LeftShift = "42"
86: RightShift = "54"
87: CapsLock = "53"
88: Insert = "82"
89: Home = "71"
90: Help = "98"
91: Undo = "97"
92: CursorUp = "72"
93: CursorDown = "80"
94: CursorLeft = "75"
95: CursorRight = "77"
96:
97:
98: # running Hatari instance
99: class Hatari:
100: controlpath = "/tmp/hatari-console-" + str(os.getpid()) + ".socket"
101: hataribin = "hatari"
102:
1.1.1.6 root 103: def __init__(self, args):
1.1.1.7 root 104: # member defaults
105: self.pid = 0
106: self.interval = 0.2
107: self.shiftdown = False
108: self.verbose = False
109: self.control = None
110: self.paused = False
111: self.winuae = False
1.1 root 112: # collect hatari process zombies without waitpid()
113: signal.signal(signal.SIGCHLD, signal.SIG_IGN)
114: self._assert_hatari_compatibility()
115: self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
116: if os.path.exists(self.controlpath):
117: os.unlink(self.controlpath)
118: self.server.bind(self.controlpath)
119: self.server.listen(1)
120: if not self.run_hatari(args):
121: print("ERROR: failed to run Hatari")
122: sys.exit(1)
123:
124: def _assert_hatari_compatibility(self):
1.1.1.4 root 125: "check Hatari compatibility and return error string if it's not"
1.1.1.8 ! root 126: print("Using following Hatari binary:")
! 127: os.system("which %s" % self.hataribin)
1.1.1.4 root 128: error = True
129: pipe = os.popen(self.hataribin + " -h")
130: for line in pipe.readlines():
1.1.1.7 root 131: if line.find("--addr24") >= 0:
132: self.winuae = True
1.1 root 133: if line.find("--control-socket") >= 0:
1.1.1.4 root 134: error = False
135: break
136: try:
137: pipe.close()
138: except IOError:
139: pass
140: if error:
141: print("ERROR: %s" % error)
142: sys.exit(-1)
1.1 root 143:
144: def is_running(self):
145: if not self.pid:
146: return False
147: try:
148: os.waitpid(self.pid, os.WNOHANG)
149: except OSError as value:
150: print("Hatari PID %d had exited in the meanwhile:\n\t%s" % (self.pid, value))
151: self.pid = 0
1.1.1.3 root 152: if self.control:
153: self.control.close()
154: self.control = None
1.1 root 155: return False
156: return True
157:
158: def run_hatari(self, args):
159: if self.control:
160: print("ERROR: Hatari is already running, stop it first")
161: return
162: pid = os.fork()
163: if pid < 0:
164: print("ERROR: fork()ing Hatari failed!")
165: return
166: if pid:
167: # in parent
168: self.pid = pid
169: print("WAIT hatari to connect to control socket...")
170: (self.control, addr) = self.server.accept()
171: print("connected!")
172: return self.control
173: else:
174: # child runs Hatari
175: allargs = [self.hataribin, "--control-socket", self.controlpath] + args
176: print("RUN:", allargs)
177: os.execvp(self.hataribin, allargs)
178:
179: def send_message(self, msg, fast = False):
180: if self.control:
181: if self.verbose:
182: print("-> '%s'" % msg)
183: self.control.sendall(bytes(msg + "\n", "ASCII"))
184: # KLUDGE: wait so that Hatari output comes before next prompt
185: if fast:
1.1.1.4 root 186: interval = self.interval/4
1.1 root 187: else:
188: interval = self.interval
189: time.sleep(interval)
190: return True
191: else:
192: print("ERROR: no Hatari (control socket)")
193: return False
194:
195: def change_option(self, option):
196: return self.send_message("hatari-option %s" % option)
197:
198: def trigger_shortcut(self, shortcut):
199: return self.send_message("hatari-shortcut %s" % shortcut)
1.1.1.4 root 200:
201: def _shift_up(self):
202: if self.shiftdown:
203: self.shiftdown = False
204: return self.send_message("hatari-event keyup %s" % Scancode.LeftShift, True)
205: return True
206:
207: def _unshifted_keypress(self, key):
208: self._shift_up()
209: if key == ' ':
210: # white space gets stripped, use scancode instead
211: key = Scancode.Space
212: return self.send_message("hatari-event keypress %s" % key, True)
213:
214: def _shifted_keypress(self, key):
215: if not self.shiftdown:
216: self.shiftdown = True
217: self.send_message("hatari-event keydown %s" % Scancode.LeftShift, True)
218: return self.send_message("hatari-event keypress %s" % key, True)
1.1 root 219:
220: def send_string(self, text):
221: print("string:", text)
1.1.1.4 root 222: for key in text:
223: if key in Scancode.Shifted:
224: ok = self._shifted_keypress(Scancode.Shifted[key])
225: elif key in Scancode.UnShifted:
226: ok = self._unshifted_keypress(Scancode.UnShifted[key])
227: else:
228: ok = self._unshifted_keypress(key)
229: if not ok:
1.1 root 230: return False
1.1.1.4 root 231: return self._shift_up()
1.1 root 232:
233: def insert_event(self, event):
234: if event.startswith("text "):
235: cmd, value = event.split(None, 1)
236: if value:
237: return self.send_string(value)
238: return self.send_message("hatari-event %s" % event, True)
239:
240: def debug_command(self, cmd):
241: return self.send_message("hatari-debug %s" % cmd)
242:
243: def change_path(self, path):
244: return self.send_message("hatari-path %s" % path)
245:
246: def toggle_device(self, device):
247: return self.send_message("hatari-toggle %s" % device)
248:
249: def toggle_pause(self):
250: self.paused = not self.paused
251: if self.paused:
252: return self.send_message("hatari-stop")
253: else:
254: return self.send_message("hatari-cont")
255:
256: def toggle_verbose(self):
257: self.verbose = not self.verbose
258: print("debug output", self.verbose)
259:
260: def kill_hatari(self):
1.1.1.3 root 261: if self.is_running():
1.1 root 262: os.kill(self.pid, signal.SIGKILL)
263: print("killed hatari with PID %d" % self.pid)
264: self.pid = 0
1.1.1.3 root 265: if self.control:
266: self.control.close()
267: self.control = None
1.1 root 268:
269:
270: # command line parsing with readline
271: class CommandInput:
272: prompt = "hatari-command: "
273: historysize = 99
274:
275: def __init__(self, commands):
276: readline.set_history_length(self.historysize)
277: readline.parse_and_bind("tab: complete")
278: readline.set_completer_delims(" \t\r\n")
279: readline.set_completer(self.complete)
280: self.commands = commands
281:
282: def complete(self, text, state):
283: idx = 0
284: #print "text: '%s', state '%d'" % (text, state)
285: for cmd in self.commands:
286: if cmd.startswith(text):
287: idx += 1
288: if idx > state:
289: return cmd
290:
291: def loop(self):
292: try:
293: rawline = input(self.prompt)
294: return rawline
295: except EOFError:
296: return ""
297:
298:
299: class Tokens:
1.1.1.3 root 300: # update with: hatari -h|grep -- --|sed 's/^ *\(--[^ ]*\).*$/ "\1",/'|grep -v -e control-socket -e 'joy<'
1.1 root 301: option_tokens = [
302: "--help",
303: "--version",
304: "--confirm-quit",
305: "--configfile",
1.1.1.3 root 306: "--keymap",
1.1 root 307: "--fast-forward",
308: "--mono",
309: "--monitor",
310: "--fullscreen",
311: "--window",
312: "--grab",
313: "--frameskips",
314: "--statusbar",
315: "--drive-led",
316: "--bpp",
1.1.1.3 root 317: "--borders",
318: "--desktop-st",
319: "--spec512",
320: "--zoom",
321: "--desktop",
322: "--max-width",
323: "--max-height",
324: "--force-max",
325: "--aspect",
1.1 root 326: "--vdi",
327: "--vdi-planes",
328: "--vdi-width",
329: "--vdi-height",
1.1.1.3 root 330: "--crop",
1.1 root 331: "--avirecord",
332: "--avi-vcodec",
333: "--avi-fps",
334: "--avi-file",
335: "--joy0",
336: "--joy1",
337: "--joy2",
338: "--joy3",
339: "--joy4",
340: "--joy5",
341: "--joystick",
342: "--printer",
343: "--midi-in",
344: "--midi-out",
345: "--rs232-in",
346: "--rs232-out",
347: "--disk-a",
348: "--disk-b",
1.1.1.2 root 349: "--fastfdc",
1.1 root 350: "--protect-floppy",
351: "--protect-hd",
352: "--harddrive",
353: "--acsi",
354: "--ide-master",
355: "--ide-slave",
356: "--memsize",
1.1.1.3 root 357: "--memstate",
1.1 root 358: "--tos",
1.1.1.3 root 359: "--patch-tos",
1.1 root 360: "--cartridge",
361: "--cpulevel",
362: "--cpuclock",
363: "--compatible",
364: "--machine",
365: "--blitter",
366: "--dsp",
1.1.1.3 root 367: "--timer-d",
368: "--fast-boot",
369: "--rtc",
370: "--mic",
1.1 root 371: "--sound",
1.1.1.3 root 372: "--sound-buffer-size",
373: "--ym-mixing",
1.1 root 374: "--debug",
375: "--bios-intercept",
1.1.1.5 root 376: "--conout",
1.1 root 377: "--trace",
378: "--trace-file",
379: "--parse",
380: "--saveconfig",
1.1.1.3 root 381: "--no-parachute",
1.1 root 382: "--log-file",
383: "--log-level",
384: "--alert-level",
385: "--run-vbls"
386: ]
387: shortcut_tokens = [
388: "mousegrab",
389: "coldreset",
390: "warmreset",
391: "screenshot",
392: "bosskey",
393: "recanim",
394: "recsound",
395: "savemem"
396: ]
397: event_tokens = [
398: "doubleclick",
399: "rightdown",
400: "rightup",
401: "keypress",
402: "keydown",
403: "keyup",
404: "text" # simulated with keypresses
405: ]
406: device_tokens = [
407: "printer",
408: "rs232",
409: "midi",
410: ]
411: path_tokens = [
412: "memauto",
413: "memsave",
414: "midiout",
415: "printout",
416: "soundout",
417: "rs232in",
418: "rs232out"
419: ]
420: # use the long variants of the commands for clarity
421: debugger_tokens = [
422: "address",
423: "breakpoint",
424: "cd",
425: "cont",
426: "cpureg",
427: "disasm",
428: "dspaddress",
429: "dspbreak",
430: "dspcont",
431: "dspdisasm",
432: "dspmemdump",
433: "dspreg",
434: "dspsymbols",
435: "evaluate",
436: "help",
1.1.1.3 root 437: "history",
1.1 root 438: "info",
439: "loadbin",
440: "lock",
441: "logfile",
442: "memdump",
443: "memwrite",
444: "parse",
1.1.1.3 root 445: "profile",
446: "quit",
1.1 root 447: "savebin",
448: "setopt",
449: "stateload",
450: "statesave",
451: "symbols",
452: "trace"
453: ]
454:
1.1.1.6 root 455: def __init__(self, hatari, do_exit = True):
1.1 root 456: self.process_tokens = {
457: "kill": hatari.kill_hatari,
458: "pause": hatari.toggle_pause
459: }
460: self.script_tokens = {
461: "script": self.do_script,
462: "sleep": self.do_sleep
463: }
464: self.help_tokens = {
465: "usage": self.show_help,
466: "verbose": hatari.toggle_verbose
467: }
468: self.hatari = hatari
1.1.1.6 root 469: # whether to exit when Hatari disappears
470: self.do_exit = do_exit
1.1 root 471:
472: def get_tokens(self):
473: tokens = []
474: for items in [self.option_tokens, self.shortcut_tokens,
475: self.event_tokens, self.debugger_tokens, self.device_tokens,
476: self.path_tokens, list(self.process_tokens.keys()),
477: list(self.script_tokens.keys()), list(self.help_tokens.keys())]:
478: for token in items:
479: if token in tokens:
480: print("ERROR: token '%s' already in tokens" % token)
481: sys.exit(1)
482: tokens += items
483: return tokens
484:
485: def show_help(self):
486: print("""
487: Hatari-console help
488: -------------------
489:
490: Hatari-console allows you to control Hatari through its control socket
491: from the provided console prompt, while Hatari is running. All control
492: commands support TAB completion on their names and options.
493:
494: The supported control facilities are:""")
495: self.list_items("Command line options", self.option_tokens)
496: self.list_items("Keyboard shortcuts", self.shortcut_tokens)
497: self.list_items("Event invocation", self.event_tokens)
498: self.list_items("Device toggling", self.device_tokens)
499: self.list_items("Path setting", self.path_tokens)
500: self.list_items("Debugger commands", self.debugger_tokens)
501: print("""
502: "pause" toggles Hatari paused state on/off.
503: "kill" will terminate Hatari.
504:
505: "script" command reads commands from the given file.
506: "sleep" command can be used in script to wait given number of seconds.
507: "verbose" command toggles commands debug output on/off.
508:
509: For command line options you can get further help with "--help"
510: and for debugger commands with "help". Some of the other facilities
511: give help when you give them invalid input.
512: """)
513:
514: def list_items(self, title, items):
515: print("\n%s:" % title)
516: for item in items:
517: print("*", item)
518:
519: def do_sleep(self, line):
520: items = line.split()[1:]
521: try:
522: secs = int(items[0])
523: except:
524: secs = 0
525: if secs > 0:
526: print("Sleeping for %d secs..." % secs)
527: time.sleep(secs)
528: else:
529: print("usage: sleep <seconds>")
530:
531: def do_script(self, line):
532: try:
533: filename = line.split()[1]
534: f = open(filename)
535: except:
536: print("usage: script <filename>")
537: return
538:
539: for line in f.readlines():
540: line = line.strip()
541: if not line or line[0] == '#':
542: continue
543: print(">", line)
544: self.process_command(line)
545:
546: def process_command(self, line):
547: if not self.hatari.is_running():
1.1.1.6 root 548: print("There's no Hatari (anymore)!")
549: if not self.do_exit:
550: return False
551: print("Exiting...")
1.1 root 552: sys.exit(0)
553: if not line:
1.1.1.6 root 554: return False
1.1 root 555:
556: first = line.split()[0]
557: # multiple items
558: if first in self.event_tokens:
559: self.hatari.insert_event(line)
560: elif first in self.debugger_tokens:
561: self.hatari.debug_command(line)
562: elif first in self.option_tokens:
563: self.hatari.change_option(line)
564: elif first in self.path_tokens:
565: self.hatari.change_path(line)
566: elif first in self.script_tokens:
567: self.script_tokens[first](line)
568: # single item
569: elif line in self.device_tokens:
570: self.hatari.toggle_device(line)
571: elif line in self.shortcut_tokens:
572: self.hatari.trigger_shortcut(line)
573: elif line in self.process_tokens:
574: self.process_tokens[line]()
575: elif line in self.help_tokens:
576: self.help_tokens[line]()
577: else:
578: print("ERROR: unknown hatari-console command:", line)
1.1.1.6 root 579: return False
580: return True
1.1 root 581:
582: class Main:
1.1.1.6 root 583: def __init__(self, options, do_exit=True):
584: args, self.file, self.exit = self.parse_args(options)
1.1 root 585: hatari = Hatari(args)
1.1.1.6 root 586: self.tokens = Tokens(hatari, do_exit)
1.1 root 587: self.command = CommandInput(self.tokens.get_tokens())
588:
589: def parse_args(self, args):
590: if "-h" in args or "--help" in args:
591: self.usage()
592:
593: file = []
594: exit = False
595: if "--" not in args:
596: return (args[1:], file, exit)
597:
598: for arg in args:
599: if arg == "--":
600: return (args[args.index("--")+1:], file, exit)
601: if arg == "--exit":
602: exit = True
603: continue
604: if os.path.exists(arg):
605: file = arg
606: else:
607: self.usage("file '%s' not found" % arg)
608:
609: def usage(self, msg=None):
610: name = os.path.basename(sys.argv[0])
611: print("\n%s" % name)
612: print("=" * len(name))
613: print("""
614: Usage: %s [<console options/args> --] [<hatari options>]
615:
616: Hatari console options/args:
617: \t<file>\t\tread commands from given file
618: \t--exit\t\texit after executing the commands in the file
619: \t-h, --help\t\tthis help
620:
621: Except for help, console options/args will be interpreted
622: only if '--' is given as one of the arguments. Otherwise
623: all arguments are given to Hatari.
624:
625: For example:
626: %s --monitor mono test.prg
627: %s commands.txt -- --monitor mono
628: %s commands.txt --exit --
629: """ % (name, name, name, name))
630: if msg:
631: print("ERROR: %s!\n" % msg)
632: sys.exit(1)
633:
634: def loop(self):
635: print("""
636: *********************************************************
637: * To see available commands, use the TAB key or 'usage' *
638: *********************************************************
639: """)
640: if self.file:
641: self.script(self.file)
642: if self.exit:
643: sys.exit(0)
644:
645: while 1:
646: line = self.command.loop().strip()
647: self.tokens.process_command(line)
648:
649: def script(self, filename):
650: self.tokens.do_script("script " + filename)
651:
652: def run(self, line):
1.1.1.6 root 653: "helper method for running Hatari commands with hatari-console, returns False on error"
654: return self.tokens.process_command(line)
1.1 root 655:
656:
657: if __name__ == "__main__":
1.1.1.6 root 658: Main(sys.argv).loop()
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.