keymap.py 23 KB

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