keymap.py 26 KB

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