keymap.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. """Functions that help you work with QMK keymaps.
  2. """
  3. import json
  4. import sys
  5. from pathlib import Path
  6. from subprocess import DEVNULL
  7. import argcomplete
  8. from milc import cli
  9. from pygments.lexers.c_cpp import CLexer
  10. from pygments.token import Token
  11. from pygments import lex
  12. import qmk.path
  13. from qmk.keyboard import find_keyboard_from_dir, keyboard_folder
  14. from qmk.errors import CppError
  15. from qmk.info import info_json
  16. # The `keymap.c` template to use when a keyboard doesn't have its own
  17. DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H
  18. __INCLUDES__
  19. /* THIS FILE WAS GENERATED!
  20. *
  21. * This file was generated by qmk json2c. You may or may not want to
  22. * edit it directly.
  23. */
  24. const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
  25. __KEYMAP_GOES_HERE__
  26. };
  27. #if defined(ENCODER_ENABLE) && defined(ENCODER_MAP_ENABLE)
  28. const uint16_t PROGMEM encoder_map[][NUM_ENCODERS][2] = {
  29. __ENCODER_MAP_GOES_HERE__
  30. };
  31. #endif // defined(ENCODER_ENABLE) && defined(ENCODER_MAP_ENABLE)
  32. __MACRO_OUTPUT_GOES_HERE__
  33. """
  34. def _generate_keymap_table(keymap_json):
  35. lines = []
  36. for layer_num, layer in enumerate(keymap_json['layers']):
  37. if layer_num != 0:
  38. lines[-1] = lines[-1] + ','
  39. layer = map(_strip_any, layer)
  40. layer_keys = ', '.join(layer)
  41. lines.append('\t[%s] = %s(%s)' % (layer_num, keymap_json['layout'], layer_keys))
  42. return lines
  43. def _generate_encodermap_table(keymap_json):
  44. lines = []
  45. for layer_num, layer in enumerate(keymap_json['encoders']):
  46. if layer_num != 0:
  47. lines[-1] = lines[-1] + ','
  48. encoder_keycode_txt = ', '.join([f'ENCODER_CCW_CW({_strip_any(e["ccw"])}, {_strip_any(e["cw"])})' for e in layer])
  49. lines.append('\t[%s] = {%s}' % (layer_num, encoder_keycode_txt))
  50. return lines
  51. def _generate_macros_function(keymap_json):
  52. macro_txt = [
  53. 'bool process_record_user(uint16_t keycode, keyrecord_t *record) {',
  54. ' if (record->event.pressed) {',
  55. ' switch (keycode) {',
  56. ]
  57. for i, macro_array in enumerate(keymap_json['macros']):
  58. macro = []
  59. for macro_fragment in macro_array:
  60. if isinstance(macro_fragment, str):
  61. macro_fragment = macro_fragment.replace('\\', '\\\\')
  62. macro_fragment = macro_fragment.replace('\r\n', r'\n')
  63. macro_fragment = macro_fragment.replace('\n', r'\n')
  64. macro_fragment = macro_fragment.replace('\r', r'\n')
  65. macro_fragment = macro_fragment.replace('\t', r'\t')
  66. macro_fragment = macro_fragment.replace('"', r'\"')
  67. macro.append(f'"{macro_fragment}"')
  68. elif isinstance(macro_fragment, dict):
  69. newstring = []
  70. if macro_fragment['action'] == 'delay':
  71. newstring.append(f"SS_DELAY({macro_fragment['duration']})")
  72. elif macro_fragment['action'] == 'beep':
  73. newstring.append(r'"\a"')
  74. elif macro_fragment['action'] == 'tap' and len(macro_fragment['keycodes']) > 1:
  75. last_keycode = macro_fragment['keycodes'].pop()
  76. for keycode in macro_fragment['keycodes']:
  77. newstring.append(f'SS_DOWN(X_{keycode})')
  78. newstring.append(f'SS_TAP(X_{last_keycode})')
  79. for keycode in reversed(macro_fragment['keycodes']):
  80. newstring.append(f'SS_UP(X_{keycode})')
  81. else:
  82. for keycode in macro_fragment['keycodes']:
  83. newstring.append(f"SS_{macro_fragment['action'].upper()}(X_{keycode})")
  84. macro.append(''.join(newstring))
  85. new_macro = "".join(macro)
  86. new_macro = new_macro.replace('""', '')
  87. macro_txt.append(f' case QK_MACRO_{i}:')
  88. macro_txt.append(f' SEND_STRING({new_macro});')
  89. macro_txt.append(' return false;')
  90. macro_txt.append(' }')
  91. macro_txt.append(' }')
  92. macro_txt.append('\n return true;')
  93. macro_txt.append('};')
  94. macro_txt.append('')
  95. return macro_txt
  96. def template_json(keyboard):
  97. """Returns a `keymap.json` template for a keyboard.
  98. If a template exists in `keyboards/<keyboard>/templates/keymap.json` that text will be used instead of an empty dictionary.
  99. Args:
  100. keyboard
  101. The keyboard to return a template for.
  102. """
  103. template_file = Path('keyboards/%s/templates/keymap.json' % keyboard)
  104. template = {'keyboard': keyboard}
  105. if template_file.exists():
  106. template.update(json.load(template_file.open(encoding='utf-8')))
  107. return template
  108. def template_c(keyboard):
  109. """Returns a `keymap.c` template for a keyboard.
  110. If a template exists in `keyboards/<keyboard>/templates/keymap.c` that text will be used instead of an empty dictionary.
  111. Args:
  112. keyboard
  113. The keyboard to return a template for.
  114. """
  115. template_file = Path('keyboards/%s/templates/keymap.c' % keyboard)
  116. if template_file.exists():
  117. template = template_file.read_text(encoding='utf-8')
  118. else:
  119. template = DEFAULT_KEYMAP_C
  120. return template
  121. def _strip_any(keycode):
  122. """Remove ANY() from a keycode.
  123. """
  124. if keycode.startswith('ANY(') and keycode.endswith(')'):
  125. keycode = keycode[4:-1]
  126. return keycode
  127. def find_keymap_from_dir():
  128. """Returns `(keymap_name, source)` for the directory we're currently in.
  129. """
  130. relative_cwd = qmk.path.under_qmk_firmware()
  131. if relative_cwd and len(relative_cwd.parts) > 1:
  132. # If we're in `qmk_firmware/keyboards` and `keymaps` is in our path, try to find the keyboard name.
  133. if relative_cwd.parts[0] == 'keyboards' and 'keymaps' in relative_cwd.parts:
  134. current_path = Path('/'.join(relative_cwd.parts[1:])) # Strip 'keyboards' from the front
  135. if 'keymaps' in current_path.parts and current_path.name != 'keymaps':
  136. while current_path.parent.name != 'keymaps':
  137. current_path = current_path.parent
  138. return current_path.name, 'keymap_directory'
  139. # If we're in `qmk_firmware/layouts` guess the name from the community keymap they're in
  140. elif relative_cwd.parts[0] == 'layouts' and is_keymap_dir(relative_cwd):
  141. return relative_cwd.name, 'layouts_directory'
  142. # If we're in `qmk_firmware/users` guess the name from the userspace they're in
  143. elif relative_cwd.parts[0] == 'users':
  144. # Guess the keymap name based on which userspace they're in
  145. return relative_cwd.parts[1], 'users_directory'
  146. return None, None
  147. def keymap_completer(prefix, action, parser, parsed_args):
  148. """Returns a list of keymaps for tab completion.
  149. """
  150. try:
  151. if parsed_args.keyboard:
  152. return list_keymaps(parsed_args.keyboard)
  153. keyboard = find_keyboard_from_dir()
  154. if keyboard:
  155. return list_keymaps(keyboard)
  156. except Exception as e:
  157. argcomplete.warn(f'Error: {e.__class__.__name__}: {str(e)}')
  158. return []
  159. return []
  160. def is_keymap_dir(keymap, c=True, json=True, additional_files=None):
  161. """Return True if Path object `keymap` has a keymap file inside.
  162. Args:
  163. keymap
  164. A Path() object for the keymap directory you want to check.
  165. c
  166. When true include `keymap.c` keymaps.
  167. json
  168. When true include `keymap.json` keymaps.
  169. additional_files
  170. A sequence of additional filenames to check against to determine if a directory is a keymap. All files must exist for a match to happen. For example, if you want to match a C keymap with both a `config.h` and `rules.mk` file: `is_keymap_dir(keymap_dir, json=False, additional_files=['config.h', 'rules.mk'])`
  171. """
  172. files = []
  173. if c:
  174. files.append('keymap.c')
  175. if json:
  176. files.append('keymap.json')
  177. for file in files:
  178. if (keymap / file).is_file():
  179. if additional_files:
  180. for additional_file in additional_files:
  181. if not (keymap / additional_file).is_file():
  182. return False
  183. return True
  184. def generate_json(keymap, keyboard, layout, layers, macros=None):
  185. """Returns a `keymap.json` for the specified keyboard, layout, and layers.
  186. Args:
  187. keymap
  188. A name for this keymap.
  189. keyboard
  190. The name of the keyboard.
  191. layout
  192. The LAYOUT macro this keymap uses.
  193. layers
  194. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  195. macros
  196. A sequence of strings containing macros to implement for this keyboard.
  197. """
  198. new_keymap = template_json(keyboard)
  199. new_keymap['keymap'] = keymap
  200. new_keymap['layout'] = layout
  201. new_keymap['layers'] = layers
  202. if macros:
  203. new_keymap['macros'] = macros
  204. return new_keymap
  205. def generate_c(keymap_json):
  206. """Returns a `keymap.c`.
  207. `keymap_json` is a dictionary with the following keys:
  208. keyboard
  209. The name of the keyboard
  210. layout
  211. The LAYOUT macro this keymap uses.
  212. layers
  213. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  214. macros
  215. A sequence of strings containing macros to implement for this keyboard.
  216. """
  217. new_keymap = template_c(keymap_json['keyboard'])
  218. layer_txt = _generate_keymap_table(keymap_json)
  219. keymap = '\n'.join(layer_txt)
  220. new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap)
  221. encodermap = ''
  222. if 'encoders' in keymap_json and keymap_json['encoders'] is not None:
  223. encoder_txt = _generate_encodermap_table(keymap_json)
  224. encodermap = '\n'.join(encoder_txt)
  225. new_keymap = new_keymap.replace('__ENCODER_MAP_GOES_HERE__', encodermap)
  226. macros = ''
  227. if 'macros' in keymap_json and keymap_json['macros'] is not None:
  228. macro_txt = _generate_macros_function(keymap_json)
  229. macros = '\n'.join(macro_txt)
  230. new_keymap = new_keymap.replace('__MACRO_OUTPUT_GOES_HERE__', macros)
  231. hostlang = ''
  232. if 'host_language' in keymap_json and keymap_json['host_language'] is not None:
  233. hostlang = f'#include "keymap_{keymap_json["host_language"]}.h"\n#include "sendstring_{keymap_json["host_language"]}.h"\n'
  234. new_keymap = new_keymap.replace('__INCLUDES__', hostlang)
  235. return new_keymap
  236. def write_file(keymap_filename, keymap_content):
  237. keymap_filename.parent.mkdir(parents=True, exist_ok=True)
  238. keymap_filename.write_text(keymap_content)
  239. cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_filename)
  240. return keymap_filename
  241. def write_json(keyboard, keymap, layout, layers, macros=None):
  242. """Generate the `keymap.json` and write it to disk.
  243. Returns the filename written to.
  244. Args:
  245. keyboard
  246. The name of the keyboard
  247. keymap
  248. The name of the keymap
  249. layout
  250. The LAYOUT macro this keymap uses.
  251. layers
  252. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  253. """
  254. keymap_json = generate_json(keyboard, keymap, layout, layers, macros=None)
  255. keymap_content = json.dumps(keymap_json)
  256. keymap_file = qmk.path.keymap(keyboard) / keymap / 'keymap.json'
  257. return write_file(keymap_file, keymap_content)
  258. def write(keymap_json):
  259. """Generate the `keymap.c` and write it to disk.
  260. Returns the filename written to.
  261. `keymap_json` should be a dict with the following keys:
  262. keyboard
  263. The name of the keyboard
  264. keymap
  265. The name of the keymap
  266. layout
  267. The LAYOUT macro this keymap uses.
  268. layers
  269. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  270. macros
  271. A list of macros for this keymap.
  272. """
  273. keymap_content = generate_c(keymap_json)
  274. keymap_file = qmk.path.keymap(keymap_json['keyboard']) / keymap_json['keymap'] / 'keymap.c'
  275. return write_file(keymap_file, keymap_content)
  276. def locate_keymap(keyboard, keymap):
  277. """Returns the path to a keymap for a specific keyboard.
  278. """
  279. if not qmk.path.is_keyboard(keyboard):
  280. raise KeyError('Invalid keyboard: ' + repr(keyboard))
  281. # Check the keyboard folder first, last match wins
  282. checked_dirs = ''
  283. keymap_path = ''
  284. for dir in keyboard_folder(keyboard).split('/'):
  285. if checked_dirs:
  286. checked_dirs = '/'.join((checked_dirs, dir))
  287. else:
  288. checked_dirs = dir
  289. keymap_dir = Path('keyboards') / checked_dirs / 'keymaps'
  290. if (keymap_dir / keymap / 'keymap.c').exists():
  291. keymap_path = keymap_dir / keymap / 'keymap.c'
  292. if (keymap_dir / keymap / 'keymap.json').exists():
  293. keymap_path = keymap_dir / keymap / 'keymap.json'
  294. if keymap_path:
  295. return keymap_path
  296. # Check community layouts as a fallback
  297. info = info_json(keyboard)
  298. for community_parent in Path('layouts').glob('*/'):
  299. for layout in info.get("community_layouts", []):
  300. community_layout = community_parent / layout / keymap
  301. if community_layout.exists():
  302. if (community_layout / 'keymap.json').exists():
  303. return community_layout / 'keymap.json'
  304. if (community_layout / 'keymap.c').exists():
  305. return community_layout / 'keymap.c'
  306. def list_keymaps(keyboard, c=True, json=True, additional_files=None, fullpath=False):
  307. """List the available keymaps for a keyboard.
  308. Args:
  309. keyboard
  310. The keyboards full name with vendor and revision if necessary, example: clueboard/66/rev3
  311. c
  312. When true include `keymap.c` keymaps.
  313. json
  314. When true include `keymap.json` keymaps.
  315. additional_files
  316. A sequence of additional filenames to check against to determine if a directory is a keymap. All files must exist for a match to happen. For example, if you want to match a C keymap with both a `config.h` and `rules.mk` file: `is_keymap_dir(keymap_dir, json=False, additional_files=['config.h', 'rules.mk'])`
  317. fullpath
  318. When set to True the full path of the keymap relative to the `qmk_firmware` root will be provided.
  319. Returns:
  320. a sorted list of valid keymap names.
  321. """
  322. names = set()
  323. keyboards_dir = Path('keyboards')
  324. kb_path = keyboards_dir / keyboard
  325. # walk up the directory tree until keyboards_dir
  326. # and collect all directories' name with keymap.c file in it
  327. while kb_path != keyboards_dir:
  328. keymaps_dir = kb_path / "keymaps"
  329. if keymaps_dir.is_dir():
  330. for keymap in keymaps_dir.iterdir():
  331. if is_keymap_dir(keymap, c, json, additional_files):
  332. keymap = keymap if fullpath else keymap.name
  333. names.add(keymap)
  334. kb_path = kb_path.parent
  335. # Check community layouts as a fallback
  336. info = info_json(keyboard)
  337. for community_parent in Path('layouts').glob('*/'):
  338. for layout in info.get("community_layouts", []):
  339. cl_path = community_parent / layout
  340. if cl_path.is_dir():
  341. for keymap in cl_path.iterdir():
  342. if is_keymap_dir(keymap, c, json, additional_files):
  343. keymap = keymap if fullpath else keymap.name
  344. names.add(keymap)
  345. return sorted(names)
  346. def _c_preprocess(path, stdin=DEVNULL):
  347. """ Run a file through the C pre-processor
  348. Args:
  349. path: path of the keymap.c file (set None to use stdin)
  350. stdin: stdin pipe (e.g. sys.stdin)
  351. Returns:
  352. the stdout of the pre-processor
  353. """
  354. cmd = ['cpp', str(path)] if path else ['cpp']
  355. pre_processed_keymap = cli.run(cmd, stdin=stdin)
  356. if 'fatal error' in pre_processed_keymap.stderr:
  357. for line in pre_processed_keymap.stderr.split('\n'):
  358. if 'fatal error' in line:
  359. raise (CppError(line))
  360. return pre_processed_keymap.stdout
  361. def _get_layers(keymap): # noqa C901 : until someone has a good idea how to simplify/split up this code
  362. """ Find the layers in a keymap.c file.
  363. Args:
  364. keymap: the content of the keymap.c file
  365. Returns:
  366. a dictionary containing the parsed keymap
  367. """
  368. layers = list()
  369. opening_braces = '({['
  370. closing_braces = ')}]'
  371. keymap_certainty = brace_depth = 0
  372. is_keymap = is_layer = is_adv_kc = False
  373. layer = dict(name=False, layout=False, keycodes=list())
  374. for line in lex(keymap, CLexer()):
  375. if line[0] is Token.Name:
  376. if is_keymap:
  377. # If we are inside the keymap array
  378. # we know the keymap's name and the layout macro will come,
  379. # followed by the keycodes
  380. if not layer['name']:
  381. if line[1].startswith('LAYOUT') or line[1].startswith('KEYMAP'):
  382. # This can happen if the keymap array only has one layer,
  383. # for macropads and such
  384. layer['name'] = '0'
  385. layer['layout'] = line[1]
  386. else:
  387. layer['name'] = line[1]
  388. elif not layer['layout']:
  389. layer['layout'] = line[1]
  390. elif is_layer:
  391. # If we are inside a layout macro,
  392. # collect all keycodes
  393. if line[1] == '_______':
  394. kc = 'KC_TRNS'
  395. elif line[1] == 'XXXXXXX':
  396. kc = 'KC_NO'
  397. else:
  398. kc = line[1]
  399. if is_adv_kc:
  400. # If we are inside an advanced keycode
  401. # collect everything and hope the user
  402. # knew what he/she was doing
  403. layer['keycodes'][-1] += kc
  404. else:
  405. layer['keycodes'].append(kc)
  406. # The keymaps array's signature:
  407. # const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS]
  408. #
  409. # Only if we've found all 6 keywords in this specific order
  410. # can we know for sure that we are inside the keymaps array
  411. elif line[1] == 'PROGMEM' and keymap_certainty == 2:
  412. keymap_certainty = 3
  413. elif line[1] == 'keymaps' and keymap_certainty == 3:
  414. keymap_certainty = 4
  415. elif line[1] == 'MATRIX_ROWS' and keymap_certainty == 4:
  416. keymap_certainty = 5
  417. elif line[1] == 'MATRIX_COLS' and keymap_certainty == 5:
  418. keymap_certainty = 6
  419. elif line[0] is Token.Keyword:
  420. if line[1] == 'const' and keymap_certainty == 0:
  421. keymap_certainty = 1
  422. elif line[0] is Token.Keyword.Type:
  423. if line[1] == 'uint16_t' and keymap_certainty == 1:
  424. keymap_certainty = 2
  425. elif line[0] is Token.Punctuation:
  426. if line[1] in opening_braces:
  427. brace_depth += 1
  428. if is_keymap:
  429. if is_layer:
  430. # We found the beginning of a non-basic keycode
  431. is_adv_kc = True
  432. layer['keycodes'][-1] += line[1]
  433. elif line[1] == '(' and brace_depth == 2:
  434. # We found the beginning of a layer
  435. is_layer = True
  436. elif line[1] == '{' and keymap_certainty == 6:
  437. # We found the beginning of the keymaps array
  438. is_keymap = True
  439. elif line[1] in closing_braces:
  440. brace_depth -= 1
  441. if is_keymap:
  442. if is_adv_kc:
  443. layer['keycodes'][-1] += line[1]
  444. if brace_depth == 2:
  445. # We found the end of a non-basic keycode
  446. is_adv_kc = False
  447. elif line[1] == ')' and brace_depth == 1:
  448. # We found the end of a layer
  449. is_layer = False
  450. layers.append(layer)
  451. layer = dict(name=False, layout=False, keycodes=list())
  452. elif line[1] == '}' and brace_depth == 0:
  453. # We found the end of the keymaps array
  454. is_keymap = False
  455. keymap_certainty = 0
  456. elif is_adv_kc:
  457. # Advanced keycodes can contain other punctuation
  458. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  459. layer['keycodes'][-1] += line[1]
  460. elif line[0] is Token.Literal.Number.Integer and is_keymap and not is_adv_kc:
  461. # If the pre-processor finds the 'meaning' of the layer names,
  462. # they will be numbers
  463. if not layer['name']:
  464. layer['name'] = line[1]
  465. else:
  466. # We only care about
  467. # operators and such if we
  468. # are inside an advanced keycode
  469. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  470. if is_adv_kc:
  471. layer['keycodes'][-1] += line[1]
  472. return layers
  473. def parse_keymap_c(keymap_file, use_cpp=True):
  474. """ Parse a keymap.c file.
  475. Currently only cares about the keymaps array.
  476. Args:
  477. keymap_file: path of the keymap.c file (or '-' to use stdin)
  478. use_cpp: if True, pre-process the file with the C pre-processor
  479. Returns:
  480. a dictionary containing the parsed keymap
  481. """
  482. if keymap_file == '-':
  483. if use_cpp:
  484. keymap_file = _c_preprocess(None, sys.stdin)
  485. else:
  486. keymap_file = sys.stdin.read()
  487. else:
  488. if use_cpp:
  489. keymap_file = _c_preprocess(keymap_file)
  490. else:
  491. keymap_file = keymap_file.read_text(encoding='utf-8')
  492. keymap = dict()
  493. keymap['layers'] = _get_layers(keymap_file)
  494. return keymap
  495. def c2json(keyboard, keymap, keymap_file, use_cpp=True):
  496. """ Convert keymap.c to keymap.json
  497. Args:
  498. keyboard: The name of the keyboard
  499. keymap: The name of the keymap
  500. layout: The LAYOUT macro this keymap uses.
  501. keymap_file: path of the keymap.c file
  502. use_cpp: if True, pre-process the file with the C pre-processor
  503. Returns:
  504. a dictionary in keymap.json format
  505. """
  506. keymap_json = parse_keymap_c(keymap_file, use_cpp)
  507. dirty_layers = keymap_json.pop('layers', None)
  508. keymap_json['layers'] = list()
  509. for layer in dirty_layers:
  510. layer.pop('name')
  511. layout = layer.pop('layout')
  512. if not keymap_json.get('layout', False):
  513. keymap_json['layout'] = layout
  514. keymap_json['layers'].append(layer.pop('keycodes'))
  515. keymap_json['keyboard'] = keyboard
  516. keymap_json['keymap'] = keymap
  517. return keymap_json