You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

557 lines
18 KiB

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