keyboard.py 11 KB

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