KeymapBeautifier.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. current_pretty_output_layer = self.pretty_output_layer(layer.name[0].value, padded_key_symbols)
  149. # strip trailing spaces from padding
  150. layer_output.append(re.sub(r" +\n", "\n", current_pretty_output_layer))
  151. return [self.KEYMAP_START + "\n",
  152. self.KEY_CHART + "\n",
  153. ",\n\n".join(layer_output) + "\n",
  154. self.KEYMAP_END + "\n"]
  155. def get_row_group(self, row):
  156. for low, high in self.KEY_ROW_GROUPS[self.output_layout]:
  157. if low <= row <= high:
  158. return (low, high)
  159. raise Exception("Cannot find row groups in KEY_ROW_GROUPS")
  160. def calculate_column_max_widths(self, key_symbols):
  161. # calculate the max width for each column
  162. self.column_max_widths = {}
  163. for i in range(len(key_symbols)):
  164. row_index, column_index = self.current_converted_KEY_COORDINATES[i]
  165. row_group = self.get_row_group(row_index)
  166. if (row_group, column_index) in self.column_max_widths:
  167. self.column_max_widths[(row_group, column_index)] = max(self.column_max_widths[(row_group, column_index)], len(key_symbols[i]))
  168. else:
  169. self.column_max_widths[(row_group, column_index)] = len(key_symbols[i])
  170. def pad_key_symbols(self, key_symbols, input_layout, just='left'):
  171. self.calculate_column_max_widths(key_symbols)
  172. padded_key_symbols = []
  173. # pad each key symbol
  174. for i in range(len(key_symbols)):
  175. key = key_symbols[i]
  176. # look up column coordinate to determine number of spaces to pad
  177. row_index, column_index = self.current_converted_KEY_COORDINATES[i]
  178. row_group = self.get_row_group(row_index)
  179. if just == 'left':
  180. padded_key_symbols.append(key.ljust(self.column_max_widths[(row_group, column_index)]))
  181. else:
  182. padded_key_symbols.append(key.rjust(self.column_max_widths[(row_group, column_index)]))
  183. return padded_key_symbols
  184. layer_keys_pointer = 0
  185. layer_keys = None
  186. def grab_next_n_columns(self, n_columns, input_layout, layer_keys = None, from_beginning = False):
  187. if layer_keys:
  188. self.layer_keys = layer_keys
  189. if from_beginning:
  190. self.layer_keys_pointer = 0
  191. begin = self.layer_keys_pointer
  192. end = begin + n_columns
  193. return self.layer_keys[self.layer_keys_pointer-n_keys:self.layer_keys_pointer]
  194. key_coordinates_counter = 0
  195. def get_padded_line(self, source_keys, key_from, key_to, just="left"):
  196. if just == "right":
  197. keys = [k.strip().rjust(len(k)) for k in source_keys[key_from:key_to]]
  198. else:
  199. keys = [k for k in source_keys[key_from:key_to]]
  200. from_row, from_column = self.KEY_COORDINATES[self.output_layout][self.key_coordinates_counter]
  201. row_group = self.get_row_group(from_row)
  202. self.key_coordinates_counter += key_to - key_from
  203. columns_before_key_from = sorted([col for row, col in self.KEY_COORDINATES[self.output_layout] if row == from_row and col < from_column])
  204. # figure out which columns in this row needs padding; only pad empty columns to the right of an existing column
  205. columns_to_pad = { c: True for c in range(from_column) }
  206. if columns_before_key_from:
  207. for c in range(max(columns_before_key_from)+1):
  208. columns_to_pad[c] = False
  209. # for rows with fewer columns that don't start with column 0, we need to insert leading spaces
  210. spaces = 0
  211. for c, v in columns_to_pad.items():
  212. if not v:
  213. continue
  214. if (row_group,c) in self.column_max_widths:
  215. spaces += self.column_max_widths[(row_group,c)] + len(", ")
  216. else:
  217. spaces += 0
  218. return " " * spaces + ", ".join(keys) + ","
  219. def pretty_output_layer(self, layer, keys):
  220. self.key_coordinates_counter = 0
  221. if self.output_layout == "LAYOUT_ergodox":
  222. formatted_key_symbols = """
  223. // left hand
  224. {}
  225. {}
  226. {}
  227. {}
  228. {}
  229. // left thumb
  230. {}
  231. {}
  232. {}
  233. // right hand
  234. {}
  235. {}
  236. {}
  237. {}
  238. {}
  239. // right thumb
  240. {}
  241. {}
  242. {}
  243. """.format(
  244. # left hand
  245. self.get_padded_line(keys, 0, 7, just="left"),
  246. self.get_padded_line(keys, 7, 14, just="left"),
  247. self.get_padded_line(keys, 14, 20, just="left"),
  248. self.get_padded_line(keys, 20, 27, just="left"),
  249. self.get_padded_line(keys, 27, 32, just="left"),
  250. # left thumb
  251. self.get_padded_line(keys, 32, 34, just="left"),
  252. self.get_padded_line(keys, 34, 35, just="left"),
  253. self.get_padded_line(keys, 35, 38, just="left"),
  254. # right hand
  255. self.get_padded_line(keys, 38, 45, just="left"),
  256. self.get_padded_line(keys, 45, 52, just="left"),
  257. self.get_padded_line(keys, 52, 58, just="left"),
  258. self.get_padded_line(keys, 58, 65, just="left"),
  259. self.get_padded_line(keys, 65, 70, just="left"),
  260. # right thumb
  261. self.get_padded_line(keys, 70, 72, just="left"),
  262. self.get_padded_line(keys, 72, 73, just="left"),
  263. self.get_padded_line(keys, 73, 76, just="left"),
  264. )
  265. elif self.output_layout == "LAYOUT_ergodox_pretty":
  266. left_half_justification = "right" if self.justify_toward_center else "left"
  267. formatted_key_symbols = """
  268. {} {}
  269. {} {}
  270. {} {}
  271. {} {}
  272. {} {}
  273. {} {}
  274. {} {}
  275. {} {}
  276. """.format(
  277. self.get_padded_line(keys, 0, 7, just=left_half_justification), self.get_padded_line(keys, 38, 45, just="left"),
  278. self.get_padded_line(keys, 7, 14, just=left_half_justification), self.get_padded_line(keys, 45, 52, just="left"),
  279. self.get_padded_line(keys, 14, 20, just=left_half_justification), self.get_padded_line(keys, 52, 58, just="left"),
  280. self.get_padded_line(keys, 20, 27, just=left_half_justification), self.get_padded_line(keys, 58, 65, just="left"),
  281. self.get_padded_line(keys, 27, 32, just=left_half_justification), self.get_padded_line(keys, 65, 70, just="left"),
  282. self.get_padded_line(keys, 32, 34, just=left_half_justification), self.get_padded_line(keys, 70, 72, just="left"),
  283. self.get_padded_line(keys, 34, 35, just=left_half_justification), self.get_padded_line(keys, 72, 73, just="left"),
  284. self.get_padded_line(keys, 35, 38, just=left_half_justification), self.get_padded_line(keys, 73, 76, just="left"),
  285. )
  286. else:
  287. formatted_key_symbols = ""
  288. # rid of the trailing comma
  289. formatted_key_symbols = formatted_key_symbols[0:len(formatted_key_symbols)-2] + "\n"
  290. s = "[{}] = {}({})".format(layer, self.output_layout, formatted_key_symbols)
  291. return s
  292. # helper functions for pycparser
  293. def parser(self, src):
  294. src = self.comment_remover(src)
  295. return pycparser.CParser().parse(src)
  296. def comment_remover(self, text):
  297. # remove comments since pycparser cannot deal with them
  298. # credit: https://stackoverflow.com/a/241506
  299. def replacer(match):
  300. s = match.group(0)
  301. if s.startswith('/'):
  302. return " " # note: a space and not an empty string
  303. else:
  304. return s
  305. pattern = re.compile(
  306. r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
  307. re.DOTALL | re.MULTILINE
  308. )
  309. return re.sub(pattern, replacer, text)
  310. def function_expr(self, f):
  311. name = f.name.name
  312. args = []
  313. for arg in f.args.exprs:
  314. if type(arg) is pycparser.c_ast.Constant:
  315. args.append(arg.value)
  316. elif type(arg) is pycparser.c_ast.ID:
  317. args.append(arg.name)
  318. return "{}({})".format(name, ",".join(args))
  319. def key_expr(self, raw):
  320. if type(raw) is pycparser.c_ast.ID:
  321. if raw.name in self.KEY_ALIASES:
  322. return self.KEY_ALIASES[raw.name]
  323. return raw.name
  324. elif type(raw) is pycparser.c_ast.FuncCall:
  325. return self.function_expr(raw)
  326. def layer_expr(self, layer):
  327. transformed = [self.key_expr(k) for k in layer.expr.args.exprs]
  328. return transformed
  329. if __name__ == "__main__":
  330. parser = argparse.ArgumentParser(description="Beautify keymap.c downloaded from ErgoDox-Ez Configurator for easier customization.")
  331. parser.add_argument("input_filename", help="input file: c source code file that has the layer keymaps")
  332. parser.add_argument("-o", "--output-filename", help="output file: beautified c filename. If not given, output to STDOUT.")
  333. parser.add_argument("-p", "--pretty-output-layout", action="store_true", help="use LAYOUT_ergodox_pretty for output instead of LAYOUT_ergodox")
  334. 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.")
  335. args = parser.parse_args()
  336. if args.pretty_output_layout:
  337. output_layout="LAYOUT_ergodox_pretty"
  338. else:
  339. output_layout="LAYOUT_ergodox"
  340. with open(args.input_filename) as f:
  341. source_code = f.read()
  342. result = KeymapBeautifier(source_code, output_layout=output_layout, justify_toward_center=args.justify_toward_center).output
  343. if args.output_filename:
  344. with open(args.output_filename, "w") as f:
  345. f.write(result)
  346. else:
  347. print(result)