Debian Codegraph @

tools/gencontrollerdb.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import os
4 import datetime
5
6 from urllib.request import urlopen
7
8
9 # This script parses the SDL game controller db header file from the
10 # SDL mercurial repository, and generates a list of mappings to be used
11 # internally by pyglet. This script may need to be updated if the
12 # format or url changes.
13
14
15 # Get the raw database header file:
16 DB_URL = "https://hg.libsdl.org/SDL/raw-file/default/src/joystick/SDL_gamepad_db.h"
17 raw = urlopen(DB_URL).read().decode('ascii')
18
19 # Format the output directory for the pyglet module:
20 script_dir = os.path.abspath(os.path.dirname(__file__))
21 output_dir = os.path.join(script_dir, os.path.pardir, 'pyglet', 'input')
22 output_file = os.path.join(output_dir, 'controller_db.py')
23
24 # Parse the Windows section:
25 win_string = '#ifdef SDL_JOYSTICK_DINPUT'
26 win_start = raw.find(win_string) + len(win_string)
27 win_end = raw.find('#endif', win_start)
28 win_raw = raw[win_start:win_end]
29
30 # Parse the Mac OSX section:
31 mac_string = '#ifdef SDL_PLATFORM_MACOS'
32 mac_start = raw.find(mac_string) + len(mac_string)
33 mac_end = raw.find('#endif', mac_start)
34 mac_raw = raw[mac_start:mac_end]
35
36 # Parse the Linux section:
37 lin_string = '#if defined(SDL_JOYSTICK_LINUX) || defined(SDL_PLATFORM_OPENBSD)'
38 lin_start = raw.find(lin_string) + len(lin_string)
39 lin_end = raw.find('#endif', lin_start)
40 lin_raw = raw[lin_start:lin_end]
41
42
43 def strip_lines(raw_lines):
44 """Strip invalid lines and C comments"""
45 lines = []
46 for line in raw_lines.splitlines():
47 line = line.strip()
48 if '"' in line:
49 line = line.split('"')[1]
50 lines.append(line)
51 return lines
52
53
54 # Create lists of formatted lines:
55 win_lines = strip_lines(win_raw)
56 mac_lines = strip_lines(mac_raw)
57 lin_lines = strip_lines(lin_raw)
58
59
60 # Write out a valid Python module in the pyglet/input directory:
61 with open(output_file, 'w+') as f:
62 f.write("from pyglet import compat_platform\n\n\n")
63 f.write("# This file is automatically generated by 'pyglet/tools/gen_controller_db.py'\n")
64 f.write("# Generated on: {0}\n\n".format(datetime.datetime.now().strftime('%c')))
65
66 f.write("""if compat_platform.startswith("linux"):\n mapping_list = [\n""")
67 for lin_line in lin_lines:
68 f.write(f'"{lin_line}",\n')
69 f.write("]\n")
70
71 f.write("""elif compat_platform.startswith("darwin"):\n mapping_list = [\n""")
72 for mac_line in mac_lines:
73 f.write(f'"{mac_line}",\n')
74 f.write("]\n")
75
76 f.write("""elif compat_platform.startswith("win"):\n mapping_list = [\n""")
77 for win_line in win_lines:
78 f.write(f'"{win_line}",\n')
79 f.write("]\n")
80
81 f.write("else:\n mapping_list = []\n")
82
83 print("Saved 'pyglet/input/controller_db.py'")