keyboard.py 11 KB

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