1
0

keymap.py 18 KB

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