keymap.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. """Functions that help you work with QMK keymaps.
  2. """
  3. import sys
  4. import re
  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. __DIP_SWITCH_MAP_GOES_HERE__
  31. __MACRO_OUTPUT_GOES_HERE__
  32. #ifdef OTHER_KEYMAP_C
  33. # include OTHER_KEYMAP_C
  34. #endif // OTHER_KEYMAP_C
  35. """
  36. def _generate_keymap_table(keymap_json):
  37. lines = ['const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {']
  38. for layer_num, layer in enumerate(keymap_json['layers']):
  39. if layer_num != 0:
  40. lines[-1] = lines[-1] + ','
  41. layer = map(_strip_any, layer)
  42. layer_keys = ', '.join(layer)
  43. lines.append(' [%s] = %s(%s)' % (layer_num, keymap_json['layout'], layer_keys))
  44. lines.append('};')
  45. return lines
  46. def _generate_encodermap_table(keymap_json):
  47. lines = [
  48. '#if defined(ENCODER_ENABLE) && defined(ENCODER_MAP_ENABLE)',
  49. 'const uint16_t PROGMEM encoder_map[][NUM_ENCODERS][NUM_DIRECTIONS] = {',
  50. ]
  51. for layer_num, layer in enumerate(keymap_json['encoders']):
  52. if layer_num != 0:
  53. lines[-1] = lines[-1] + ','
  54. encoder_keycode_txt = ', '.join([f'ENCODER_CCW_CW({_strip_any(e["ccw"])}, {_strip_any(e["cw"])})' for e in layer])
  55. lines.append(' [%s] = {%s}' % (layer_num, encoder_keycode_txt))
  56. lines.extend(['};', '#endif // defined(ENCODER_ENABLE) && defined(ENCODER_MAP_ENABLE)'])
  57. return lines
  58. def _generate_dipswitchmap_table(keymap_json):
  59. lines = [
  60. '#if defined(DIP_SWITCH_ENABLE) && defined(DIP_SWITCH_MAP_ENABLE)',
  61. 'const uint16_t PROGMEM dip_switch_map[NUM_DIP_SWITCHES][NUM_DIP_STATES] = {',
  62. ]
  63. for index, switch in enumerate(keymap_json['dip_switches']):
  64. if index != 0:
  65. lines[-1] = lines[-1] + ','
  66. lines.append(f' DIP_SWITCH_OFF_ON({_strip_any(switch["off"])}, {_strip_any(switch["on"])})')
  67. lines.extend(['};', '#endif // defined(DIP_SWITCH_ENABLE) && defined(DIP_SWITCH_MAP_ENABLE)'])
  68. return lines
  69. def _generate_macros_function(keymap_json):
  70. macro_txt = [
  71. 'bool process_record_user(uint16_t keycode, keyrecord_t *record) {',
  72. ' if (record->event.pressed) {',
  73. ' switch (keycode) {',
  74. ]
  75. for i, macro_array in enumerate(keymap_json['macros']):
  76. macro = []
  77. for macro_fragment in macro_array:
  78. if isinstance(macro_fragment, str):
  79. macro_fragment = macro_fragment.replace('\\', '\\\\')
  80. macro_fragment = macro_fragment.replace('\r\n', r'\n')
  81. macro_fragment = macro_fragment.replace('\n', r'\n')
  82. macro_fragment = macro_fragment.replace('\r', r'\n')
  83. macro_fragment = macro_fragment.replace('\t', r'\t')
  84. macro_fragment = macro_fragment.replace('"', r'\"')
  85. macro.append(f'"{macro_fragment}"')
  86. elif isinstance(macro_fragment, dict):
  87. newstring = []
  88. if macro_fragment['action'] == 'delay':
  89. newstring.append(f"SS_DELAY({macro_fragment['duration']})")
  90. elif macro_fragment['action'] == 'beep':
  91. newstring.append(r'"\a"')
  92. elif macro_fragment['action'] == 'tap' and len(macro_fragment['keycodes']) > 1:
  93. last_keycode = macro_fragment['keycodes'].pop()
  94. for keycode in macro_fragment['keycodes']:
  95. newstring.append(f'SS_DOWN(X_{keycode})')
  96. newstring.append(f'SS_TAP(X_{last_keycode})')
  97. for keycode in reversed(macro_fragment['keycodes']):
  98. newstring.append(f'SS_UP(X_{keycode})')
  99. else:
  100. for keycode in macro_fragment['keycodes']:
  101. newstring.append(f"SS_{macro_fragment['action'].upper()}(X_{keycode})")
  102. macro.append(''.join(newstring))
  103. new_macro = "".join(macro)
  104. new_macro = new_macro.replace('""', '')
  105. macro_txt.append(f' case QK_MACRO_{i}:')
  106. macro_txt.append(f' SEND_STRING({new_macro});')
  107. macro_txt.append(' return false;')
  108. macro_txt.append(' }')
  109. macro_txt.append(' }')
  110. macro_txt.append('\n return true;')
  111. macro_txt.append('};')
  112. macro_txt.append('')
  113. return macro_txt
  114. def _strip_any(keycode):
  115. """Remove ANY() from a keycode.
  116. """
  117. if keycode.startswith('ANY(') and keycode.endswith(')'):
  118. keycode = keycode[4:-1]
  119. return keycode
  120. def find_keymap_from_dir(*args):
  121. """Returns `(keymap_name, source)` for the directory provided (or cwd if not specified).
  122. """
  123. def _impl_find_keymap_from_dir(relative_path):
  124. if relative_path and len(relative_path.parts) > 1:
  125. # If we're in `qmk_firmware/keyboards` and `keymaps` is in our path, try to find the keyboard name.
  126. if relative_path.parts[0] == 'keyboards' and 'keymaps' in relative_path.parts:
  127. current_path = Path('/'.join(relative_path.parts[1:])) # Strip 'keyboards' from the front
  128. if 'keymaps' in current_path.parts and current_path.name != 'keymaps':
  129. while current_path.parent.name != 'keymaps':
  130. current_path = current_path.parent
  131. return current_path.name, 'keymap_directory'
  132. # If we're in `qmk_firmware/layouts` guess the name from the community keymap they're in
  133. elif relative_path.parts[0] == 'layouts' and is_keymap_dir(relative_path):
  134. return relative_path.name, 'layouts_directory'
  135. # If we're in `qmk_firmware/users` guess the name from the userspace they're in
  136. elif relative_path.parts[0] == 'users':
  137. # Guess the keymap name based on which userspace they're in
  138. return relative_path.parts[1], 'users_directory'
  139. return None, None
  140. if HAS_QMK_USERSPACE:
  141. name, source = _impl_find_keymap_from_dir(qmk.path.under_qmk_userspace(*args))
  142. if name and source:
  143. return name, source
  144. name, source = _impl_find_keymap_from_dir(qmk.path.under_qmk_firmware(*args))
  145. if name and source:
  146. return name, source
  147. return (None, None)
  148. def keymap_completer(prefix, action, parser, parsed_args):
  149. """Returns a list of keymaps for tab completion.
  150. """
  151. try:
  152. if parsed_args.keyboard:
  153. return list_keymaps(parsed_args.keyboard)
  154. keyboard = find_keyboard_from_dir()
  155. if keyboard:
  156. return list_keymaps(keyboard)
  157. except Exception as e:
  158. argcomplete.warn(f'Error: {e.__class__.__name__}: {str(e)}')
  159. return []
  160. return []
  161. def is_keymap_dir(keymap, c=True, json=True, additional_files=None):
  162. """Return True if Path object `keymap` has a keymap file inside.
  163. Args:
  164. keymap
  165. A Path() object for the keymap directory you want to check.
  166. c
  167. When true include `keymap.c` keymaps.
  168. json
  169. When true include `keymap.json` keymaps.
  170. additional_files
  171. 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'])`
  172. """
  173. files = []
  174. if c:
  175. files.append('keymap.c')
  176. if json:
  177. files.append('keymap.json')
  178. for file in files:
  179. if (keymap / file).is_file():
  180. if additional_files:
  181. for additional_file in additional_files:
  182. if not (keymap / additional_file).is_file():
  183. return False
  184. return True
  185. def is_valid_keymap_name(name):
  186. """Returns True if the given keymap name contains only valid characters.
  187. """
  188. regex = re.compile(r'^[a-z0-9][a-z0-9_]+$')
  189. return bool(regex.match(name))
  190. def generate_json(keymap, keyboard, layout, layers, macros=None):
  191. """Returns a `keymap.json` for the specified keyboard, layout, and layers.
  192. Args:
  193. keymap
  194. A name for this keymap.
  195. keyboard
  196. The name of the keyboard.
  197. layout
  198. The LAYOUT macro this keymap uses.
  199. layers
  200. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  201. macros
  202. A sequence of strings containing macros to implement for this keyboard.
  203. """
  204. new_keymap = {'keyboard': keyboard}
  205. new_keymap['keymap'] = keymap
  206. new_keymap['layout'] = layout
  207. new_keymap['layers'] = layers
  208. if macros:
  209. new_keymap['macros'] = macros
  210. return new_keymap
  211. def generate_c(keymap_json):
  212. """Returns a `keymap.c`.
  213. `keymap_json` is a dictionary with the following keys:
  214. keyboard
  215. The name of the keyboard
  216. layout
  217. The LAYOUT macro this keymap uses.
  218. layers
  219. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  220. macros
  221. A sequence of strings containing macros to implement for this keyboard.
  222. """
  223. new_keymap = DEFAULT_KEYMAP_C
  224. keymap = ''
  225. if 'layers' in keymap_json and keymap_json['layers'] is not None:
  226. layer_txt = _generate_keymap_table(keymap_json)
  227. keymap = '\n'.join(layer_txt)
  228. new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap)
  229. encodermap = ''
  230. if 'encoders' in keymap_json and keymap_json['encoders'] is not None:
  231. encoder_txt = _generate_encodermap_table(keymap_json)
  232. encodermap = '\n'.join(encoder_txt)
  233. new_keymap = new_keymap.replace('__ENCODER_MAP_GOES_HERE__', encodermap)
  234. dipswitchmap = ''
  235. if 'dip_switches' in keymap_json and keymap_json['dip_switches'] is not None:
  236. dip_txt = _generate_dipswitchmap_table(keymap_json)
  237. dipswitchmap = '\n'.join(dip_txt)
  238. new_keymap = new_keymap.replace('__DIP_SWITCH_MAP_GOES_HERE__', dipswitchmap)
  239. macros = ''
  240. if 'macros' in keymap_json and keymap_json['macros'] is not None:
  241. macro_txt = _generate_macros_function(keymap_json)
  242. macros = '\n'.join(macro_txt)
  243. new_keymap = new_keymap.replace('__MACRO_OUTPUT_GOES_HERE__', macros)
  244. hostlang = ''
  245. if 'host_language' in keymap_json and keymap_json['host_language'] is not None:
  246. hostlang = f'#include "keymap_{keymap_json["host_language"]}.h"\n#include "sendstring_{keymap_json["host_language"]}.h"\n'
  247. new_keymap = new_keymap.replace('__INCLUDES__', hostlang)
  248. return new_keymap
  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_conf = {QMK_FIRMWARE: [keyboard_folder(keyboard)]}
  257. if HAS_QMK_USERSPACE:
  258. # When we've got userspace, check there _last_ as we want them to override anything in the main repo.
  259. # We also want to search for any aliases as QMK's folder structure may have changed, with an alias, but the user
  260. # hasn't updated their keymap location yet.
  261. search_conf[QMK_USERSPACE] = list(set([keyboard_folder(keyboard), *keyboard_aliases(keyboard)]))
  262. for search_dir, keyboard_dirs in search_conf.items():
  263. for keyboard_dir in keyboard_dirs:
  264. checked_dirs = ''
  265. for folder_name in keyboard_dir.split('/'):
  266. if checked_dirs:
  267. checked_dirs = '/'.join((checked_dirs, folder_name))
  268. else:
  269. checked_dirs = folder_name
  270. keymap_dir = Path(search_dir) / Path('keyboards') / checked_dirs / 'keymaps'
  271. if (keymap_dir / keymap / 'keymap.c').exists():
  272. keymap_path = keymap_dir / keymap / 'keymap.c'
  273. if (keymap_dir / keymap / 'keymap.json').exists():
  274. keymap_path = keymap_dir / keymap / 'keymap.json'
  275. if keymap_path:
  276. return keymap_path
  277. # Check community layouts as a fallback
  278. info = info_json(keyboard, force_layout=force_layout)
  279. community_parents = list(Path('layouts').glob('*/'))
  280. if HAS_QMK_USERSPACE and (Path(QMK_USERSPACE) / "layouts").exists():
  281. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  282. for community_parent in community_parents:
  283. for layout in info.get("community_layouts", []):
  284. community_layout = community_parent / layout / keymap
  285. if community_layout.exists():
  286. if (community_layout / 'keymap.json').exists():
  287. return community_layout / 'keymap.json'
  288. if (community_layout / 'keymap.c').exists():
  289. return community_layout / 'keymap.c'
  290. def is_keymap_target(keyboard, keymap):
  291. if keymap == 'all':
  292. return True
  293. if locate_keymap(keyboard, keymap):
  294. return True
  295. return False
  296. def list_keymaps(keyboard, c=True, json=True, additional_files=None, fullpath=False, include_userspace=True, include_community=True):
  297. """List the available keymaps for a keyboard.
  298. Args:
  299. keyboard
  300. The keyboards full name with vendor and revision if necessary, example: clueboard/66/rev3
  301. c
  302. When true include `keymap.c` keymaps.
  303. json
  304. When true include `keymap.json` keymaps.
  305. additional_files
  306. 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'])`
  307. fullpath
  308. When set to True the full path of the keymap relative to the `qmk_firmware` root will be provided.
  309. include_userspace
  310. When set to True, also search userspace for available keymaps
  311. include_community
  312. When set to True, also search community layouts folder for available keymaps
  313. Returns:
  314. a sorted list of valid keymap names.
  315. """
  316. names = set()
  317. has_userspace = HAS_QMK_USERSPACE and include_userspace
  318. # walk up the directory tree until keyboards_dir
  319. # and collect all directories' name with keymap.c file in it
  320. for search_dir in [QMK_FIRMWARE, QMK_USERSPACE] if has_userspace else [QMK_FIRMWARE]:
  321. keyboards_dir = search_dir / Path('keyboards')
  322. kb_path = keyboards_dir / keyboard
  323. while kb_path != keyboards_dir:
  324. keymaps_dir = kb_path / "keymaps"
  325. if keymaps_dir.is_dir():
  326. for keymap in keymaps_dir.iterdir():
  327. if is_keymap_dir(keymap, c, json, additional_files):
  328. keymap = keymap if fullpath else keymap.name
  329. names.add(keymap)
  330. kb_path = kb_path.parent
  331. if include_community:
  332. # Check community layouts as a fallback
  333. info = info_json(keyboard)
  334. community_parents = list(Path('layouts').glob('*/'))
  335. if has_userspace and (Path(QMK_USERSPACE) / "layouts").exists():
  336. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  337. for community_parent in community_parents:
  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 not isinstance(keymap_file, (Path, str)) or 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