info.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. return info_json
  33. def show_keymap(kb_info_json, title_caps=True):
  34. """Render the keymap in ascii art.
  35. """
  36. keymap_path = locate_keymap(cli.config.info.keyboard, cli.config.info.keymap)
  37. if keymap_path and keymap_path.suffix == '.json':
  38. keymap_data = json.load(keymap_path.open(encoding='utf-8'))
  39. layout_name = keymap_data['layout']
  40. layout_name = kb_info_json.get('layout_aliases', {}).get(layout_name, layout_name) # Resolve alias names
  41. for layer_num, layer in enumerate(keymap_data['layers']):
  42. if title_caps:
  43. cli.echo('{fg_cyan}Keymap %s Layer %s{fg_reset}:', cli.config.info.keymap, layer_num)
  44. else:
  45. cli.echo('{fg_cyan}keymap.%s.layer.%s{fg_reset}:', cli.config.info.keymap, layer_num)
  46. print(render_layout(kb_info_json['layouts'][layout_name]['layout'], cli.config.info.ascii, layer))
  47. def show_layouts(kb_info_json, title_caps=True):
  48. """Render the layouts with info.json labels.
  49. """
  50. for layout_name, layout_art in render_layouts(kb_info_json, cli.config.info.ascii).items():
  51. title = f'Layout {layout_name.title()}' if title_caps else f'layouts.{layout_name}'
  52. cli.echo('{fg_cyan}%s{fg_reset}:', title)
  53. print(layout_art) # Avoid passing dirty data to cli.echo()
  54. def show_matrix(kb_info_json, title_caps=True):
  55. """Render the layout with matrix labels in ascii art.
  56. """
  57. for layout_name, layout in kb_info_json['layouts'].items():
  58. # Build our label list
  59. labels = []
  60. for key in layout['layout']:
  61. if 'matrix' in key:
  62. row = ROW_LETTERS[key['matrix'][0]]
  63. col = COL_LETTERS[key['matrix'][1]]
  64. labels.append(row + col)
  65. else:
  66. labels.append('')
  67. # Print the header
  68. if title_caps:
  69. cli.echo('{fg_blue}Matrix for "%s"{fg_reset}:', layout_name)
  70. else:
  71. cli.echo('{fg_blue}matrix_%s{fg_reset}:', layout_name)
  72. print(render_layout(kb_info_json['layouts'][layout_name]['layout'], cli.config.info.ascii, labels))
  73. def print_friendly_output(kb_info_json):
  74. """Print the info.json in a friendly text format.
  75. """
  76. cli.echo('{fg_blue}Keyboard Name{fg_reset}: %s', kb_info_json.get('keyboard_name', 'Unknown'))
  77. cli.echo('{fg_blue}Manufacturer{fg_reset}: %s', kb_info_json.get('manufacturer', 'Unknown'))
  78. if 'url' in kb_info_json:
  79. cli.echo('{fg_blue}Website{fg_reset}: %s', kb_info_json.get('url', ''))
  80. if kb_info_json.get('maintainer', 'qmk') == 'qmk':
  81. cli.echo('{fg_blue}Maintainer{fg_reset}: QMK Community')
  82. else:
  83. cli.echo('{fg_blue}Maintainer{fg_reset}: %s', kb_info_json['maintainer'])
  84. cli.echo('{fg_blue}Layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  85. cli.echo('{fg_blue}Processor{fg_reset}: %s', kb_info_json.get('processor', 'Unknown'))
  86. cli.echo('{fg_blue}Bootloader{fg_reset}: %s', kb_info_json.get('bootloader', 'Unknown'))
  87. if 'layout_aliases' in kb_info_json:
  88. aliases = [f'{key}={value}' for key, value in kb_info_json['layout_aliases'].items()]
  89. cli.echo('{fg_blue}Layout aliases:{fg_reset} %s' % (', '.join(aliases),))
  90. def print_text_output(kb_info_json):
  91. """Print the info.json in a plain text format.
  92. """
  93. for key in sorted(kb_info_json):
  94. if key == 'layouts':
  95. cli.echo('{fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  96. else:
  97. cli.echo('{fg_blue}%s{fg_reset}: %s', key, kb_info_json[key])
  98. if cli.config.info.layouts:
  99. show_layouts(kb_info_json, False)
  100. if cli.config.info.matrix:
  101. show_matrix(kb_info_json, False)
  102. if cli.config_source.info.keymap and cli.config_source.info.keymap != 'config_file':
  103. show_keymap(kb_info_json, False)
  104. def print_dotted_output(kb_info_json, prefix=''):
  105. """Print the info.json in a plain text format with dot-joined keys.
  106. """
  107. for key in sorted(kb_info_json):
  108. new_prefix = f'{prefix}.{key}' if prefix else key
  109. if key in ['parse_errors', 'parse_warnings']:
  110. continue
  111. elif key == 'layouts' and prefix == '':
  112. cli.echo('{fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  113. elif isinstance(kb_info_json[key], dict):
  114. print_dotted_output(kb_info_json[key], new_prefix)
  115. elif isinstance(kb_info_json[key], list):
  116. cli.echo('{fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, sorted(kb_info_json[key]))))
  117. else:
  118. cli.echo('{fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  119. def print_parsed_rules_mk(keyboard_name):
  120. rules = rules_mk(keyboard_name)
  121. for k in sorted(rules.keys()):
  122. print('%s = %s' % (k, rules[k]))
  123. return
  124. @cli.argument('-kb', '--keyboard', type=keyboard_folder, completer=keyboard_completer, help='Keyboard to show info for.')
  125. @cli.argument('-km', '--keymap', help='Keymap to show info for (Optional).')
  126. @cli.argument('-l', '--layouts', action='store_true', help='Render the layouts.')
  127. @cli.argument('-m', '--matrix', action='store_true', help='Render the layouts with matrix information.')
  128. @cli.argument('-f', '--format', default='friendly', arg_only=True, help='Format to display the data in (friendly, text, json) (Default: friendly).')
  129. @cli.argument('--ascii', action='store_true', default=not UNICODE_SUPPORT, help='Render layout box drawings in ASCII only.')
  130. @cli.argument('-r', '--rules-mk', action='store_true', help='Render the parsed values of the keyboard\'s rules.mk file.')
  131. @cli.argument('-a', '--api', action='store_true', help='Show fully processed info intended for API consumption.')
  132. @cli.subcommand('Keyboard information.')
  133. @automagic_keyboard
  134. @automagic_keymap
  135. def info(cli):
  136. """Compile an info.json for a particular keyboard and pretty-print it.
  137. """
  138. # Determine our keyboard(s)
  139. if not cli.config.info.keyboard:
  140. cli.log.error('Missing parameter: --keyboard')
  141. cli.subcommands['info'].print_help()
  142. return False
  143. if not is_keyboard(cli.config.info.keyboard):
  144. cli.log.error('Invalid keyboard: "%s"', cli.config.info.keyboard)
  145. return False
  146. if bool(cli.args.rules_mk):
  147. print_parsed_rules_mk(cli.config.info.keyboard)
  148. return False
  149. # default keymap stored in config file should be ignored
  150. if cli.config_source.info.keymap == 'config_file':
  151. cli.config_source.info.keymap = None
  152. # Build the info.json file
  153. if cli.config.info.keymap:
  154. kb_info_json = keymap_json(cli.config.info.keyboard, cli.config.info.keymap)
  155. else:
  156. kb_info_json = info_json(cli.config.info.keyboard)
  157. if not cli.args.api:
  158. kb_info_json = _strip_api_content(kb_info_json)
  159. # Output in the requested format
  160. if cli.args.format == 'json':
  161. print(json.dumps(kb_info_json, cls=InfoJSONEncoder, sort_keys=True))
  162. return True
  163. elif cli.args.format == 'text':
  164. print_dotted_output(kb_info_json)
  165. title_caps = False
  166. elif cli.args.format == 'friendly':
  167. print_friendly_output(kb_info_json)
  168. title_caps = True
  169. else:
  170. cli.log.error('Unknown format: %s', cli.args.format)
  171. return False
  172. # Output requested extras
  173. if cli.config.info.layouts:
  174. show_layouts(kb_info_json, title_caps)
  175. if cli.config.info.matrix:
  176. show_matrix(kb_info_json, title_caps)
  177. if cli.config.info.keymap:
  178. show_keymap(kb_info_json, title_caps)