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