keyboard.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 rules.mk.
  132. """
  133. return path.replace(base_path, "").replace(os.path.sep + "rules.mk", "")
  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. kb_wildcard = os.path.join(base_path, "**", "rules.mk")
  143. paths = [path for path in glob(kb_wildcard, recursive=True) if os.path.sep + 'keymaps' + os.path.sep not in path]
  144. found = map(_find_name, paths)
  145. if resolve_defaults:
  146. found = map(resolve_keyboard, found)
  147. return sorted(set(found))
  148. @lru_cache(maxsize=None)
  149. def resolve_keyboard(keyboard):
  150. cur_dir = Path('keyboards')
  151. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  152. while 'DEFAULT_FOLDER' in rules and keyboard != rules['DEFAULT_FOLDER']:
  153. keyboard = rules['DEFAULT_FOLDER']
  154. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  155. return keyboard
  156. def config_h(keyboard):
  157. """Parses all the config.h files for a keyboard.
  158. Args:
  159. keyboard: name of the keyboard
  160. Returns:
  161. a dictionary representing the content of the entire config.h tree for a keyboard
  162. """
  163. config = {}
  164. cur_dir = Path('keyboards')
  165. keyboard = Path(resolve_keyboard(keyboard))
  166. for dir in keyboard.parts:
  167. cur_dir = cur_dir / dir
  168. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  169. return config
  170. def rules_mk(keyboard):
  171. """Get a rules.mk for a keyboard
  172. Args:
  173. keyboard: name of the keyboard
  174. Returns:
  175. a dictionary representing the content of the entire rules.mk tree for a keyboard
  176. """
  177. cur_dir = Path('keyboards')
  178. keyboard = Path(resolve_keyboard(keyboard))
  179. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  180. for i, dir in enumerate(keyboard.parts):
  181. cur_dir = cur_dir / dir
  182. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  183. return rules
  184. def render_layout(layout_data, render_ascii, key_labels=None):
  185. """Renders a single layout.
  186. """
  187. textpad = [array('u', ' ' * 200) for x in range(100)]
  188. style = 'ascii' if render_ascii else 'unicode'
  189. for key in layout_data:
  190. x = key.get('x', 0)
  191. y = key.get('y', 0)
  192. w = key.get('w', 1)
  193. h = key.get('h', 1)
  194. if key_labels:
  195. label = key_labels.pop(0)
  196. if label.startswith('KC_'):
  197. label = label[3:]
  198. else:
  199. label = key.get('label', '')
  200. if 'encoder' in key:
  201. render_encoder(textpad, x, y, w, h, label, style)
  202. elif x >= 0.25 and w == 1.25 and h == 2:
  203. render_key_isoenter(textpad, x, y, w, h, label, style)
  204. elif w == 1.5 and h == 2:
  205. render_key_baenter(textpad, x, y, w, h, label, style)
  206. else:
  207. render_key_rect(textpad, x, y, w, h, label, style)
  208. lines = []
  209. for line in textpad:
  210. if line.tounicode().strip():
  211. lines.append(line.tounicode().rstrip())
  212. return '\n'.join(lines)
  213. def render_layouts(info_json, render_ascii):
  214. """Renders all the layouts from an `info_json` structure.
  215. """
  216. layouts = {}
  217. for layout in info_json['layouts']:
  218. layout_data = info_json['layouts'][layout]['layout']
  219. layouts[layout] = render_layout(layout_data, render_ascii)
  220. return layouts
  221. def render_key_rect(textpad, x, y, w, h, label, style):
  222. box_chars = BOX_DRAWING_CHARACTERS[style]
  223. x = ceil(x * 4)
  224. y = ceil(y * 3)
  225. w = ceil(w * 4)
  226. h = ceil(h * 3)
  227. label_len = w - 2
  228. label_leftover = label_len - len(label)
  229. if len(label) > label_len:
  230. label = label[:label_len]
  231. label_blank = ' ' * label_len
  232. label_border = box_chars['h'] * label_len
  233. label_middle = label + ' ' * label_leftover
  234. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  235. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  236. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  237. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  238. textpad[y][x:x + w] = top_line
  239. textpad[y + 1][x:x + w] = lab_line
  240. for i in range(h - 3):
  241. textpad[y + i + 2][x:x + w] = mid_line
  242. textpad[y + h - 1][x:x + w] = bot_line
  243. def render_key_isoenter(textpad, x, y, w, h, label, style):
  244. box_chars = BOX_DRAWING_CHARACTERS[style]
  245. x = ceil(x * 4)
  246. y = ceil(y * 3)
  247. w = ceil(w * 4)
  248. h = ceil(h * 3)
  249. label_len = w - 1
  250. label_leftover = label_len - len(label)
  251. if len(label) > label_len:
  252. label = label[:label_len]
  253. label_blank = ' ' * (label_len - 1)
  254. label_border_top = box_chars['h'] * label_len
  255. label_border_bottom = box_chars['h'] * (label_len - 1)
  256. label_middle = label + ' ' * label_leftover
  257. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  258. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  259. crn_line = array('u', box_chars['bl'] + box_chars['tr'] + label_blank + box_chars['v'])
  260. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  261. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  262. textpad[y][x - 1:x + w] = top_line
  263. textpad[y + 1][x - 1:x + w] = lab_line
  264. textpad[y + 2][x - 1:x + w] = crn_line
  265. textpad[y + 3][x:x + w] = mid_line
  266. textpad[y + 4][x:x + w] = mid_line
  267. textpad[y + 5][x:x + w] = bot_line
  268. def render_key_baenter(textpad, x, y, w, h, label, style):
  269. box_chars = BOX_DRAWING_CHARACTERS[style]
  270. x = ceil(x * 4)
  271. y = ceil(y * 3)
  272. w = ceil(w * 4)
  273. h = ceil(h * 3)
  274. label_len = w + 1
  275. label_leftover = label_len - len(label)
  276. if len(label) > label_len:
  277. label = label[:label_len]
  278. label_blank = ' ' * (label_len - 3)
  279. label_border_top = box_chars['h'] * (label_len - 3)
  280. label_border_bottom = box_chars['h'] * label_len
  281. label_middle = label + ' ' * label_leftover
  282. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  283. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  284. crn_line = array('u', box_chars['tl'] + box_chars['h'] + box_chars['h'] + box_chars['br'] + label_blank + box_chars['v'])
  285. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  286. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  287. textpad[y][x:x + w] = top_line
  288. textpad[y + 1][x:x + w] = mid_line
  289. textpad[y + 2][x:x + w] = mid_line
  290. textpad[y + 3][x - 3:x + w] = crn_line
  291. textpad[y + 4][x - 3:x + w] = lab_line
  292. textpad[y + 5][x - 3:x + w] = bot_line
  293. def render_encoder(textpad, x, y, w, h, label, style):
  294. box_chars = ENC_DRAWING_CHARACTERS[style]
  295. x = ceil(x * 4)
  296. y = ceil(y * 3)
  297. w = ceil(w * 4)
  298. h = ceil(h * 3)
  299. label_len = w - 2
  300. label_leftover = label_len - len(label)
  301. if len(label) > label_len:
  302. label = label[:label_len]
  303. label_blank = ' ' * label_len
  304. label_border = box_chars['h'] * label_len
  305. label_middle = label + ' ' * label_leftover
  306. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  307. lab_line = array('u', box_chars['vl'] + label_middle + box_chars['vr'])
  308. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  309. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  310. textpad[y][x:x + w] = top_line
  311. textpad[y + 1][x:x + w] = lab_line
  312. for i in range(h - 3):
  313. textpad[y + i + 2][x:x + w] = mid_line
  314. textpad[y + h - 1][x:x + w] = bot_line