diff options
Diffstat (limited to 'lib/python/qmk/keymap.py')
| -rw-r--r-- | lib/python/qmk/keymap.py | 280 |
1 files changed, 251 insertions, 29 deletions
diff --git a/lib/python/qmk/keymap.py b/lib/python/qmk/keymap.py index 78510a8a7..2b271fe80 100644 --- a/lib/python/qmk/keymap.py +++ b/lib/python/qmk/keymap.py | |||
| @@ -1,11 +1,18 @@ | |||
| 1 | """Functions that help you work with QMK keymaps. | 1 | """Functions that help you work with QMK keymaps. |
| 2 | """ | 2 | """ |
| 3 | from pathlib import Path | 3 | from pathlib import Path |
| 4 | import json | ||
| 5 | import subprocess | ||
| 6 | |||
| 7 | from pygments.lexers.c_cpp import CLexer | ||
| 8 | from pygments.token import Token | ||
| 9 | from pygments import lex | ||
| 4 | 10 | ||
| 5 | from milc import cli | 11 | from milc import cli |
| 6 | 12 | ||
| 7 | from qmk.keyboard import rules_mk | 13 | from qmk.keyboard import rules_mk |
| 8 | import qmk.path | 14 | import qmk.path |
| 15 | import qmk.commands | ||
| 9 | 16 | ||
| 10 | # The `keymap.c` template to use when a keyboard doesn't have its own | 17 | # The `keymap.c` template to use when a keyboard doesn't have its own |
| 11 | DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H | 18 | DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H |
| @@ -22,22 +29,35 @@ __KEYMAP_GOES_HERE__ | |||
| 22 | """ | 29 | """ |
| 23 | 30 | ||
| 24 | 31 | ||
| 25 | def template(keyboard): | 32 | def template(keyboard, type='c'): |
| 26 | """Returns the `keymap.c` template for a keyboard. | 33 | """Returns the `keymap.c` or `keymap.json` template for a keyboard. |
| 27 | 34 | ||
| 28 | If a template exists in `keyboards/<keyboard>/templates/keymap.c` that | 35 | If a template exists in `keyboards/<keyboard>/templates/keymap.c` that |
| 29 | text will be used instead of `DEFAULT_KEYMAP_C`. | 36 | text will be used instead of `DEFAULT_KEYMAP_C`. |
| 30 | 37 | ||
| 38 | If a template exists in `keyboards/<keyboard>/templates/keymap.json` that | ||
| 39 | text will be used instead of an empty dictionary. | ||
| 40 | |||
| 31 | Args: | 41 | Args: |
| 32 | keyboard | 42 | keyboard |
| 33 | The keyboard to return a template for. | 43 | The keyboard to return a template for. |
| 34 | """ | ||
| 35 | template_file = Path('keyboards/%s/templates/keymap.c' % keyboard) | ||
| 36 | 44 | ||
| 37 | if template_file.exists(): | 45 | type |
| 38 | return template_file.read_text() | 46 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` |
| 47 | """ | ||
| 48 | if type == 'json': | ||
| 49 | template_file = Path('keyboards/%s/templates/keymap.json' % keyboard) | ||
| 50 | template = {'keyboard': keyboard} | ||
| 51 | if template_file.exists(): | ||
| 52 | template.update(json.loads(template_file.read_text())) | ||
| 53 | else: | ||
| 54 | template_file = Path('keyboards/%s/templates/keymap.c' % keyboard) | ||
| 55 | if template_file.exists(): | ||
| 56 | template = template_file.read_text() | ||
| 57 | else: | ||
| 58 | template = DEFAULT_KEYMAP_C | ||
| 39 | 59 | ||
| 40 | return DEFAULT_KEYMAP_C | 60 | return template |
| 41 | 61 | ||
| 42 | 62 | ||
| 43 | def _strip_any(keycode): | 63 | def _strip_any(keycode): |
| @@ -57,8 +77,8 @@ def is_keymap_dir(keymap): | |||
| 57 | return True | 77 | return True |
| 58 | 78 | ||
| 59 | 79 | ||
| 60 | def generate(keyboard, layout, layers): | 80 | def generate(keyboard, layout, layers, type='c', keymap=None): |
| 61 | """Returns a keymap.c for the specified keyboard, layout, and layers. | 81 | """Returns a `keymap.c` or `keymap.json` for the specified keyboard, layout, and layers. |
| 62 | 82 | ||
| 63 | Args: | 83 | Args: |
| 64 | keyboard | 84 | keyboard |
| @@ -69,24 +89,30 @@ def generate(keyboard, layout, layers): | |||
| 69 | 89 | ||
| 70 | layers | 90 | layers |
| 71 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. | 91 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. |
| 72 | """ | ||
| 73 | layer_txt = [] | ||
| 74 | |||
| 75 | for layer_num, layer in enumerate(layers): | ||
| 76 | if layer_num != 0: | ||
| 77 | layer_txt[-1] = layer_txt[-1] + ',' | ||
| 78 | 92 | ||
| 79 | layer = map(_strip_any, layer) | 93 | type |
| 80 | layer_keys = ', '.join(layer) | 94 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` |
| 81 | layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys)) | 95 | """ |
| 82 | 96 | new_keymap = template(keyboard, type) | |
| 83 | keymap = '\n'.join(layer_txt) | 97 | if type == 'json': |
| 84 | keymap_c = template(keyboard) | 98 | new_keymap['keymap'] = keymap |
| 85 | 99 | new_keymap['layout'] = layout | |
| 86 | return keymap_c.replace('__KEYMAP_GOES_HERE__', keymap) | 100 | new_keymap['layers'] = layers |
| 87 | 101 | else: | |
| 88 | 102 | layer_txt = [] | |
| 89 | def write(keyboard, keymap, layout, layers): | 103 | for layer_num, layer in enumerate(layers): |
| 104 | if layer_num != 0: | ||
| 105 | layer_txt[-1] = layer_txt[-1] + ',' | ||
| 106 | layer_keys = ', '.join(layer) | ||
| 107 | layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys)) | ||
| 108 | |||
| 109 | keymap = '\n'.join(layer_txt) | ||
| 110 | new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap) | ||
| 111 | |||
| 112 | return new_keymap | ||
| 113 | |||
| 114 | |||
| 115 | def write(keyboard, keymap, layout, layers, type='c'): | ||
| 90 | """Generate the `keymap.c` and write it to disk. | 116 | """Generate the `keymap.c` and write it to disk. |
| 91 | 117 | ||
| 92 | Returns the filename written to. | 118 | Returns the filename written to. |
| @@ -103,12 +129,19 @@ def write(keyboard, keymap, layout, layers): | |||
| 103 | 129 | ||
| 104 | layers | 130 | layers |
| 105 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. | 131 | An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode. |
| 132 | |||
| 133 | type | ||
| 134 | 'json' for `keymap.json` and 'c' (or anything else) for `keymap.c` | ||
| 106 | """ | 135 | """ |
| 107 | keymap_c = generate(keyboard, layout, layers) | 136 | keymap_content = generate(keyboard, layout, layers, type) |
| 108 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.c' | 137 | if type == 'json': |
| 138 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.json' | ||
| 139 | keymap_content = json.dumps(keymap_content) | ||
| 140 | else: | ||
| 141 | keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.c' | ||
| 109 | 142 | ||
| 110 | keymap_file.parent.mkdir(parents=True, exist_ok=True) | 143 | keymap_file.parent.mkdir(parents=True, exist_ok=True) |
| 111 | keymap_file.write_text(keymap_c) | 144 | keymap_file.write_text(keymap_content) |
| 112 | 145 | ||
| 113 | cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_file) | 146 | cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_file) |
| 114 | 147 | ||
| @@ -188,3 +221,192 @@ def list_keymaps(keyboard): | |||
| 188 | names = names.union([keymap.name for keymap in cl_path.iterdir() if is_keymap_dir(keymap)]) | 221 | names = names.union([keymap.name for keymap in cl_path.iterdir() if is_keymap_dir(keymap)]) |
| 189 | 222 | ||
| 190 | return sorted(names) | 223 | return sorted(names) |
| 224 | |||
| 225 | |||
| 226 | def _c_preprocess(path): | ||
| 227 | """ Run a file through the C pre-processor | ||
| 228 | |||
| 229 | Args: | ||
| 230 | path: path of the keymap.c file | ||
| 231 | |||
| 232 | Returns: | ||
| 233 | the stdout of the pre-processor | ||
| 234 | """ | ||
| 235 | pre_processed_keymap = qmk.commands.run(['cpp', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) | ||
| 236 | return pre_processed_keymap.stdout | ||
| 237 | |||
| 238 | |||
| 239 | def _get_layers(keymap): # noqa C901 : until someone has a good idea how to simplify/split up this code | ||
| 240 | """ Find the layers in a keymap.c file. | ||
| 241 | |||
| 242 | Args: | ||
| 243 | keymap: the content of the keymap.c file | ||
| 244 | |||
| 245 | Returns: | ||
| 246 | a dictionary containing the parsed keymap | ||
| 247 | """ | ||
| 248 | layers = list() | ||
| 249 | opening_braces = '({[' | ||
| 250 | closing_braces = ')}]' | ||
| 251 | keymap_certainty = brace_depth = 0 | ||
| 252 | is_keymap = is_layer = is_adv_kc = False | ||
| 253 | layer = dict(name=False, layout=False, keycodes=list()) | ||
| 254 | for line in lex(keymap, CLexer()): | ||
| 255 | if line[0] is Token.Name: | ||
| 256 | if is_keymap: | ||
| 257 | # If we are inside the keymap array | ||
| 258 | # we know the keymap's name and the layout macro will come, | ||
| 259 | # followed by the keycodes | ||
| 260 | if not layer['name']: | ||
| 261 | if line[1].startswith('LAYOUT') or line[1].startswith('KEYMAP'): | ||
| 262 | # This can happen if the keymap array only has one layer, | ||
| 263 | # for macropads and such | ||
| 264 | layer['name'] = '0' | ||
| 265 | layer['layout'] = line[1] | ||
| 266 | else: | ||
| 267 | layer['name'] = line[1] | ||
| 268 | elif not layer['layout']: | ||
| 269 | layer['layout'] = line[1] | ||
| 270 | elif is_layer: | ||
| 271 | # If we are inside a layout macro, | ||
| 272 | # collect all keycodes | ||
| 273 | if line[1] == '_______': | ||
| 274 | kc = 'KC_TRNS' | ||
| 275 | elif line[1] == 'XXXXXXX': | ||
| 276 | kc = 'KC_NO' | ||
| 277 | else: | ||
| 278 | kc = line[1] | ||
| 279 | if is_adv_kc: | ||
| 280 | # If we are inside an advanced keycode | ||
| 281 | # collect everything and hope the user | ||
| 282 | # knew what he/she was doing | ||
| 283 | layer['keycodes'][-1] += kc | ||
| 284 | else: | ||
| 285 | layer['keycodes'].append(kc) | ||
| 286 | |||
| 287 | # The keymaps array's signature: | ||
| 288 | # const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] | ||
| 289 | # | ||
| 290 | # Only if we've found all 6 keywords in this specific order | ||
| 291 | # can we know for sure that we are inside the keymaps array | ||
| 292 | elif line[1] == 'PROGMEM' and keymap_certainty == 2: | ||
| 293 | keymap_certainty = 3 | ||
| 294 | elif line[1] == 'keymaps' and keymap_certainty == 3: | ||
| 295 | keymap_certainty = 4 | ||
| 296 | elif line[1] == 'MATRIX_ROWS' and keymap_certainty == 4: | ||
| 297 | keymap_certainty = 5 | ||
| 298 | elif line[1] == 'MATRIX_COLS' and keymap_certainty == 5: | ||
| 299 | keymap_certainty = 6 | ||
| 300 | elif line[0] is Token.Keyword: | ||
| 301 | if line[1] == 'const' and keymap_certainty == 0: | ||
| 302 | keymap_certainty = 1 | ||
| 303 | elif line[0] is Token.Keyword.Type: | ||
| 304 | if line[1] == 'uint16_t' and keymap_certainty == 1: | ||
| 305 | keymap_certainty = 2 | ||
| 306 | elif line[0] is Token.Punctuation: | ||
| 307 | if line[1] in opening_braces: | ||
| 308 | brace_depth += 1 | ||
| 309 | if is_keymap: | ||
| 310 | if is_layer: | ||
| 311 | # We found the beginning of a non-basic keycode | ||
| 312 | is_adv_kc = True | ||
| 313 | layer['keycodes'][-1] += line[1] | ||
| 314 | elif line[1] == '(' and brace_depth == 2: | ||
| 315 | # We found the beginning of a layer | ||
| 316 | is_layer = True | ||
| 317 | elif line[1] == '{' and keymap_certainty == 6: | ||
| 318 | # We found the beginning of the keymaps array | ||
| 319 | is_keymap = True | ||
| 320 | elif line[1] in closing_braces: | ||
| 321 | brace_depth -= 1 | ||
| 322 | if is_keymap: | ||
| 323 | if is_adv_kc: | ||
| 324 | layer['keycodes'][-1] += line[1] | ||
| 325 | if brace_depth == 2: | ||
| 326 | # We found the end of a non-basic keycode | ||
| 327 | is_adv_kc = False | ||
| 328 | elif line[1] == ')' and brace_depth == 1: | ||
| 329 | # We found the end of a layer | ||
| 330 | is_layer = False | ||
| 331 | layers.append(layer) | ||
| 332 | layer = dict(name=False, layout=False, keycodes=list()) | ||
| 333 | elif line[1] == '}' and brace_depth == 0: | ||
| 334 | # We found the end of the keymaps array | ||
| 335 | is_keymap = False | ||
| 336 | keymap_certainty = 0 | ||
| 337 | elif is_adv_kc: | ||
| 338 | # Advanced keycodes can contain other punctuation | ||
| 339 | # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC) | ||
| 340 | layer['keycodes'][-1] += line[1] | ||
| 341 | |||
| 342 | elif line[0] is Token.Literal.Number.Integer and is_keymap and not is_adv_kc: | ||
| 343 | # If the pre-processor finds the 'meaning' of the layer names, | ||
| 344 | # they will be numbers | ||
| 345 | if not layer['name']: | ||
| 346 | layer['name'] = line[1] | ||
| 347 | |||
| 348 | else: | ||
| 349 | # We only care about | ||
| 350 | # operators and such if we | ||
| 351 | # are inside an advanced keycode | ||
| 352 | # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC) | ||
| 353 | if is_adv_kc: | ||
| 354 | layer['keycodes'][-1] += line[1] | ||
| 355 | |||
| 356 | return layers | ||
| 357 | |||
| 358 | |||
| 359 | def parse_keymap_c(keymap_file, use_cpp=True): | ||
| 360 | """ Parse a keymap.c file. | ||
| 361 | |||
| 362 | Currently only cares about the keymaps array. | ||
| 363 | |||
| 364 | Args: | ||
| 365 | keymap_file: path of the keymap.c file | ||
| 366 | |||
| 367 | use_cpp: if True, pre-process the file with the C pre-processor | ||
| 368 | |||
| 369 | Returns: | ||
| 370 | a dictionary containing the parsed keymap | ||
| 371 | """ | ||
| 372 | if use_cpp: | ||
| 373 | keymap_file = _c_preprocess(keymap_file) | ||
| 374 | else: | ||
| 375 | keymap_file = keymap_file.read_text() | ||
| 376 | |||
| 377 | keymap = dict() | ||
| 378 | keymap['layers'] = _get_layers(keymap_file) | ||
| 379 | return keymap | ||
| 380 | |||
| 381 | |||
| 382 | def c2json(keyboard, keymap, keymap_file, use_cpp=True): | ||
| 383 | """ Convert keymap.c to keymap.json | ||
| 384 | |||
| 385 | Args: | ||
| 386 | keyboard: The name of the keyboard | ||
| 387 | |||
| 388 | keymap: The name of the keymap | ||
| 389 | |||
| 390 | layout: The LAYOUT macro this keymap uses. | ||
| 391 | |||
| 392 | keymap_file: path of the keymap.c file | ||
| 393 | |||
| 394 | use_cpp: if True, pre-process the file with the C pre-processor | ||
| 395 | |||
| 396 | Returns: | ||
| 397 | a dictionary in keymap.json format | ||
| 398 | """ | ||
| 399 | keymap_json = parse_keymap_c(keymap_file, use_cpp) | ||
| 400 | |||
| 401 | dirty_layers = keymap_json.pop('layers', None) | ||
| 402 | keymap_json['layers'] = list() | ||
| 403 | for layer in dirty_layers: | ||
| 404 | layer.pop('name') | ||
| 405 | layout = layer.pop('layout') | ||
| 406 | if not keymap_json.get('layout', False): | ||
| 407 | keymap_json['layout'] = layout | ||
| 408 | keymap_json['layers'].append(layer.pop('keycodes')) | ||
| 409 | |||
| 410 | keymap_json['keyboard'] = keyboard | ||
| 411 | keymap_json['keymap'] = keymap | ||
| 412 | return keymap_json | ||
