KeymapBeautifier.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #!/usr/bin/env python
  2. import argparse
  3. import pycparser
  4. import re
  5. class KeymapBeautifier:
  6. justify_toward_center = False
  7. filename_in = None
  8. filename_out = None
  9. output_layout = None
  10. output = None
  11. column_max_widths = {}
  12. KEY_ALIASES = {
  13. "KC_TRANSPARENT": "_______",
  14. "KC_TRNS": "_______",
  15. "KC_NO": "XXXXXXX",
  16. }
  17. KEYMAP_START = 'const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {\n'
  18. KEYMAP_END = '};\n'
  19. KEYMAP_START_REPLACEMENT = "const int keymaps[]={\n"
  20. KEY_CHART = """
  21. /*
  22. * ,--------------------------------------------------. ,--------------------------------------------------.
  23. * | 0 | 1 | 2 | 3 | 4 | 5 | 6 | | 38 | 39 | 40 | 41 | 42 | 43 | 44 |
  24. * |--------+------+------+------+------+------+------| |------+------+------+------+------+------+--------|
  25. * | 7 | 8 | 9 | 10 | 11 | 12 | 13 | | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
  26. * |--------+------+------+------+------+------| | | |------+------+------+------+------+--------|
  27. * | 14 | 15 | 16 | 17 | 18 | 19 |------| |------| 52 | 53 | 54 | 55 | 56 | 57 |
  28. * |--------+------+------+------+------+------| 26 | | 58 |------+------+------+------+------+--------|
  29. * | 20 | 21 | 22 | 23 | 24 | 25 | | | | 59 | 60 | 61 | 62 | 63 | 64 |
  30. * `--------+------+------+------+------+-------------' `-------------+------+------+------+------+--------'
  31. * | 27 | 28 | 29 | 30 | 31 | | 65 | 66 | 67 | 68 | 69 |
  32. * `----------------------------------' `----------------------------------'
  33. * ,-------------. ,-------------.
  34. * | 32 | 33 | | 70 | 71 |
  35. * ,------+------+------| |------+------+------.
  36. * | | | 34 | | 72 | | |
  37. * | 35 | 36 |------| |------| 74 | 75 |
  38. * | | | 37 | | 73 | | |
  39. * `--------------------' `--------------------'
  40. */
  41. """
  42. KEY_COORDINATES = {
  43. 'LAYOUT_ergodox': [
  44. # left hand
  45. (0,0), (0,1), (0,2), (0,3), (0,4), (0,5), (0,6),
  46. (1,0), (1,1), (1,2), (1,3), (1,4), (1,5), (1,6),
  47. (2,0), (2,1), (2,2), (2,3), (2,4), (2,5),
  48. (3,0), (3,1), (3,2), (3,3), (3,4), (3,5), (3,6),
  49. (4,0), (4,1), (4,2), (4,3), (4,4),
  50. # left thumb
  51. (5,5), (5,6),
  52. (6,6),
  53. (7,4), (7,5), (7,6),
  54. # right hand
  55. (8,0), (8,1), (8,2), (8,3), (8,4), (8,5), (8,6),
  56. (9,0), (9,1), (9,2), (9,3), (9,4), (9,5), (9,6),
  57. (10,1), (10,2), (10,3), (10,4), (10,5), (10,6),
  58. (11,0), (11,1), (11,2), (11,3), (11,4), (11,5), (11,6),
  59. (12,2), (12,3), (12,4), (12,5), (12,6),
  60. # right thumb
  61. (13,0), (13,1),
  62. (14,0),
  63. (15,0), (15,1), (15,2)
  64. ],
  65. 'LAYOUT_ergodox_pretty': [
  66. # left hand and right hand
  67. (0,0), (0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7), (0,8), (0,9), (0,10), (0,11), (0,12), (0,13),
  68. (1,0), (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9), (1,10), (1,11), (1,12), (1,13),
  69. (2,0), (2,1), (2,2), (2,3), (2,4), (2,5), (2,8), (2,9), (2,10), (2,11), (2,12), (2,13),
  70. (3,0), (3,1), (3,2), (3,3), (3,4), (3,5), (3,6), (3,7), (3,8), (3,9), (3,10), (3,11), (3,12), (3,13),
  71. (4,0), (4,1), (4,2), (4,3), (4,4), (4,9), (4,10), (4,11), (4,12), (4,13),
  72. # left thumb and right thumb
  73. (5,5), (5,6), (5,7), (5,8),
  74. (6,6), (6,7),
  75. (7,4), (7,5), (7,6), (7,7), (7,8), (7,9)
  76. ],
  77. }
  78. current_converted_KEY_COORDINATES = []
  79. # each column is aligned within each group (tuples of row indexes are inclusive)
  80. KEY_ROW_GROUPS = {
  81. 'LAYOUT_ergodox': [(0,4),(5,7),(8,12),(13,15)],
  82. 'LAYOUT_ergodox_pretty': [(0,7)],
  83. #'LAYOUT_ergodox_pretty': [(0,5),(6,7)],
  84. #'LAYOUT_ergodox_pretty': [(0,3),(4,4),(5,7)],
  85. #'LAYOUT_ergodox_pretty': [(0,4),(5,7)],
  86. }
  87. INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox = [
  88. 0, 1, 2, 3, 4, 5, 6, 38,39,40,41,42,43,44,
  89. 7, 8, 9,10,11,12,13, 45,46,47,48,49,50,51,
  90. 14,15,16,17,18,19, 52,53,54,55,56,57,
  91. 20,21,22,23,24,25,26, 58,59,60,61,62,63,64,
  92. 27,28,29,30,31, 65,66,67,68,69,
  93. 32,33, 70,71,
  94. 34, 72,
  95. 35,36,37, 73,74,75,
  96. ]
  97. def index_conversion_map_reversed(self, conversion_map):
  98. return [conversion_map.index(i) for i in range(len(conversion_map))]
  99. def __init__(self, source_code = "", output_layout="LAYOUT_ergodox", justify_toward_center = False):
  100. self.output_layout = output_layout
  101. self.justify_toward_center = justify_toward_center
  102. # determine the conversion map
  103. #if input_layout == self.output_layout:
  104. # conversion_map = [i for i in range(len(self.INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox))]
  105. #conversion_map = self.INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox
  106. if self.output_layout == "LAYOUT_ergodox_pretty":
  107. index_conversion_map = self.index_conversion_map_reversed(self.INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox)
  108. else:
  109. index_conversion_map = list(range(len(self.INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox)))
  110. self.current_converted_KEY_COORDINATES = [
  111. self.KEY_COORDINATES[self.output_layout][index_conversion_map[i]]
  112. for i in range(len(self.KEY_COORDINATES[self.output_layout]))
  113. ]
  114. self.output = self.beautify_source_code(source_code)
  115. def beautify_source_code(self, source_code):
  116. # to keep it simple for the parser, we only use the parser to parse the key definition part
  117. src = {
  118. "before": [],
  119. "keys": [],
  120. "after": [],
  121. }
  122. current_section = "before"
  123. for line in source_code.splitlines(True):
  124. if current_section == 'before' and line == self.KEYMAP_START:
  125. src[current_section].append("\n")
  126. current_section = 'keys'
  127. src[current_section].append(self.KEYMAP_START_REPLACEMENT)
  128. continue
  129. elif current_section == 'keys' and line == self.KEYMAP_END:
  130. src[current_section].append(self.KEYMAP_END)
  131. current_section = 'after'
  132. continue
  133. src[current_section].append(line)
  134. output_lines = src['before'] + self.beautify_keys_section("".join(src['keys'])) + src['after']
  135. return "".join(output_lines)
  136. def beautify_keys_section(self, src):
  137. parsed = self.parser(src)
  138. layer_output = []
  139. keymap = parsed.children()[0]
  140. layers = keymap[1]
  141. for layer in layers.init.exprs:
  142. input_layout = layer.expr.name.name
  143. key_symbols = self.layer_expr(layer)
  144. # re-order keys from input_layout to regular layout
  145. if input_layout == "LAYOUT_ergodox_pretty":
  146. key_symbols = [key_symbols[i] for i in self.index_conversion_map_reversed(self.INDEX_CONVERSTION_LAYOUT_ergodox_pretty_to_LAYOUT_ergodox)]
  147. padded_key_symbols = self.pad_key_symbols(key_symbols, input_layout)
  148. layer_identifier = None
  149. if hasattr(layer.name[0], "value"):
  150. layer_identifier = layer.name[0].value
  151. elif hasattr(layer.name[0], "name"):
  152. layer_identifier = layer.name[0].name
  153. else:
  154. raise AttributeError("Layer is missing both index and name (e.g., [BASE] = LAYOUT_ergodox(...))")
  155. current_pretty_output_layer = self.pretty_output_layer(layer_identifier, padded_key_symbols)
  156. # strip trailing spaces from padding
  157. layer_output.append(re.sub(r" +\n", "\n", current_pretty_output_layer))
  158. return [self.KEYMAP_START + "\n",
  159. self.KEY_CHART + "\n",
  160. ",\n\n".join(layer_output) + "\n",
  161. self.KEYMAP_END + "\n"]
  162. def get_row_group(self, row):
  163. for low, high in self.KEY_ROW_GROUPS[self.output_layout]:
  164. if low <= row <= high:
  165. return (low, high)
  166. raise Exception("Cannot find row groups in KEY_ROW_GROUPS")
  167. def calculate_column_max_widths(self, key_symbols):
  168. # calculate the max width for each column
  169. self.column_max_widths = {}
  170. for i in range(len(key_symbols)):
  171. row_index, column_index = self.current_converted_KEY_COORDINATES[i]
  172. row_group = self.get_row_group(row_index)
  173. if (row_group, column_index) in self.column_max_widths:
  174. self.column_max_widths[(row_group, column_index)] = max(self.column_max_widths[(row_group, column_index)], len(key_symbols[i]))
  175. else:
  176. self.column_max_widths[(row_group, column_index)] = len(key_symbols[i])
  177. def pad_key_symbols(self, key_symbols, input_layout, just='left'):
  178. self.calculate_column_max_widths(key_symbols)
  179. padded_key_symbols = []
  180. # pad each key symbol
  181. for i in range(len(key_symbols)):
  182. key = key_symbols[i]
  183. # look up column coordinate to determine number of spaces to pad
  184. row_index, column_index = self.current_converted_KEY_COORDINATES[i]
  185. row_group = self.get_row_group(row_index)
  186. if just == 'left':
  187. padded_key_symbols.append(key.ljust(self.column_max_widths[(row_group, column_index)]))
  188. else:
  189. padded_key_symbols.append(key.rjust(self.column_max_widths[(row_group, column_index)]))
  190. return padded_key_symbols
  191. layer_keys_pointer = 0
  192. layer_keys = None
  193. def grab_next_n_columns(self, n_columns, input_layout, layer_keys = None, from_beginning = False):
  194. if layer_keys:
  195. self.layer_keys = layer_keys
  196. if from_beginning:
  197. self.layer_keys_pointer = 0
  198. begin = self.layer_keys_pointer
  199. end = begin + n_columns
  200. return self.layer_keys[self.layer_keys_pointer-n_keys:self.layer_keys_pointer]
  201. key_coordinates_counter = 0
  202. def get_padded_line(self, source_keys, key_from, key_to, just="left"):
  203. if just == "right":
  204. keys = [k.strip().rjust(len(k)) for k in source_keys[key_from:key_to]]
  205. else:
  206. keys = [k for k in source_keys[key_from:key_to]]
  207. from_row, from_column = self.KEY_COORDINATES[self.output_layout][self.key_coordinates_counter]
  208. row_group = self.get_row_group(from_row)
  209. self.key_coordinates_counter += key_to - key_from
  210. columns_before_key_from = sorted([col for row, col in self.KEY_COORDINATES[self.output_layout] if row == from_row and col < from_column])
  211. # figure out which columns in this row needs padding; only pad empty columns to the right of an existing column
  212. columns_to_pad = { c: True for c in range(from_column) }
  213. if columns_before_key_from:
  214. for c in range(max(columns_before_key_from)+1):
  215. columns_to_pad[c] = False
  216. # for rows with fewer columns that don't start with column 0, we need to insert leading spaces
  217. spaces = 0
  218. for c, v in columns_to_pad.items():
  219. if not v:
  220. continue
  221. if (row_group,c) in self.column_max_widths:
  222. spaces += self.column_max_widths[(row_group,c)] + len(", ")
  223. else:
  224. spaces += 0
  225. return " " * spaces + ", ".join(keys) + ","
  226. def pretty_output_layer(self, layer, keys):
  227. self.key_coordinates_counter = 0
  228. if self.output_layout == "LAYOUT_ergodox":
  229. formatted_key_symbols = """
  230. // left hand
  231. {}
  232. {}
  233. {}
  234. {}
  235. {}
  236. // left thumb
  237. {}
  238. {}
  239. {}
  240. // right hand
  241. {}
  242. {}
  243. {}
  244. {}
  245. {}
  246. // right thumb
  247. {}
  248. {}
  249. {}
  250. """.format(
  251. # left hand
  252. self.get_padded_line(keys, 0, 7, just="left"),
  253. self.get_padded_line(keys, 7, 14, just="left"),
  254. self.get_padded_line(keys, 14, 20, just="left"),
  255. self.get_padded_line(keys, 20, 27, just="left"),
  256. self.get_padded_line(keys, 27, 32, just="left"),
  257. # left thumb
  258. self.get_padded_line(keys, 32, 34, just="left"),
  259. self.get_padded_line(keys, 34, 35, just="left"),
  260. self.get_padded_line(keys, 35, 38, just="left"),
  261. # right hand
  262. self.get_padded_line(keys, 38, 45, just="left"),
  263. self.get_padded_line(keys, 45, 52, just="left"),
  264. self.get_padded_line(keys, 52, 58, just="left"),
  265. self.get_padded_line(keys, 58, 65, just="left"),
  266. self.get_padded_line(keys, 65, 70, just="left"),
  267. # right thumb
  268. self.get_padded_line(keys, 70, 72, just="left"),
  269. self.get_padded_line(keys, 72, 73, just="left"),
  270. self.get_padded_line(keys, 73, 76, just="left"),
  271. )
  272. elif self.output_layout == "LAYOUT_ergodox_pretty":
  273. left_half_justification = "right" if self.justify_toward_center else "left"
  274. formatted_key_symbols = """
  275. {} {}
  276. {} {}
  277. {} {}
  278. {} {}
  279. {} {}
  280. {} {}
  281. {} {}
  282. {} {}
  283. """.format(
  284. self.get_padded_line(keys, 0, 7, just=left_half_justification), self.get_padded_line(keys, 38, 45, just="left"),
  285. self.get_padded_line(keys, 7, 14, just=left_half_justification), self.get_padded_line(keys, 45, 52, just="left"),
  286. self.get_padded_line(keys, 14, 20, just=left_half_justification), self.get_padded_line(keys, 52, 58, just="left"),
  287. self.get_padded_line(keys, 20, 27, just=left_half_justification), self.get_padded_line(keys, 58, 65, just="left"),
  288. self.get_padded_line(keys, 27, 32, just=left_half_justification), self.get_padded_line(keys, 65, 70, just="left"),
  289. self.get_padded_line(keys, 32, 34, just=left_half_justification), self.get_padded_line(keys, 70, 72, just="left"),
  290. self.get_padded_line(keys, 34, 35, just=left_half_justification), self.get_padded_line(keys, 72, 73, just="left"),
  291. self.get_padded_line(keys, 35, 38, just=left_half_justification), self.get_padded_line(keys, 73, 76, just="left"),
  292. )
  293. else:
  294. formatted_key_symbols = ""
  295. # rid of the trailing comma
  296. formatted_key_symbols = formatted_key_symbols[0:len(formatted_key_symbols)-2] + "\n"
  297. s = "[{}] = {}({})".format(layer, self.output_layout, formatted_key_symbols)
  298. return s
  299. # helper functions for pycparser
  300. def parser(self, src):
  301. src = self.comment_remover(src)
  302. return pycparser.CParser().parse(src)
  303. def comment_remover(self, text):
  304. # remove comments since pycparser cannot deal with them
  305. # credit: https://stackoverflow.com/a/241506
  306. def replacer(match):
  307. s = match.group(0)
  308. if s.startswith('/'):
  309. return " " # note: a space and not an empty string
  310. else:
  311. return s
  312. pattern = re.compile(
  313. r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
  314. re.DOTALL | re.MULTILINE
  315. )
  316. return re.sub(pattern, replacer, text)
  317. def function_expr(self, f):
  318. name = f.name.name
  319. args = []
  320. for arg in f.args.exprs:
  321. if type(arg) is pycparser.c_ast.Constant:
  322. args.append(arg.value)
  323. elif type(arg) is pycparser.c_ast.ID:
  324. args.append(arg.name)
  325. elif type(arg) is pycparser.c_ast.FuncCall:
  326. args.append(self.function_expr(arg))
  327. return "{}({})".format(name, ",".join(args))
  328. def key_expr(self, raw):
  329. if type(raw) is pycparser.c_ast.ID:
  330. if raw.name in self.KEY_ALIASES:
  331. return self.KEY_ALIASES[raw.name]
  332. return raw.name
  333. elif type(raw) is pycparser.c_ast.FuncCall:
  334. return self.function_expr(raw)
  335. def layer_expr(self, layer):
  336. transformed = [self.key_expr(k) for k in layer.expr.args.exprs]
  337. return transformed
  338. if __name__ == "__main__":
  339. parser = argparse.ArgumentParser(description="Beautify keymap.c downloaded from ErgoDox-Ez Configurator for easier customization.")
  340. parser.add_argument("input_filename", help="input file: c source code file that has the layer keymaps")
  341. parser.add_argument("-o", "--output-filename", help="output file: beautified c filename. If not given, output to STDOUT.")
  342. parser.add_argument("-p", "--pretty-output-layout", action="store_true", help="use LAYOUT_ergodox_pretty for output instead of LAYOUT_ergodox")
  343. parser.add_argument("-c", "--justify-toward-center", action="store_true", help="for LAYOUT_ergodox_pretty, align right for the left half, and align left for the right half. Default is align left for both halves.")
  344. args = parser.parse_args()
  345. if args.pretty_output_layout:
  346. output_layout="LAYOUT_ergodox_pretty"
  347. else:
  348. output_layout="LAYOUT_ergodox"
  349. with open(args.input_filename) as f:
  350. source_code = f.read()
  351. result = KeymapBeautifier(source_code, output_layout=output_layout, justify_toward_center=args.justify_toward_center).output
  352. if args.output_filename:
  353. with open(args.output_filename, "w") as f:
  354. f.write(result)
  355. else:
  356. print(result)