keyboard.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 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. if not qmk.path.is_keyboard(keyboard):
  108. raise ValueError(f'Invalid keyboard: {keyboard}')
  109. return keyboard
  110. def keyboard_aliases(keyboard):
  111. """Returns the list of aliases for the supplied keyboard.
  112. Includes the keyboard itself.
  113. """
  114. aliases = json_load(Path('data/mappings/keyboard_aliases.hjson'))
  115. if keyboard in aliases:
  116. keyboard = aliases[keyboard].get('target', keyboard)
  117. keyboards = set(filter(lambda k: aliases[k].get('target', '') == keyboard, aliases.keys()))
  118. keyboards.add(keyboard)
  119. keyboards = list(sorted(keyboards))
  120. return keyboards
  121. def keyboard_folder_or_all(keyboard):
  122. """Returns the actual keyboard folder.
  123. This checks aliases to resolve the actual path for a keyboard.
  124. If the supplied argument is "all", it returns an AllKeyboards object.
  125. """
  126. if keyboard == 'all':
  127. return AllKeyboards()
  128. return keyboard_folder(keyboard)
  129. def _find_name(path):
  130. """Determine the keyboard name by stripping off the base_path and filename.
  131. """
  132. return path.replace(base_path, "").rsplit(os.path.sep, 1)[0]
  133. def keyboard_completer(prefix, action, parser, parsed_args):
  134. """Returns a list of keyboards for tab completion.
  135. """
  136. return list_keyboards()
  137. @lru_cache(maxsize=None)
  138. def list_keyboards():
  139. """Returns a list of all keyboards.
  140. """
  141. # We avoid pathlib here because this is performance critical code.
  142. kb_wildcard = os.path.join(base_path, "**", 'keyboard.json')
  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. # Convert to posix paths for consistency
  146. found = map(lambda x: str(Path(x).as_posix()), found)
  147. return sorted(set(found))
  148. def config_h(keyboard):
  149. """Parses all the config.h files for a keyboard.
  150. Args:
  151. keyboard: name of the keyboard
  152. Returns:
  153. a dictionary representing the content of the entire config.h tree for a keyboard
  154. """
  155. config = {}
  156. cur_dir = Path('keyboards')
  157. keyboard = Path(keyboard)
  158. for dir in keyboard.parts:
  159. cur_dir = cur_dir / dir
  160. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  161. return config
  162. def rules_mk(keyboard):
  163. """Get a rules.mk for a keyboard
  164. Args:
  165. keyboard: name of the keyboard
  166. Returns:
  167. a dictionary representing the content of the entire rules.mk tree for a keyboard
  168. """
  169. cur_dir = Path('keyboards')
  170. keyboard = Path(keyboard)
  171. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  172. for i, dir in enumerate(keyboard.parts):
  173. cur_dir = cur_dir / dir
  174. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  175. return rules
  176. def render_layout(layout_data, render_ascii, key_labels=None):
  177. """Renders a single layout.
  178. """
  179. textpad = [array('u', ' ' * 200) for x in range(100)]
  180. style = 'ascii' if render_ascii else 'unicode'
  181. for key in layout_data:
  182. x = key.get('x', 0)
  183. y = key.get('y', 0)
  184. w = key.get('w', 1)
  185. h = key.get('h', 1)
  186. if key_labels:
  187. label = key_labels.pop(0)
  188. if label.startswith('KC_'):
  189. label = label[3:]
  190. else:
  191. label = key.get('label', '')
  192. if 'encoder' in key:
  193. render_encoder(textpad, x, y, w, h, label, style)
  194. elif x >= 0.25 and w == 1.25 and h == 2:
  195. render_key_isoenter(textpad, x, y, w, h, label, style)
  196. elif w == 1.5 and h == 2:
  197. render_key_baenter(textpad, x, y, w, h, label, style)
  198. else:
  199. render_key_rect(textpad, x, y, w, h, label, style)
  200. lines = []
  201. for line in textpad:
  202. if line.tounicode().strip():
  203. lines.append(line.tounicode().rstrip())
  204. return '\n'.join(lines)
  205. def render_layouts(info_json, render_ascii):
  206. """Renders all the layouts from an `info_json` structure.
  207. """
  208. layouts = {}
  209. for layout in info_json['layouts']:
  210. layout_data = info_json['layouts'][layout]['layout']
  211. layouts[layout] = render_layout(layout_data, render_ascii)
  212. return layouts
  213. def render_key_rect(textpad, x, y, w, h, label, style):
  214. box_chars = BOX_DRAWING_CHARACTERS[style]
  215. x = ceil(x * 4)
  216. y = ceil(y * 3)
  217. w = ceil(w * 4)
  218. h = ceil(h * 3)
  219. label_len = w - 2
  220. label_leftover = label_len - len(label)
  221. if len(label) > label_len:
  222. label = label[:label_len]
  223. label_blank = ' ' * label_len
  224. label_border = box_chars['h'] * label_len
  225. label_middle = label + ' ' * label_leftover
  226. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  227. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  228. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  229. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  230. textpad[y][x:x + w] = top_line
  231. textpad[y + 1][x:x + w] = lab_line
  232. for i in range(h - 3):
  233. textpad[y + i + 2][x:x + w] = mid_line
  234. textpad[y + h - 1][x:x + w] = bot_line
  235. def render_key_isoenter(textpad, x, y, w, h, label, style):
  236. box_chars = BOX_DRAWING_CHARACTERS[style]
  237. x = ceil(x * 4)
  238. y = ceil(y * 3)
  239. w = ceil(w * 4)
  240. h = ceil(h * 3)
  241. label_len = w - 1
  242. label_leftover = label_len - len(label)
  243. if len(label) > label_len:
  244. label = label[:label_len]
  245. label_blank = ' ' * (label_len - 1)
  246. label_border_top = box_chars['h'] * label_len
  247. label_border_bottom = box_chars['h'] * (label_len - 1)
  248. label_middle = label + ' ' * label_leftover
  249. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  250. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  251. crn_line = array('u', box_chars['bl'] + box_chars['tr'] + label_blank + box_chars['v'])
  252. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  253. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  254. textpad[y][x - 1:x + w] = top_line
  255. textpad[y + 1][x - 1:x + w] = lab_line
  256. textpad[y + 2][x - 1:x + w] = crn_line
  257. textpad[y + 3][x:x + w] = mid_line
  258. textpad[y + 4][x:x + w] = mid_line
  259. textpad[y + 5][x:x + w] = bot_line
  260. def render_key_baenter(textpad, x, y, w, h, label, style):
  261. box_chars = BOX_DRAWING_CHARACTERS[style]
  262. x = ceil(x * 4)
  263. y = ceil(y * 3)
  264. w = ceil(w * 4)
  265. h = ceil(h * 3)
  266. label_len = w + 1
  267. label_leftover = label_len - len(label)
  268. if len(label) > label_len:
  269. label = label[:label_len]
  270. label_blank = ' ' * (label_len - 3)
  271. label_border_top = box_chars['h'] * (label_len - 3)
  272. label_border_bottom = box_chars['h'] * label_len
  273. label_middle = label + ' ' * label_leftover
  274. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  275. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  276. crn_line = array('u', box_chars['tl'] + box_chars['h'] + box_chars['h'] + box_chars['br'] + label_blank + box_chars['v'])
  277. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  278. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  279. textpad[y][x:x + w] = top_line
  280. textpad[y + 1][x:x + w] = mid_line
  281. textpad[y + 2][x:x + w] = mid_line
  282. textpad[y + 3][x - 3:x + w] = crn_line
  283. textpad[y + 4][x - 3:x + w] = lab_line
  284. textpad[y + 5][x - 3:x + w] = bot_line
  285. def render_encoder(textpad, x, y, w, h, label, style):
  286. box_chars = ENC_DRAWING_CHARACTERS[style]
  287. x = ceil(x * 4)
  288. y = ceil(y * 3)
  289. w = ceil(w * 4)
  290. h = ceil(h * 3)
  291. label_len = w - 2
  292. label_leftover = label_len - len(label)
  293. if len(label) > label_len:
  294. label = label[:label_len]
  295. label_blank = ' ' * label_len
  296. label_border = box_chars['h'] * label_len
  297. label_middle = label + ' ' * label_leftover
  298. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  299. lab_line = array('u', box_chars['vl'] + label_middle + box_chars['vr'])
  300. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  301. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  302. textpad[y][x:x + w] = top_line
  303. textpad[y + 1][x:x + w] = lab_line
  304. for i in range(h - 3):
  305. textpad[y + i + 2][x:x + w] = mid_line
  306. textpad[y + h - 1][x:x + w] = bot_line