You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
5.8 KiB

  1. """Functions that help us work with keyboards.
  2. """
  3. from array import array
  4. from math import ceil
  5. from pathlib import Path
  6. import os
  7. from glob import glob
  8. from qmk.c_parse import parse_config_h_file
  9. from qmk.json_schema import json_load
  10. from qmk.makefile import parse_rules_mk_file
  11. from qmk.path import is_keyboard, under_qmk_firmware
  12. BOX_DRAWING_CHARACTERS = {
  13. "unicode": {
  14. "tl": "",
  15. "tr": "",
  16. "bl": "",
  17. "br": "",
  18. "v": "",
  19. "h": "",
  20. },
  21. "ascii": {
  22. "tl": " ",
  23. "tr": " ",
  24. "bl": "|",
  25. "br": "|",
  26. "v": "|",
  27. "h": "_",
  28. },
  29. }
  30. base_path = os.path.join(os.getcwd(), "keyboards") + os.path.sep
  31. def find_keyboard_from_dir():
  32. """Returns a keyboard name based on the user's current directory.
  33. """
  34. relative_cwd = under_qmk_firmware()
  35. if relative_cwd and len(relative_cwd.parts) > 1 and relative_cwd.parts[0] == 'keyboards':
  36. # Attempt to extract the keyboard name from the current directory
  37. current_path = Path('/'.join(relative_cwd.parts[1:]))
  38. if 'keymaps' in current_path.parts:
  39. # Strip current_path of anything after `keymaps`
  40. keymap_index = len(current_path.parts) - current_path.parts.index('keymaps') - 1
  41. current_path = current_path.parents[keymap_index]
  42. if is_keyboard(current_path):
  43. return str(current_path)
  44. def keyboard_folder(keyboard):
  45. """Returns the actual keyboard folder.
  46. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  47. """
  48. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  49. if keyboard in aliases:
  50. keyboard = aliases[keyboard].get('target', keyboard)
  51. rules_mk_file = Path(base_path, keyboard, 'rules.mk')
  52. if rules_mk_file.exists():
  53. rules_mk = parse_rules_mk_file(rules_mk_file)
  54. keyboard = rules_mk.get('DEFAULT_FOLDER', keyboard)
  55. if not is_keyboard(keyboard):
  56. raise ValueError(f'Invalid keyboard: {keyboard}')
  57. return keyboard
  58. def _find_name(path):
  59. """Determine the keyboard name by stripping off the base_path and rules.mk.
  60. """
  61. return path.replace(base_path, "").replace(os.path.sep + "rules.mk", "")
  62. def keyboard_completer(prefix, action, parser, parsed_args):
  63. """Returns a list of keyboards for tab completion.
  64. """
  65. return list_keyboards()
  66. def list_keyboards():
  67. """Returns a list of all keyboards.
  68. """
  69. # We avoid pathlib here because this is performance critical code.
  70. kb_wildcard = os.path.join(base_path, "**", "rules.mk")
  71. paths = [path for path in glob(kb_wildcard, recursive=True) if 'keymaps' not in path]
  72. return sorted(map(_find_name, paths))
  73. def config_h(keyboard):
  74. """Parses all the config.h files for a keyboard.
  75. Args:
  76. keyboard: name of the keyboard
  77. Returns:
  78. a dictionary representing the content of the entire config.h tree for a keyboard
  79. """
  80. config = {}
  81. cur_dir = Path('keyboards')
  82. rules = rules_mk(keyboard)
  83. keyboard = Path(rules['DEFAULT_FOLDER'] if 'DEFAULT_FOLDER' in rules else keyboard)
  84. for dir in keyboard.parts:
  85. cur_dir = cur_dir / dir
  86. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  87. return config
  88. def rules_mk(keyboard):
  89. """Get a rules.mk for a keyboard
  90. Args:
  91. keyboard: name of the keyboard
  92. Returns:
  93. a dictionary representing the content of the entire rules.mk tree for a keyboard
  94. """
  95. keyboard = Path(keyboard)
  96. cur_dir = Path('keyboards')
  97. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  98. if 'DEFAULT_FOLDER' in rules:
  99. keyboard = Path(rules['DEFAULT_FOLDER'])
  100. for i, dir in enumerate(keyboard.parts):
  101. cur_dir = cur_dir / dir
  102. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  103. return rules
  104. def render_layout(layout_data, render_ascii, key_labels=None):
  105. """Renders a single layout.
  106. """
  107. textpad = [array('u', ' ' * 200) for x in range(50)]
  108. style = 'ascii' if render_ascii else 'unicode'
  109. box_chars = BOX_DRAWING_CHARACTERS[style]
  110. for key in layout_data:
  111. x = ceil(key.get('x', 0) * 4)
  112. y = ceil(key.get('y', 0) * 3)
  113. w = ceil(key.get('w', 1) * 4)
  114. h = ceil(key.get('h', 1) * 3)
  115. if key_labels:
  116. label = key_labels.pop(0)
  117. if label.startswith('KC_'):
  118. label = label[3:]
  119. else:
  120. label = key.get('label', '')
  121. label_len = w - 2
  122. label_leftover = label_len - len(label)
  123. if len(label) > label_len:
  124. label = label[:label_len]
  125. label_blank = ' ' * label_len
  126. label_border = box_chars['h'] * label_len
  127. label_middle = label + ' '*label_leftover # noqa: yapf insists there be no whitespace around *
  128. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  129. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  130. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  131. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  132. textpad[y][x:x + w] = top_line
  133. textpad[y + 1][x:x + w] = lab_line
  134. for i in range(h - 3):
  135. textpad[y + i + 2][x:x + w] = mid_line
  136. textpad[y + h - 1][x:x + w] = bot_line
  137. lines = []
  138. for line in textpad:
  139. if line.tounicode().strip():
  140. lines.append(line.tounicode().rstrip())
  141. return '\n'.join(lines)
  142. def render_layouts(info_json, render_ascii):
  143. """Renders all the layouts from an `info_json` structure.
  144. """
  145. layouts = {}
  146. for layout in info_json['layouts']:
  147. layout_data = info_json['layouts'][layout]['layout']
  148. layouts[layout] = render_layout(layout_data, render_ascii)
  149. return layouts