keymap.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. """Functions that help you work with QMK keymaps.
  2. """
  3. import sys
  4. from pathlib import Path
  5. from subprocess import DEVNULL
  6. import argcomplete
  7. from milc import cli
  8. from pygments.lexers.c_cpp import CLexer
  9. from pygments.token import Token
  10. from pygments import lex
  11. import qmk.path
  12. from qmk.constants import QMK_FIRMWARE, QMK_USERSPACE, HAS_QMK_USERSPACE
  13. from qmk.keyboard import find_keyboard_from_dir, keyboard_folder, keyboard_aliases
  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. #if __has_include("keymap.h")
  19. # include "keymap.h"
  20. #endif
  21. __INCLUDES__
  22. /* THIS FILE WAS GENERATED!
  23. *
  24. * This file was generated by qmk json2c. You may or may not want to
  25. * edit it directly.
  26. */
  27. __KEYMAP_GOES_HERE__
  28. __ENCODER_MAP_GOES_HERE__
  29. __DIP_SWITCH_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_dipswitchmap_table(keymap_json):
  58. lines = [
  59. '#if defined(DIP_SWITCH_ENABLE) && defined(DIP_SWITCH_MAP_ENABLE)',
  60. 'const uint16_t PROGMEM dip_switch_map[NUM_DIP_SWITCHES][NUM_DIP_STATES] = {',
  61. ]
  62. for index, switch in enumerate(keymap_json['dip_switches']):
  63. if index != 0:
  64. lines[-1] = lines[-1] + ','
  65. lines.append(f' DIP_SWITCH_OFF_ON({_strip_any(switch["off"])}, {_strip_any(switch["on"])})')
  66. lines.extend(['};', '#endif // defined(DIP_SWITCH_ENABLE) && defined(DIP_SWITCH_MAP_ENABLE)'])
  67. return lines
  68. def _generate_macros_function(keymap_json):
  69. macro_txt = [
  70. 'bool process_record_user(uint16_t keycode, keyrecord_t *record) {',
  71. ' if (record->event.pressed) {',
  72. ' switch (keycode) {',
  73. ]
  74. for i, macro_array in enumerate(keymap_json['macros']):
  75. macro = []
  76. for macro_fragment in macro_array:
  77. if isinstance(macro_fragment, str):
  78. macro_fragment = macro_fragment.replace('\\', '\\\\')
  79. macro_fragment = macro_fragment.replace('\r\n', r'\n')
  80. macro_fragment = macro_fragment.replace('\n', r'\n')
  81. macro_fragment = macro_fragment.replace('\r', r'\n')
  82. macro_fragment = macro_fragment.replace('\t', r'\t')
  83. macro_fragment = macro_fragment.replace('"', r'\"')
  84. macro.append(f'"{macro_fragment}"')
  85. elif isinstance(macro_fragment, dict):
  86. newstring = []
  87. if macro_fragment['action'] == 'delay':
  88. newstring.append(f"SS_DELAY({macro_fragment['duration']})")
  89. elif macro_fragment['action'] == 'beep':
  90. newstring.append(r'"\a"')
  91. elif macro_fragment['action'] == 'tap' and len(macro_fragment['keycodes']) > 1:
  92. last_keycode = macro_fragment['keycodes'].pop()
  93. for keycode in macro_fragment['keycodes']:
  94. newstring.append(f'SS_DOWN(X_{keycode})')
  95. newstring.append(f'SS_TAP(X_{last_keycode})')
  96. for keycode in reversed(macro_fragment['keycodes']):
  97. newstring.append(f'SS_UP(X_{keycode})')
  98. else:
  99. for keycode in macro_fragment['keycodes']:
  100. newstring.append(f"SS_{macro_fragment['action'].upper()}(X_{keycode})")
  101. macro.append(''.join(newstring))
  102. new_macro = "".join(macro)
  103. new_macro = new_macro.replace('""', '')
  104. macro_txt.append(f' case QK_MACRO_{i}:')
  105. macro_txt.append(f' SEND_STRING({new_macro});')
  106. macro_txt.append(' return false;')
  107. macro_txt.append(' }')
  108. macro_txt.append(' }')
  109. macro_txt.append('\n return true;')
  110. macro_txt.append('};')
  111. macro_txt.append('')
  112. return macro_txt
  113. def _strip_any(keycode):
  114. """Remove ANY() from a keycode.
  115. """
  116. if keycode.startswith('ANY(') and keycode.endswith(')'):
  117. keycode = keycode[4:-1]
  118. return keycode
  119. def find_keymap_from_dir(*args):
  120. """Returns `(keymap_name, source)` for the directory provided (or cwd if not specified).
  121. """
  122. def _impl_find_keymap_from_dir(relative_path):
  123. if relative_path and len(relative_path.parts) > 1:
  124. # If we're in `qmk_firmware/keyboards` and `keymaps` is in our path, try to find the keyboard name.
  125. if relative_path.parts[0] == 'keyboards' and 'keymaps' in relative_path.parts:
  126. current_path = Path('/'.join(relative_path.parts[1:])) # Strip 'keyboards' from the front
  127. if 'keymaps' in current_path.parts and current_path.name != 'keymaps':
  128. while current_path.parent.name != 'keymaps':
  129. current_path = current_path.parent
  130. return current_path.name, 'keymap_directory'
  131. # If we're in `qmk_firmware/layouts` guess the name from the community keymap they're in
  132. elif relative_path.parts[0] == 'layouts' and is_keymap_dir(relative_path):
  133. return relative_path.name, 'layouts_directory'
  134. # If we're in `qmk_firmware/users` guess the name from the userspace they're in
  135. elif relative_path.parts[0] == 'users':
  136. # Guess the keymap name based on which userspace they're in
  137. return relative_path.parts[1], 'users_directory'
  138. return None, None
  139. if HAS_QMK_USERSPACE:
  140. name, source = _impl_find_keymap_from_dir(qmk.path.under_qmk_userspace(*args))
  141. if name and source:
  142. return name, source
  143. name, source = _impl_find_keymap_from_dir(qmk.path.under_qmk_firmware(*args))
  144. if name and source:
  145. return name, source
  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 = {'keyboard': 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 = DEFAULT_KEYMAP_C
  218. keymap = ''
  219. if 'layers' in keymap_json and keymap_json['layers'] is not None:
  220. layer_txt = _generate_keymap_table(keymap_json)
  221. keymap = '\n'.join(layer_txt)
  222. new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap)
  223. encodermap = ''
  224. if 'encoders' in keymap_json and keymap_json['encoders'] is not None:
  225. encoder_txt = _generate_encodermap_table(keymap_json)
  226. encodermap = '\n'.join(encoder_txt)
  227. new_keymap = new_keymap.replace('__ENCODER_MAP_GOES_HERE__', encodermap)
  228. dipswitchmap = ''
  229. if 'dip_switches' in keymap_json and keymap_json['dip_switches'] is not None:
  230. dip_txt = _generate_dipswitchmap_table(keymap_json)
  231. dipswitchmap = '\n'.join(dip_txt)
  232. new_keymap = new_keymap.replace('__DIP_SWITCH_MAP_GOES_HERE__', dipswitchmap)
  233. macros = ''
  234. if 'macros' in keymap_json and keymap_json['macros'] is not None:
  235. macro_txt = _generate_macros_function(keymap_json)
  236. macros = '\n'.join(macro_txt)
  237. new_keymap = new_keymap.replace('__MACRO_OUTPUT_GOES_HERE__', macros)
  238. hostlang = ''
  239. if 'host_language' in keymap_json and keymap_json['host_language'] is not None:
  240. hostlang = f'#include "keymap_{keymap_json["host_language"]}.h"\n#include "sendstring_{keymap_json["host_language"]}.h"\n'
  241. new_keymap = new_keymap.replace('__INCLUDES__', hostlang)
  242. return new_keymap
  243. def locate_keymap(keyboard, keymap, force_layout=None):
  244. """Returns the path to a keymap for a specific keyboard.
  245. """
  246. if not qmk.path.is_keyboard(keyboard):
  247. raise KeyError('Invalid keyboard: ' + repr(keyboard))
  248. # Check the keyboard folder first, last match wins
  249. keymap_path = ''
  250. search_conf = {QMK_FIRMWARE: [keyboard_folder(keyboard)]}
  251. if HAS_QMK_USERSPACE:
  252. # When we've got userspace, check there _last_ as we want them to override anything in the main repo.
  253. # We also want to search for any aliases as QMK's folder structure may have changed, with an alias, but the user
  254. # hasn't updated their keymap location yet.
  255. search_conf[QMK_USERSPACE] = list(set([keyboard_folder(keyboard), *keyboard_aliases(keyboard)]))
  256. for search_dir, keyboard_dirs in search_conf.items():
  257. for keyboard_dir in keyboard_dirs:
  258. checked_dirs = ''
  259. for folder_name in keyboard_dir.split('/'):
  260. if checked_dirs:
  261. checked_dirs = '/'.join((checked_dirs, folder_name))
  262. else:
  263. checked_dirs = folder_name
  264. keymap_dir = Path(search_dir) / Path('keyboards') / checked_dirs / 'keymaps'
  265. if (keymap_dir / keymap / 'keymap.c').exists():
  266. keymap_path = keymap_dir / keymap / 'keymap.c'
  267. if (keymap_dir / keymap / 'keymap.json').exists():
  268. keymap_path = keymap_dir / keymap / 'keymap.json'
  269. if keymap_path:
  270. return keymap_path
  271. # Check community layouts as a fallback
  272. info = info_json(keyboard, force_layout=force_layout)
  273. community_parents = list(Path('layouts').glob('*/'))
  274. if HAS_QMK_USERSPACE and (Path(QMK_USERSPACE) / "layouts").exists():
  275. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  276. for community_parent in community_parents:
  277. for layout in info.get("community_layouts", []):
  278. community_layout = community_parent / layout / keymap
  279. if community_layout.exists():
  280. if (community_layout / 'keymap.json').exists():
  281. return community_layout / 'keymap.json'
  282. if (community_layout / 'keymap.c').exists():
  283. return community_layout / 'keymap.c'
  284. def is_keymap_target(keyboard, keymap):
  285. if keymap == 'all':
  286. return True
  287. if locate_keymap(keyboard, keymap):
  288. return True
  289. return False
  290. def list_keymaps(keyboard, c=True, json=True, additional_files=None, fullpath=False, include_userspace=True):
  291. """List the available keymaps for a keyboard.
  292. Args:
  293. keyboard
  294. The keyboards full name with vendor and revision if necessary, example: clueboard/66/rev3
  295. c
  296. When true include `keymap.c` keymaps.
  297. json
  298. When true include `keymap.json` keymaps.
  299. additional_files
  300. 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'])`
  301. fullpath
  302. When set to True the full path of the keymap relative to the `qmk_firmware` root will be provided.
  303. include_userspace
  304. When set to True, also search userspace for available keymaps
  305. Returns:
  306. a sorted list of valid keymap names.
  307. """
  308. names = set()
  309. has_userspace = HAS_QMK_USERSPACE and include_userspace
  310. # walk up the directory tree until keyboards_dir
  311. # and collect all directories' name with keymap.c file in it
  312. for search_dir in [QMK_FIRMWARE, QMK_USERSPACE] if has_userspace else [QMK_FIRMWARE]:
  313. keyboards_dir = search_dir / Path('keyboards')
  314. kb_path = keyboards_dir / keyboard
  315. while kb_path != keyboards_dir:
  316. keymaps_dir = kb_path / "keymaps"
  317. if keymaps_dir.is_dir():
  318. for keymap in keymaps_dir.iterdir():
  319. if is_keymap_dir(keymap, c, json, additional_files):
  320. keymap = keymap if fullpath else keymap.name
  321. names.add(keymap)
  322. kb_path = kb_path.parent
  323. # Check community layouts as a fallback
  324. info = info_json(keyboard)
  325. community_parents = list(Path('layouts').glob('*/'))
  326. if has_userspace and (Path(QMK_USERSPACE) / "layouts").exists():
  327. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  328. for community_parent in community_parents:
  329. for layout in info.get("community_layouts", []):
  330. cl_path = community_parent / layout
  331. if cl_path.is_dir():
  332. for keymap in cl_path.iterdir():
  333. if is_keymap_dir(keymap, c, json, additional_files):
  334. keymap = keymap if fullpath else keymap.name
  335. names.add(keymap)
  336. return sorted(names)
  337. def _c_preprocess(path, stdin=DEVNULL):
  338. """ Run a file through the C pre-processor
  339. Args:
  340. path: path of the keymap.c file (set None to use stdin)
  341. stdin: stdin pipe (e.g. sys.stdin)
  342. Returns:
  343. the stdout of the pre-processor
  344. """
  345. cmd = ['cpp', str(path)] if path else ['cpp']
  346. pre_processed_keymap = cli.run(cmd, stdin=stdin)
  347. if 'fatal error' in pre_processed_keymap.stderr:
  348. for line in pre_processed_keymap.stderr.split('\n'):
  349. if 'fatal error' in line:
  350. raise (CppError(line))
  351. return pre_processed_keymap.stdout
  352. def _get_layers(keymap): # noqa C901 : until someone has a good idea how to simplify/split up this code
  353. """ Find the layers in a keymap.c file.
  354. Args:
  355. keymap: the content of the keymap.c file
  356. Returns:
  357. a dictionary containing the parsed keymap
  358. """
  359. layers = list()
  360. opening_braces = '({['
  361. closing_braces = ')}]'
  362. keymap_certainty = brace_depth = 0
  363. is_keymap = is_layer = is_adv_kc = False
  364. layer = dict(name=False, layout=False, keycodes=list())
  365. for line in lex(keymap, CLexer()):
  366. if line[0] is Token.Name:
  367. if is_keymap:
  368. # If we are inside the keymap array
  369. # we know the keymap's name and the layout macro will come,
  370. # followed by the keycodes
  371. if not layer['name']:
  372. if line[1].startswith('LAYOUT') or line[1].startswith('KEYMAP'):
  373. # This can happen if the keymap array only has one layer,
  374. # for macropads and such
  375. layer['name'] = '0'
  376. layer['layout'] = line[1]
  377. else:
  378. layer['name'] = line[1]
  379. elif not layer['layout']:
  380. layer['layout'] = line[1]
  381. elif is_layer:
  382. # If we are inside a layout macro,
  383. # collect all keycodes
  384. if line[1] == '_______':
  385. kc = 'KC_TRNS'
  386. elif line[1] == 'XXXXXXX':
  387. kc = 'KC_NO'
  388. else:
  389. kc = line[1]
  390. if is_adv_kc:
  391. # If we are inside an advanced keycode
  392. # collect everything and hope the user
  393. # knew what he/she was doing
  394. layer['keycodes'][-1] += kc
  395. else:
  396. layer['keycodes'].append(kc)
  397. # The keymaps array's signature:
  398. # const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS]
  399. #
  400. # Only if we've found all 6 keywords in this specific order
  401. # can we know for sure that we are inside the keymaps array
  402. elif line[1] == 'PROGMEM' and keymap_certainty == 2:
  403. keymap_certainty = 3
  404. elif line[1] == 'keymaps' and keymap_certainty == 3:
  405. keymap_certainty = 4
  406. elif line[1] == 'MATRIX_ROWS' and keymap_certainty == 4:
  407. keymap_certainty = 5
  408. elif line[1] == 'MATRIX_COLS' and keymap_certainty == 5:
  409. keymap_certainty = 6
  410. elif line[0] is Token.Keyword:
  411. if line[1] == 'const' and keymap_certainty == 0:
  412. keymap_certainty = 1
  413. elif line[0] is Token.Keyword.Type:
  414. if line[1] == 'uint16_t' and keymap_certainty == 1:
  415. keymap_certainty = 2
  416. elif line[0] is Token.Punctuation:
  417. if line[1] in opening_braces:
  418. brace_depth += 1
  419. if is_keymap:
  420. if is_layer:
  421. # We found the beginning of a non-basic keycode
  422. is_adv_kc = True
  423. layer['keycodes'][-1] += line[1]
  424. elif line[1] == '(' and brace_depth == 2:
  425. # We found the beginning of a layer
  426. is_layer = True
  427. elif line[1] == '{' and keymap_certainty == 6:
  428. # We found the beginning of the keymaps array
  429. is_keymap = True
  430. elif line[1] in closing_braces:
  431. brace_depth -= 1
  432. if is_keymap:
  433. if is_adv_kc:
  434. layer['keycodes'][-1] += line[1]
  435. if brace_depth == 2:
  436. # We found the end of a non-basic keycode
  437. is_adv_kc = False
  438. elif line[1] == ')' and brace_depth == 1:
  439. # We found the end of a layer
  440. is_layer = False
  441. layers.append(layer)
  442. layer = dict(name=False, layout=False, keycodes=list())
  443. elif line[1] == '}' and brace_depth == 0:
  444. # We found the end of the keymaps array
  445. is_keymap = False
  446. keymap_certainty = 0
  447. elif is_adv_kc:
  448. # Advanced keycodes can contain other punctuation
  449. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  450. layer['keycodes'][-1] += line[1]
  451. elif line[0] is Token.Literal.Number.Integer and is_keymap and not is_adv_kc:
  452. # If the pre-processor finds the 'meaning' of the layer names,
  453. # they will be numbers
  454. if not layer['name']:
  455. layer['name'] = line[1]
  456. else:
  457. # We only care about
  458. # operators and such if we
  459. # are inside an advanced keycode
  460. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  461. if is_adv_kc:
  462. layer['keycodes'][-1] += line[1]
  463. return layers
  464. def parse_keymap_c(keymap_file, use_cpp=True):
  465. """ Parse a keymap.c file.
  466. Currently only cares about the keymaps array.
  467. Args:
  468. keymap_file: path of the keymap.c file (or '-' to use stdin)
  469. use_cpp: if True, pre-process the file with the C pre-processor
  470. Returns:
  471. a dictionary containing the parsed keymap
  472. """
  473. if not isinstance(keymap_file, (Path, str)) or keymap_file == '-':
  474. if use_cpp:
  475. keymap_file = _c_preprocess(None, sys.stdin)
  476. else:
  477. keymap_file = sys.stdin.read()
  478. else:
  479. if use_cpp:
  480. keymap_file = _c_preprocess(keymap_file)
  481. else:
  482. keymap_file = keymap_file.read_text(encoding='utf-8')
  483. keymap = dict()
  484. keymap['layers'] = _get_layers(keymap_file)
  485. return keymap
  486. def c2json(keyboard, keymap, keymap_file, use_cpp=True):
  487. """ Convert keymap.c to keymap.json
  488. Args:
  489. keyboard: The name of the keyboard
  490. keymap: The name of the keymap
  491. layout: The LAYOUT macro this keymap uses.
  492. keymap_file: path of the keymap.c file
  493. use_cpp: if True, pre-process the file with the C pre-processor
  494. Returns:
  495. a dictionary in keymap.json format
  496. """
  497. keymap_json = parse_keymap_c(keymap_file, use_cpp)
  498. dirty_layers = keymap_json.pop('layers', None)
  499. keymap_json['layers'] = list()
  500. for layer in dirty_layers:
  501. layer.pop('name')
  502. layout = layer.pop('layout')
  503. if not keymap_json.get('layout', False):
  504. keymap_json['layout'] = layout
  505. keymap_json['layers'].append(layer.pop('keycodes'))
  506. keymap_json['keyboard'] = keyboard
  507. keymap_json['keymap'] = keymap
  508. return keymap_json