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.

205 lines
6.0 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(set(map(resolve_keyboard, map(_find_name, paths))))
  73. def resolve_keyboard(keyboard):
  74. cur_dir = Path('keyboards')
  75. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  76. while 'DEFAULT_FOLDER' in rules and keyboard != rules['DEFAULT_FOLDER']:
  77. keyboard = rules['DEFAULT_FOLDER']
  78. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  79. return keyboard
  80. def config_h(keyboard):
  81. """Parses all the config.h files for a keyboard.
  82. Args:
  83. keyboard: name of the keyboard
  84. Returns:
  85. a dictionary representing the content of the entire config.h tree for a keyboard
  86. """
  87. config = {}
  88. cur_dir = Path('keyboards')
  89. keyboard = Path(resolve_keyboard(keyboard))
  90. for dir in keyboard.parts:
  91. cur_dir = cur_dir / dir
  92. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  93. return config
  94. def rules_mk(keyboard):
  95. """Get a rules.mk for a keyboard
  96. Args:
  97. keyboard: name of the keyboard
  98. Returns:
  99. a dictionary representing the content of the entire rules.mk tree for a keyboard
  100. """
  101. cur_dir = Path('keyboards')
  102. keyboard = Path(resolve_keyboard(keyboard))
  103. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  104. for i, dir in enumerate(keyboard.parts):
  105. cur_dir = cur_dir / dir
  106. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  107. return rules
  108. def render_layout(layout_data, render_ascii, key_labels=None):
  109. """Renders a single layout.
  110. """
  111. textpad = [array('u', ' ' * 200) for x in range(50)]
  112. style = 'ascii' if render_ascii else 'unicode'
  113. box_chars = BOX_DRAWING_CHARACTERS[style]
  114. for key in layout_data:
  115. x = ceil(key.get('x', 0) * 4)
  116. y = ceil(key.get('y', 0) * 3)
  117. w = ceil(key.get('w', 1) * 4)
  118. h = ceil(key.get('h', 1) * 3)
  119. if key_labels:
  120. label = key_labels.pop(0)
  121. if label.startswith('KC_'):
  122. label = label[3:]
  123. else:
  124. label = key.get('label', '')
  125. label_len = w - 2
  126. label_leftover = label_len - len(label)
  127. if len(label) > label_len:
  128. label = label[:label_len]
  129. label_blank = ' ' * label_len
  130. label_border = box_chars['h'] * label_len
  131. label_middle = label + ' '*label_leftover # noqa: yapf insists there be no whitespace around *
  132. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  133. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  134. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  135. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  136. textpad[y][x:x + w] = top_line
  137. textpad[y + 1][x:x + w] = lab_line
  138. for i in range(h - 3):
  139. textpad[y + i + 2][x:x + w] = mid_line
  140. textpad[y + h - 1][x:x + w] = bot_line
  141. lines = []
  142. for line in textpad:
  143. if line.tounicode().strip():
  144. lines.append(line.tounicode().rstrip())
  145. return '\n'.join(lines)
  146. def render_layouts(info_json, render_ascii):
  147. """Renders all the layouts from an `info_json` structure.
  148. """
  149. layouts = {}
  150. for layout in info_json['layouts']:
  151. layout_data = info_json['layouts'][layout]['layout']
  152. layouts[layout] = render_layout(layout_data, render_ascii)
  153. return layouts