keymap.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. __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 generate_json(keymap, keyboard, layout, layers, macros=None):
  186. """Returns a `keymap.json` for the specified keyboard, layout, and layers.
  187. Args:
  188. keymap
  189. A name for this keymap.
  190. keyboard
  191. The name of the keyboard.
  192. layout
  193. The LAYOUT macro this keymap uses.
  194. layers
  195. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  196. macros
  197. A sequence of strings containing macros to implement for this keyboard.
  198. """
  199. new_keymap = {'keyboard': keyboard}
  200. new_keymap['keymap'] = keymap
  201. new_keymap['layout'] = layout
  202. new_keymap['layers'] = layers
  203. if macros:
  204. new_keymap['macros'] = macros
  205. return new_keymap
  206. def generate_c(keymap_json):
  207. """Returns a `keymap.c`.
  208. `keymap_json` is a dictionary with the following keys:
  209. keyboard
  210. The name of the keyboard
  211. layout
  212. The LAYOUT macro this keymap uses.
  213. layers
  214. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  215. macros
  216. A sequence of strings containing macros to implement for this keyboard.
  217. """
  218. new_keymap = DEFAULT_KEYMAP_C
  219. keymap = ''
  220. if 'layers' in keymap_json and keymap_json['layers'] is not None:
  221. layer_txt = _generate_keymap_table(keymap_json)
  222. keymap = '\n'.join(layer_txt)
  223. new_keymap = new_keymap.replace('__KEYMAP_GOES_HERE__', keymap)
  224. encodermap = ''
  225. if 'encoders' in keymap_json and keymap_json['encoders'] is not None:
  226. encoder_txt = _generate_encodermap_table(keymap_json)
  227. encodermap = '\n'.join(encoder_txt)
  228. new_keymap = new_keymap.replace('__ENCODER_MAP_GOES_HERE__', encodermap)
  229. dipswitchmap = ''
  230. if 'dip_switches' in keymap_json and keymap_json['dip_switches'] is not None:
  231. dip_txt = _generate_dipswitchmap_table(keymap_json)
  232. dipswitchmap = '\n'.join(dip_txt)
  233. new_keymap = new_keymap.replace('__DIP_SWITCH_MAP_GOES_HERE__', dipswitchmap)
  234. macros = ''
  235. if 'macros' in keymap_json and keymap_json['macros'] is not None:
  236. macro_txt = _generate_macros_function(keymap_json)
  237. macros = '\n'.join(macro_txt)
  238. new_keymap = new_keymap.replace('__MACRO_OUTPUT_GOES_HERE__', macros)
  239. hostlang = ''
  240. if 'host_language' in keymap_json and keymap_json['host_language'] is not None:
  241. hostlang = f'#include "keymap_{keymap_json["host_language"]}.h"\n#include "sendstring_{keymap_json["host_language"]}.h"\n'
  242. new_keymap = new_keymap.replace('__INCLUDES__', hostlang)
  243. return new_keymap
  244. def write_file(keymap_filename, keymap_content):
  245. keymap_filename.parent.mkdir(parents=True, exist_ok=True)
  246. keymap_filename.write_text(keymap_content)
  247. cli.log.info('Wrote keymap to {fg_cyan}%s', keymap_filename)
  248. return keymap_filename
  249. def write_json(keyboard, keymap, layout, layers, macros=None):
  250. """Generate the `keymap.json` and write it to disk.
  251. Returns the filename written to.
  252. Args:
  253. keyboard
  254. The name of the keyboard
  255. keymap
  256. The name of the keymap
  257. layout
  258. The LAYOUT macro this keymap uses.
  259. layers
  260. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  261. """
  262. keymap_json = generate_json(keyboard, keymap, layout, layers, macros=None)
  263. keymap_content = json.dumps(keymap_json)
  264. keymap_file = qmk.path.keymaps(keyboard)[0] / keymap / 'keymap.json'
  265. return write_file(keymap_file, keymap_content)
  266. def locate_keymap(keyboard, keymap, force_layout=None):
  267. """Returns the path to a keymap for a specific keyboard.
  268. """
  269. if not qmk.path.is_keyboard(keyboard):
  270. raise KeyError('Invalid keyboard: ' + repr(keyboard))
  271. # Check the keyboard folder first, last match wins
  272. keymap_path = ''
  273. search_conf = {QMK_FIRMWARE: [keyboard_folder(keyboard)]}
  274. if HAS_QMK_USERSPACE:
  275. # When we've got userspace, check there _last_ as we want them to override anything in the main repo.
  276. # We also want to search for any aliases as QMK's folder structure may have changed, with an alias, but the user
  277. # hasn't updated their keymap location yet.
  278. search_conf[QMK_USERSPACE] = list(set([keyboard_folder(keyboard), *keyboard_aliases(keyboard)]))
  279. for search_dir, keyboard_dirs in search_conf.items():
  280. for keyboard_dir in keyboard_dirs:
  281. checked_dirs = ''
  282. for folder_name in keyboard_dir.split('/'):
  283. if checked_dirs:
  284. checked_dirs = '/'.join((checked_dirs, folder_name))
  285. else:
  286. checked_dirs = folder_name
  287. keymap_dir = Path(search_dir) / Path('keyboards') / checked_dirs / 'keymaps'
  288. if (keymap_dir / keymap / 'keymap.c').exists():
  289. keymap_path = keymap_dir / keymap / 'keymap.c'
  290. if (keymap_dir / keymap / 'keymap.json').exists():
  291. keymap_path = keymap_dir / keymap / 'keymap.json'
  292. if keymap_path:
  293. return keymap_path
  294. # Check community layouts as a fallback
  295. info = info_json(keyboard, force_layout=force_layout)
  296. community_parents = list(Path('layouts').glob('*/'))
  297. if HAS_QMK_USERSPACE and (Path(QMK_USERSPACE) / "layouts").exists():
  298. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  299. for community_parent in community_parents:
  300. for layout in info.get("community_layouts", []):
  301. community_layout = community_parent / layout / keymap
  302. if community_layout.exists():
  303. if (community_layout / 'keymap.json').exists():
  304. return community_layout / 'keymap.json'
  305. if (community_layout / 'keymap.c').exists():
  306. return community_layout / 'keymap.c'
  307. def is_keymap_target(keyboard, keymap):
  308. if keymap == 'all':
  309. return True
  310. if locate_keymap(keyboard, keymap):
  311. return True
  312. return False
  313. def list_keymaps(keyboard, c=True, json=True, additional_files=None, fullpath=False, include_userspace=True):
  314. """List the available keymaps for a keyboard.
  315. Args:
  316. keyboard
  317. The keyboards full name with vendor and revision if necessary, example: clueboard/66/rev3
  318. c
  319. When true include `keymap.c` keymaps.
  320. json
  321. When true include `keymap.json` keymaps.
  322. additional_files
  323. 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'])`
  324. fullpath
  325. When set to True the full path of the keymap relative to the `qmk_firmware` root will be provided.
  326. include_userspace
  327. When set to True, also search userspace for available keymaps
  328. Returns:
  329. a sorted list of valid keymap names.
  330. """
  331. names = set()
  332. has_userspace = HAS_QMK_USERSPACE and include_userspace
  333. # walk up the directory tree until keyboards_dir
  334. # and collect all directories' name with keymap.c file in it
  335. for search_dir in [QMK_FIRMWARE, QMK_USERSPACE] if has_userspace else [QMK_FIRMWARE]:
  336. keyboards_dir = search_dir / Path('keyboards')
  337. kb_path = keyboards_dir / keyboard
  338. while kb_path != keyboards_dir:
  339. keymaps_dir = kb_path / "keymaps"
  340. if keymaps_dir.is_dir():
  341. for keymap in keymaps_dir.iterdir():
  342. if is_keymap_dir(keymap, c, json, additional_files):
  343. keymap = keymap if fullpath else keymap.name
  344. names.add(keymap)
  345. kb_path = kb_path.parent
  346. # Check community layouts as a fallback
  347. info = info_json(keyboard)
  348. community_parents = list(Path('layouts').glob('*/'))
  349. if has_userspace and (Path(QMK_USERSPACE) / "layouts").exists():
  350. community_parents.append(Path(QMK_USERSPACE) / "layouts")
  351. for community_parent in community_parents:
  352. for layout in info.get("community_layouts", []):
  353. cl_path = community_parent / layout
  354. if cl_path.is_dir():
  355. for keymap in cl_path.iterdir():
  356. if is_keymap_dir(keymap, c, json, additional_files):
  357. keymap = keymap if fullpath else keymap.name
  358. names.add(keymap)
  359. return sorted(names)
  360. def _c_preprocess(path, stdin=DEVNULL):
  361. """ Run a file through the C pre-processor
  362. Args:
  363. path: path of the keymap.c file (set None to use stdin)
  364. stdin: stdin pipe (e.g. sys.stdin)
  365. Returns:
  366. the stdout of the pre-processor
  367. """
  368. cmd = ['cpp', str(path)] if path else ['cpp']
  369. pre_processed_keymap = cli.run(cmd, stdin=stdin)
  370. if 'fatal error' in pre_processed_keymap.stderr:
  371. for line in pre_processed_keymap.stderr.split('\n'):
  372. if 'fatal error' in line:
  373. raise (CppError(line))
  374. return pre_processed_keymap.stdout
  375. def _get_layers(keymap): # noqa C901 : until someone has a good idea how to simplify/split up this code
  376. """ Find the layers in a keymap.c file.
  377. Args:
  378. keymap: the content of the keymap.c file
  379. Returns:
  380. a dictionary containing the parsed keymap
  381. """
  382. layers = list()
  383. opening_braces = '({['
  384. closing_braces = ')}]'
  385. keymap_certainty = brace_depth = 0
  386. is_keymap = is_layer = is_adv_kc = False
  387. layer = dict(name=False, layout=False, keycodes=list())
  388. for line in lex(keymap, CLexer()):
  389. if line[0] is Token.Name:
  390. if is_keymap:
  391. # If we are inside the keymap array
  392. # we know the keymap's name and the layout macro will come,
  393. # followed by the keycodes
  394. if not layer['name']:
  395. if line[1].startswith('LAYOUT') or line[1].startswith('KEYMAP'):
  396. # This can happen if the keymap array only has one layer,
  397. # for macropads and such
  398. layer['name'] = '0'
  399. layer['layout'] = line[1]
  400. else:
  401. layer['name'] = line[1]
  402. elif not layer['layout']:
  403. layer['layout'] = line[1]
  404. elif is_layer:
  405. # If we are inside a layout macro,
  406. # collect all keycodes
  407. if line[1] == '_______':
  408. kc = 'KC_TRNS'
  409. elif line[1] == 'XXXXXXX':
  410. kc = 'KC_NO'
  411. else:
  412. kc = line[1]
  413. if is_adv_kc:
  414. # If we are inside an advanced keycode
  415. # collect everything and hope the user
  416. # knew what he/she was doing
  417. layer['keycodes'][-1] += kc
  418. else:
  419. layer['keycodes'].append(kc)
  420. # The keymaps array's signature:
  421. # const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS]
  422. #
  423. # Only if we've found all 6 keywords in this specific order
  424. # can we know for sure that we are inside the keymaps array
  425. elif line[1] == 'PROGMEM' and keymap_certainty == 2:
  426. keymap_certainty = 3
  427. elif line[1] == 'keymaps' and keymap_certainty == 3:
  428. keymap_certainty = 4
  429. elif line[1] == 'MATRIX_ROWS' and keymap_certainty == 4:
  430. keymap_certainty = 5
  431. elif line[1] == 'MATRIX_COLS' and keymap_certainty == 5:
  432. keymap_certainty = 6
  433. elif line[0] is Token.Keyword:
  434. if line[1] == 'const' and keymap_certainty == 0:
  435. keymap_certainty = 1
  436. elif line[0] is Token.Keyword.Type:
  437. if line[1] == 'uint16_t' and keymap_certainty == 1:
  438. keymap_certainty = 2
  439. elif line[0] is Token.Punctuation:
  440. if line[1] in opening_braces:
  441. brace_depth += 1
  442. if is_keymap:
  443. if is_layer:
  444. # We found the beginning of a non-basic keycode
  445. is_adv_kc = True
  446. layer['keycodes'][-1] += line[1]
  447. elif line[1] == '(' and brace_depth == 2:
  448. # We found the beginning of a layer
  449. is_layer = True
  450. elif line[1] == '{' and keymap_certainty == 6:
  451. # We found the beginning of the keymaps array
  452. is_keymap = True
  453. elif line[1] in closing_braces:
  454. brace_depth -= 1
  455. if is_keymap:
  456. if is_adv_kc:
  457. layer['keycodes'][-1] += line[1]
  458. if brace_depth == 2:
  459. # We found the end of a non-basic keycode
  460. is_adv_kc = False
  461. elif line[1] == ')' and brace_depth == 1:
  462. # We found the end of a layer
  463. is_layer = False
  464. layers.append(layer)
  465. layer = dict(name=False, layout=False, keycodes=list())
  466. elif line[1] == '}' and brace_depth == 0:
  467. # We found the end of the keymaps array
  468. is_keymap = False
  469. keymap_certainty = 0
  470. elif is_adv_kc:
  471. # Advanced keycodes can contain other punctuation
  472. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  473. layer['keycodes'][-1] += line[1]
  474. elif line[0] is Token.Literal.Number.Integer and is_keymap and not is_adv_kc:
  475. # If the pre-processor finds the 'meaning' of the layer names,
  476. # they will be numbers
  477. if not layer['name']:
  478. layer['name'] = line[1]
  479. else:
  480. # We only care about
  481. # operators and such if we
  482. # are inside an advanced keycode
  483. # e.g.: MT(MOD_LCTL | MOD_LSFT, KC_ESC)
  484. if is_adv_kc:
  485. layer['keycodes'][-1] += line[1]
  486. return layers
  487. def parse_keymap_c(keymap_file, use_cpp=True):
  488. """ Parse a keymap.c file.
  489. Currently only cares about the keymaps array.
  490. Args:
  491. keymap_file: path of the keymap.c file (or '-' to use stdin)
  492. use_cpp: if True, pre-process the file with the C pre-processor
  493. Returns:
  494. a dictionary containing the parsed keymap
  495. """
  496. if not isinstance(keymap_file, (Path, str)) or keymap_file == '-':
  497. if use_cpp:
  498. keymap_file = _c_preprocess(None, sys.stdin)
  499. else:
  500. keymap_file = sys.stdin.read()
  501. else:
  502. if use_cpp:
  503. keymap_file = _c_preprocess(keymap_file)
  504. else:
  505. keymap_file = keymap_file.read_text(encoding='utf-8')
  506. keymap = dict()
  507. keymap['layers'] = _get_layers(keymap_file)
  508. return keymap
  509. def c2json(keyboard, keymap, keymap_file, use_cpp=True):
  510. """ Convert keymap.c to keymap.json
  511. Args:
  512. keyboard: The name of the keyboard
  513. keymap: The name of the keymap
  514. layout: The LAYOUT macro this keymap uses.
  515. keymap_file: path of the keymap.c file
  516. use_cpp: if True, pre-process the file with the C pre-processor
  517. Returns:
  518. a dictionary in keymap.json format
  519. """
  520. keymap_json = parse_keymap_c(keymap_file, use_cpp)
  521. dirty_layers = keymap_json.pop('layers', None)
  522. keymap_json['layers'] = list()
  523. for layer in dirty_layers:
  524. layer.pop('name')
  525. layout = layer.pop('layout')
  526. if not keymap_json.get('layout', False):
  527. keymap_json['layout'] = layout
  528. keymap_json['layers'].append(layer.pop('keycodes'))
  529. keymap_json['keyboard'] = keyboard
  530. keymap_json['keymap'] = keymap
  531. return keymap_json