1
0

keymap.py 25 KB

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