keymap.py 19 KB

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