logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

keymap.py (24005B)


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