keymap.py 22 KB

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