keyboard.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. """Functions that help us work with keyboards.
  2. """
  3. from array import array
  4. from functools import lru_cache
  5. from math import ceil
  6. from pathlib import Path
  7. import os
  8. from glob import glob
  9. import qmk.path
  10. from qmk.c_parse import parse_config_h_file
  11. from qmk.json_schema import json_load
  12. from qmk.makefile import parse_rules_mk_file
  13. BOX_DRAWING_CHARACTERS = {
  14. "unicode": {
  15. "tl": "┌",
  16. "tr": "┐",
  17. "bl": "└",
  18. "br": "┘",
  19. "v": "│",
  20. "h": "─",
  21. },
  22. "ascii": {
  23. "tl": " ",
  24. "tr": " ",
  25. "bl": "|",
  26. "br": "|",
  27. "v": "|",
  28. "h": "_",
  29. },
  30. }
  31. ENC_DRAWING_CHARACTERS = {
  32. "unicode": {
  33. "tl": "╭",
  34. "tr": "╮",
  35. "bl": "╰",
  36. "br": "╯",
  37. "vl": "▲",
  38. "vr": "▼",
  39. "v": "│",
  40. "h": "─",
  41. },
  42. "ascii": {
  43. "tl": " ",
  44. "tr": " ",
  45. "bl": "\\",
  46. "br": "/",
  47. "v": "|",
  48. "vl": "/",
  49. "vr": "\\",
  50. "h": "_",
  51. },
  52. }
  53. class AllKeyboards:
  54. """Represents all keyboards.
  55. """
  56. def __str__(self):
  57. return 'all'
  58. def __repr__(self):
  59. return 'all'
  60. def __eq__(self, other):
  61. return isinstance(other, AllKeyboards)
  62. base_path = os.path.join(os.getcwd(), "keyboards") + os.path.sep
  63. @lru_cache(maxsize=1)
  64. def keyboard_alias_definitions():
  65. return json_load(Path('data/mappings/keyboard_aliases.hjson'))
  66. def is_all_keyboards(keyboard):
  67. """Returns True if the keyboard is an AllKeyboards object.
  68. """
  69. if isinstance(keyboard, str):
  70. return (keyboard == 'all')
  71. return isinstance(keyboard, AllKeyboards)
  72. def find_keyboard_from_dir():
  73. """Returns a keyboard name based on the user's current directory.
  74. """
  75. relative_cwd = qmk.path.under_qmk_userspace()
  76. if not relative_cwd:
  77. relative_cwd = qmk.path.under_qmk_firmware()
  78. if relative_cwd and len(relative_cwd.parts) > 1 and relative_cwd.parts[0] == 'keyboards':
  79. # Attempt to extract the keyboard name from the current directory
  80. current_path = Path('/'.join(relative_cwd.parts[1:]))
  81. if 'keymaps' in current_path.parts:
  82. # Strip current_path of anything after `keymaps`
  83. keymap_index = len(current_path.parts) - current_path.parts.index('keymaps') - 1
  84. current_path = current_path.parents[keymap_index]
  85. if qmk.path.is_keyboard(current_path):
  86. return str(current_path)
  87. def find_readme(keyboard):
  88. """Returns the readme for this keyboard.
  89. """
  90. cur_dir = qmk.path.keyboard(keyboard)
  91. keyboards_dir = Path('keyboards')
  92. while not (cur_dir / 'readme.md').exists():
  93. if cur_dir == keyboards_dir:
  94. return None
  95. cur_dir = cur_dir.parent
  96. return cur_dir / 'readme.md'
  97. def keyboard_folder(keyboard):
  98. """Returns the actual keyboard folder.
  99. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  100. """
  101. aliases = keyboard_alias_definitions()
  102. while keyboard in aliases:
  103. last_keyboard = keyboard
  104. keyboard = aliases[keyboard].get('target', keyboard)
  105. if keyboard == last_keyboard:
  106. break
  107. keyboard = resolve_keyboard(keyboard)
  108. if not qmk.path.is_keyboard(keyboard):
  109. raise ValueError(f'Invalid keyboard: {keyboard}')
  110. return keyboard
  111. def keyboard_aliases(keyboard):
  112. """Returns the list of aliases for the supplied keyboard.
  113. Includes the keyboard itself.
  114. """
  115. aliases = json_load(Path('data/mappings/keyboard_aliases.hjson'))
  116. if keyboard in aliases:
  117. keyboard = aliases[keyboard].get('target', keyboard)
  118. keyboards = set(filter(lambda k: aliases[k].get('target', '') == keyboard, aliases.keys()))
  119. keyboards.add(keyboard)
  120. keyboards = list(sorted(keyboards))
  121. return keyboards
  122. def keyboard_folder_or_all(keyboard):
  123. """Returns the actual keyboard folder.
  124. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  125. If the supplied argument is "all", it returns an AllKeyboards object.
  126. """
  127. if keyboard == 'all':
  128. return AllKeyboards()
  129. return keyboard_folder(keyboard)
  130. def _find_name(path):
  131. """Determine the keyboard name by stripping off the base_path and filename.
  132. """
  133. return path.replace(base_path, "").rsplit(os.path.sep, 1)[0]
  134. def keyboard_completer(prefix, action, parser, parsed_args):
  135. """Returns a list of keyboards for tab completion.
  136. """
  137. return list_keyboards()
  138. def list_keyboards(resolve_defaults=True):
  139. """Returns a list of all keyboards - optionally processing any DEFAULT_FOLDER.
  140. """
  141. # We avoid pathlib here because this is performance critical code.
  142. paths = []
  143. for marker in ['rules.mk', 'keyboard.json']:
  144. kb_wildcard = os.path.join(base_path, "**", marker)
  145. paths += [path for path in glob(kb_wildcard, recursive=True) if os.path.sep + 'keymaps' + os.path.sep not in path]
  146. found = map(_find_name, paths)
  147. if resolve_defaults:
  148. found = map(resolve_keyboard, found)
  149. return sorted(set(found))
  150. @lru_cache(maxsize=None)
  151. def resolve_keyboard(keyboard):
  152. cur_dir = Path('keyboards')
  153. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  154. while 'DEFAULT_FOLDER' in rules and keyboard != rules['DEFAULT_FOLDER']:
  155. keyboard = rules['DEFAULT_FOLDER']
  156. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  157. return keyboard
  158. def config_h(keyboard):
  159. """Parses all the config.h files for a keyboard.
  160. Args:
  161. keyboard: name of the keyboard
  162. Returns:
  163. a dictionary representing the content of the entire config.h tree for a keyboard
  164. """
  165. config = {}
  166. cur_dir = Path('keyboards')
  167. keyboard = Path(resolve_keyboard(keyboard))
  168. for dir in keyboard.parts:
  169. cur_dir = cur_dir / dir
  170. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  171. return config
  172. def rules_mk(keyboard):
  173. """Get a rules.mk for a keyboard
  174. Args:
  175. keyboard: name of the keyboard
  176. Returns:
  177. a dictionary representing the content of the entire rules.mk tree for a keyboard
  178. """
  179. cur_dir = Path('keyboards')
  180. keyboard = Path(resolve_keyboard(keyboard))
  181. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  182. for i, dir in enumerate(keyboard.parts):
  183. cur_dir = cur_dir / dir
  184. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  185. return rules
  186. def render_layout(layout_data, render_ascii, key_labels=None):
  187. """Renders a single layout.
  188. """
  189. textpad = [array('u', ' ' * 200) for x in range(100)]
  190. style = 'ascii' if render_ascii else 'unicode'
  191. for key in layout_data:
  192. x = key.get('x', 0)
  193. y = key.get('y', 0)
  194. w = key.get('w', 1)
  195. h = key.get('h', 1)
  196. if key_labels:
  197. label = key_labels.pop(0)
  198. if label.startswith('KC_'):
  199. label = label[3:]
  200. else:
  201. label = key.get('label', '')
  202. if 'encoder' in key:
  203. render_encoder(textpad, x, y, w, h, label, style)
  204. elif x >= 0.25 and w == 1.25 and h == 2:
  205. render_key_isoenter(textpad, x, y, w, h, label, style)
  206. elif w == 1.5 and h == 2:
  207. render_key_baenter(textpad, x, y, w, h, label, style)
  208. else:
  209. render_key_rect(textpad, x, y, w, h, label, style)
  210. lines = []
  211. for line in textpad:
  212. if line.tounicode().strip():
  213. lines.append(line.tounicode().rstrip())
  214. return '\n'.join(lines)
  215. def render_layouts(info_json, render_ascii):
  216. """Renders all the layouts from an `info_json` structure.
  217. """
  218. layouts = {}
  219. for layout in info_json['layouts']:
  220. layout_data = info_json['layouts'][layout]['layout']
  221. layouts[layout] = render_layout(layout_data, render_ascii)
  222. return layouts
  223. def render_key_rect(textpad, x, y, w, h, label, style):
  224. box_chars = BOX_DRAWING_CHARACTERS[style]
  225. x = ceil(x * 4)
  226. y = ceil(y * 3)
  227. w = ceil(w * 4)
  228. h = ceil(h * 3)
  229. label_len = w - 2
  230. label_leftover = label_len - len(label)
  231. if len(label) > label_len:
  232. label = label[:label_len]
  233. label_blank = ' ' * label_len
  234. label_border = box_chars['h'] * label_len
  235. label_middle = label + ' ' * label_leftover
  236. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  237. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  238. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  239. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  240. textpad[y][x:x + w] = top_line
  241. textpad[y + 1][x:x + w] = lab_line
  242. for i in range(h - 3):
  243. textpad[y + i + 2][x:x + w] = mid_line
  244. textpad[y + h - 1][x:x + w] = bot_line
  245. def render_key_isoenter(textpad, x, y, w, h, label, style):
  246. box_chars = BOX_DRAWING_CHARACTERS[style]
  247. x = ceil(x * 4)
  248. y = ceil(y * 3)
  249. w = ceil(w * 4)
  250. h = ceil(h * 3)
  251. label_len = w - 1
  252. label_leftover = label_len - len(label)
  253. if len(label) > label_len:
  254. label = label[:label_len]
  255. label_blank = ' ' * (label_len - 1)
  256. label_border_top = box_chars['h'] * label_len
  257. label_border_bottom = box_chars['h'] * (label_len - 1)
  258. label_middle = label + ' ' * label_leftover
  259. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  260. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  261. crn_line = array('u', box_chars['bl'] + box_chars['tr'] + label_blank + box_chars['v'])
  262. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  263. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  264. textpad[y][x - 1:x + w] = top_line
  265. textpad[y + 1][x - 1:x + w] = lab_line
  266. textpad[y + 2][x - 1:x + w] = crn_line
  267. textpad[y + 3][x:x + w] = mid_line
  268. textpad[y + 4][x:x + w] = mid_line
  269. textpad[y + 5][x:x + w] = bot_line
  270. def render_key_baenter(textpad, x, y, w, h, label, style):
  271. box_chars = BOX_DRAWING_CHARACTERS[style]
  272. x = ceil(x * 4)
  273. y = ceil(y * 3)
  274. w = ceil(w * 4)
  275. h = ceil(h * 3)
  276. label_len = w + 1
  277. label_leftover = label_len - len(label)
  278. if len(label) > label_len:
  279. label = label[:label_len]
  280. label_blank = ' ' * (label_len - 3)
  281. label_border_top = box_chars['h'] * (label_len - 3)
  282. label_border_bottom = box_chars['h'] * label_len
  283. label_middle = label + ' ' * label_leftover
  284. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  285. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  286. crn_line = array('u', box_chars['tl'] + box_chars['h'] + box_chars['h'] + box_chars['br'] + label_blank + box_chars['v'])
  287. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  288. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  289. textpad[y][x:x + w] = top_line
  290. textpad[y + 1][x:x + w] = mid_line
  291. textpad[y + 2][x:x + w] = mid_line
  292. textpad[y + 3][x - 3:x + w] = crn_line
  293. textpad[y + 4][x - 3:x + w] = lab_line
  294. textpad[y + 5][x - 3:x + w] = bot_line
  295. def render_encoder(textpad, x, y, w, h, label, style):
  296. box_chars = ENC_DRAWING_CHARACTERS[style]
  297. x = ceil(x * 4)
  298. y = ceil(y * 3)
  299. w = ceil(w * 4)
  300. h = ceil(h * 3)
  301. label_len = w - 2
  302. label_leftover = label_len - len(label)
  303. if len(label) > label_len:
  304. label = label[:label_len]
  305. label_blank = ' ' * label_len
  306. label_border = box_chars['h'] * label_len
  307. label_middle = label + ' ' * label_leftover
  308. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  309. lab_line = array('u', box_chars['vl'] + label_middle + box_chars['vr'])
  310. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  311. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  312. textpad[y][x:x + w] = top_line
  313. textpad[y + 1][x:x + w] = lab_line
  314. for i in range(h - 3):
  315. textpad[y + i + 2][x:x + w] = mid_line
  316. textpad[y + h - 1][x:x + w] = bot_line