keyboard.py 11 KB

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