info.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. """Keyboard information script.
  2. Compile an info.json for a particular keyboard and pretty-print it.
  3. """
  4. import sys
  5. import json
  6. from milc import cli
  7. from qmk.json_encoders import InfoJSONEncoder
  8. from qmk.constants import COL_LETTERS, ROW_LETTERS
  9. from qmk.decorators import automagic_keyboard, automagic_keymap
  10. from qmk.keyboard import keyboard_completer, keyboard_folder, render_layouts, render_layout, rules_mk
  11. from qmk.info import info_json, keymap_json
  12. from qmk.keymap import locate_keymap
  13. from qmk.path import is_keyboard
  14. UNICODE_SUPPORT = sys.stdout.encoding.lower().startswith('utf')
  15. def _strip_api_content(info_json):
  16. # Ideally this would only be added in the API pathway.
  17. info_json.pop('platform', None)
  18. info_json.pop('platform_key', None)
  19. info_json.pop('processor_type', None)
  20. info_json.pop('protocol', None)
  21. info_json.pop('config_h_features', None)
  22. info_json.pop('keymaps', None)
  23. info_json.pop('keyboard_folder', None)
  24. info_json.pop('parse_errors', None)
  25. info_json.pop('parse_warnings', None)
  26. for layout in info_json.get('layouts', {}).values():
  27. layout.pop('filename', None)
  28. layout.pop('c_macro', None)
  29. layout.pop('json_layout', None)
  30. if 'matrix_pins' in info_json:
  31. info_json.pop('matrix_size', None)
  32. for feature in ['rgb_matrix', 'led_matrix']:
  33. if info_json.get(feature, {}).get("layout", None):
  34. info_json[feature].pop('led_count', None)
  35. return info_json
  36. def show_keymap(kb_info_json, title_caps=True):
  37. """Render the keymap in ascii art.
  38. """
  39. keymap_path = locate_keymap(cli.config.info.keyboard, cli.config.info.keymap)
  40. if keymap_path and keymap_path.suffix == '.json':
  41. keymap_data = json.load(keymap_path.open(encoding='utf-8'))
  42. # cater for layout-less keymap.json
  43. if 'layout' not in keymap_data:
  44. return
  45. layout_name = keymap_data['layout']
  46. layout_name = kb_info_json.get('layout_aliases', {}).get(layout_name, layout_name) # Resolve alias names
  47. for layer_num, layer in enumerate(keymap_data['layers']):
  48. if title_caps:
  49. cli.echo('{fg_cyan}Keymap %s Layer %s{fg_reset}:', cli.config.info.keymap, layer_num)
  50. else:
  51. cli.echo('{fg_cyan}keymap.%s.layer.%s{fg_reset}:', cli.config.info.keymap, layer_num)
  52. print(render_layout(kb_info_json['layouts'][layout_name]['layout'], cli.config.info.ascii, layer))
  53. def show_layouts(kb_info_json, title_caps=True):
  54. """Render the layouts with info.json labels.
  55. """
  56. for layout_name, layout_art in render_layouts(kb_info_json, cli.config.info.ascii).items():
  57. title = f'Layout {layout_name.title()}' if title_caps else f'layouts.{layout_name}'
  58. cli.echo('{fg_cyan}%s{fg_reset}:', title)
  59. print(layout_art) # Avoid passing dirty data to cli.echo()
  60. def show_matrix(kb_info_json, title_caps=True):
  61. """Render the layout with matrix labels in ascii art.
  62. """
  63. for layout_name, layout in kb_info_json['layouts'].items():
  64. # Build our label list
  65. labels = []
  66. for key in layout['layout']:
  67. if 'matrix' in key:
  68. row = ROW_LETTERS[key['matrix'][0]]
  69. col = COL_LETTERS[key['matrix'][1]]
  70. labels.append(row + col)
  71. else:
  72. labels.append('')
  73. # Print the header
  74. if title_caps:
  75. cli.echo('{fg_blue}Matrix for "%s"{fg_reset}:', layout_name)
  76. else:
  77. cli.echo('{fg_blue}matrix_%s{fg_reset}:', layout_name)
  78. print(render_layout(kb_info_json['layouts'][layout_name]['layout'], cli.config.info.ascii, labels))
  79. def show_leds(kb_info_json, title_caps=True):
  80. """Render LED indices per key, using the keyboard's key layout geometry.
  81. We build a map from (row, col) -> LED index using rgb_matrix/led_matrix layout,
  82. then label each key with its LED index. Keys without an associated LED are left blank.
  83. """
  84. # Prefer rgb_matrix, fall back to led_matrix
  85. led_feature = None
  86. for feature in ['rgb_matrix', 'led_matrix']:
  87. if 'layout' in kb_info_json.get(feature, {}):
  88. led_feature = feature
  89. break
  90. if not led_feature:
  91. cli.echo('{fg_yellow}No rgb_matrix/led_matrix layout found to derive LED indices.{fg_reset}')
  92. return
  93. # Build mapping from matrix position -> LED indices for faster lookup later
  94. by_matrix = {}
  95. for idx, led in enumerate(kb_info_json[led_feature]['layout']):
  96. if 'matrix' in led:
  97. led_key = tuple(led.get('matrix'))
  98. by_matrix[led_key] = idx
  99. # For each keyboard layout (e.g., LAYOUT), render keys labeled with LED index (or blank)
  100. for layout_name, layout in kb_info_json['layouts'].items():
  101. labels = []
  102. for key in layout['layout']:
  103. led_key = tuple(key.get('matrix'))
  104. label = str(by_matrix[led_key]) if led_key in by_matrix else ''
  105. labels.append(label)
  106. # Header
  107. if title_caps:
  108. cli.echo('{fg_blue}LED indices for "%s"{fg_reset}:', layout_name)
  109. else:
  110. cli.echo('{fg_blue}leds_%s{fg_reset}:', layout_name)
  111. print(render_layout(kb_info_json['layouts'][layout_name]['layout'], cli.config.info.ascii, labels))
  112. def print_friendly_output(kb_info_json):
  113. """Print the info.json in a friendly text format.
  114. """
  115. cli.echo('{fg_blue}Keyboard Name{fg_reset}: %s', kb_info_json.get('keyboard_name', 'Unknown'))
  116. cli.echo('{fg_blue}Manufacturer{fg_reset}: %s', kb_info_json.get('manufacturer', 'Unknown'))
  117. if 'url' in kb_info_json:
  118. cli.echo('{fg_blue}Website{fg_reset}: %s', kb_info_json.get('url', ''))
  119. if kb_info_json.get('maintainer', 'qmk') == 'qmk':
  120. cli.echo('{fg_blue}Maintainer{fg_reset}: QMK Community')
  121. else:
  122. cli.echo('{fg_blue}Maintainer{fg_reset}: %s', kb_info_json['maintainer'])
  123. cli.echo('{fg_blue}Layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  124. cli.echo('{fg_blue}Processor{fg_reset}: %s', kb_info_json.get('processor', 'Unknown'))
  125. cli.echo('{fg_blue}Bootloader{fg_reset}: %s', kb_info_json.get('bootloader', 'Unknown'))
  126. if 'layout_aliases' in kb_info_json:
  127. aliases = [f'{key}={value}' for key, value in kb_info_json['layout_aliases'].items()]
  128. cli.echo('{fg_blue}Layout aliases:{fg_reset} %s' % (', '.join(aliases),))
  129. def print_text_output(kb_info_json):
  130. """Print the info.json in a plain text format.
  131. """
  132. for key in sorted(kb_info_json):
  133. if key == 'layouts':
  134. cli.echo('{fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  135. else:
  136. cli.echo('{fg_blue}%s{fg_reset}: %s', key, kb_info_json[key])
  137. if cli.config.info.layouts:
  138. show_layouts(kb_info_json, False)
  139. if cli.config.info.matrix:
  140. show_matrix(kb_info_json, False)
  141. if cli.config_source.info.keymap and cli.config_source.info.keymap != 'config_file':
  142. show_keymap(kb_info_json, False)
  143. def print_dotted_output(kb_info_json, prefix=''):
  144. """Print the info.json in a plain text format with dot-joined keys.
  145. """
  146. for key in sorted(kb_info_json):
  147. new_prefix = f'{prefix}.{key}' if prefix else key
  148. if key in ['parse_errors', 'parse_warnings']:
  149. continue
  150. elif key == 'layouts' and prefix == '':
  151. cli.echo('{fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  152. elif isinstance(kb_info_json[key], dict):
  153. print_dotted_output(kb_info_json[key], new_prefix)
  154. elif isinstance(kb_info_json[key], list):
  155. cli.echo('{fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, sorted(kb_info_json[key]))))
  156. else:
  157. cli.echo('{fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  158. def print_parsed_rules_mk(keyboard_name):
  159. rules = rules_mk(keyboard_name)
  160. for k in sorted(rules.keys()):
  161. print('%s = %s' % (k, rules[k]))
  162. return
  163. @cli.argument('-kb', '--keyboard', type=keyboard_folder, completer=keyboard_completer, help='Keyboard to show info for.')
  164. @cli.argument('-km', '--keymap', help='Keymap to show info for (Optional).')
  165. @cli.argument('-l', '--layouts', action='store_true', help='Render the layouts.')
  166. @cli.argument('-m', '--matrix', action='store_true', help='Render the layouts with matrix information.')
  167. @cli.argument('-L', '--leds', action='store_true', help='Render the LED layout with LED indices (rgb_matrix/led_matrix).')
  168. @cli.argument('-f', '--format', default='friendly', arg_only=True, help='Format to display the data in (friendly, text, json) (Default: friendly).')
  169. @cli.argument('--ascii', action='store_true', default=not UNICODE_SUPPORT, help='Render layout box drawings in ASCII only.')
  170. @cli.argument('-r', '--rules-mk', action='store_true', help='Render the parsed values of the keyboard\'s rules.mk file.')
  171. @cli.argument('-a', '--api', action='store_true', help='Show fully processed info intended for API consumption.')
  172. @cli.subcommand('Keyboard information.')
  173. @automagic_keyboard
  174. @automagic_keymap
  175. def info(cli):
  176. """Compile an info.json for a particular keyboard and pretty-print it.
  177. """
  178. # Determine our keyboard(s)
  179. if not cli.config.info.keyboard:
  180. cli.log.error('Missing parameter: --keyboard')
  181. cli.subcommands['info'].print_help()
  182. return False
  183. if not is_keyboard(cli.config.info.keyboard):
  184. cli.log.error('Invalid keyboard: "%s"', cli.config.info.keyboard)
  185. return False
  186. if bool(cli.args.rules_mk):
  187. print_parsed_rules_mk(cli.config.info.keyboard)
  188. return False
  189. # default keymap stored in config file should be ignored
  190. if cli.config_source.info.keymap == 'config_file':
  191. cli.config_source.info.keymap = None
  192. # Build the info.json file
  193. if cli.config.info.keymap:
  194. kb_info_json = keymap_json(cli.config.info.keyboard, cli.config.info.keymap)
  195. else:
  196. kb_info_json = info_json(cli.config.info.keyboard)
  197. if not cli.args.api:
  198. kb_info_json = _strip_api_content(kb_info_json)
  199. # Output in the requested format
  200. if cli.args.format == 'json':
  201. print(json.dumps(kb_info_json, cls=InfoJSONEncoder, sort_keys=True))
  202. return True
  203. elif cli.args.format == 'text':
  204. print_dotted_output(kb_info_json)
  205. title_caps = False
  206. elif cli.args.format == 'friendly':
  207. print_friendly_output(kb_info_json)
  208. title_caps = True
  209. else:
  210. cli.log.error('Unknown format: %s', cli.args.format)
  211. return False
  212. # Output requested extras
  213. if cli.config.info.layouts:
  214. show_layouts(kb_info_json, title_caps)
  215. if cli.config.info.matrix:
  216. show_matrix(kb_info_json, title_caps)
  217. if cli.config.info.leds:
  218. show_leds(kb_info_json, title_caps)
  219. if cli.config.info.keymap:
  220. show_keymap(kb_info_json, title_caps)