metadata.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. """Functions that help us generate and use info.json files.
  2. """
  3. from functools import lru_cache
  4. from glob import glob
  5. from pathlib import Path
  6. import jsonschema
  7. from dotty_dict import dotty
  8. from milc import cli
  9. from qmk.constants import CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS
  10. from qmk.c_parse import find_layouts
  11. from qmk.json_schema import deep_update, json_load, validate
  12. from qmk.keyboard import config_h, rules_mk
  13. from qmk.makefile import parse_rules_mk_file
  14. from qmk.math import compute
  15. true_values = ['1', 'on', 'yes', 'true']
  16. false_values = ['0', 'off', 'no', 'false']
  17. @lru_cache(maxsize=None)
  18. def basic_info_json(keyboard):
  19. """Generate a subset of info.json for a specific keyboard.
  20. This does no validation, and should only be used as needed to avoid loops or when performance is critical.
  21. """
  22. cur_dir = Path('keyboards')
  23. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  24. if 'DEFAULT_FOLDER' in rules:
  25. keyboard = rules['DEFAULT_FOLDER']
  26. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk', rules)
  27. info_data = {
  28. 'keyboard_name': str(keyboard),
  29. 'keyboard_folder': str(keyboard),
  30. 'keymaps': {},
  31. 'layouts': {},
  32. 'parse_errors': [],
  33. 'parse_warnings': [],
  34. 'maintainer': 'qmk',
  35. }
  36. # Populate layout data
  37. layouts, aliases = _find_all_layouts(info_data, keyboard)
  38. if aliases:
  39. info_data['layout_aliases'] = aliases
  40. for layout_name, layout_json in layouts.items():
  41. if not layout_name.startswith('LAYOUT_kc'):
  42. layout_json['c_macro'] = True
  43. info_data['layouts'][layout_name] = layout_json
  44. # Merge in the data from info.json, config.h, and rules.mk
  45. info_data = merge_info_jsons(keyboard, info_data)
  46. info_data = _extract_config_h(info_data)
  47. info_data = _extract_rules_mk(info_data)
  48. return info_data
  49. def _extract_features(info_data, rules):
  50. """Find all the features enabled in rules.mk.
  51. """
  52. # Special handling for bootmagic which also supports a "lite" mode.
  53. if rules.get('BOOTMAGIC_ENABLE') == 'lite':
  54. rules['BOOTMAGIC_LITE_ENABLE'] = 'on'
  55. del rules['BOOTMAGIC_ENABLE']
  56. if rules.get('BOOTMAGIC_ENABLE') == 'full':
  57. rules['BOOTMAGIC_ENABLE'] = 'on'
  58. # Skip non-boolean features we haven't implemented special handling for
  59. for feature in 'HAPTIC_ENABLE', 'QWIIC_ENABLE':
  60. if rules.get(feature):
  61. del rules[feature]
  62. # Process the rest of the rules as booleans
  63. for key, value in rules.items():
  64. if key.endswith('_ENABLE'):
  65. key = '_'.join(key.split('_')[:-1]).lower()
  66. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  67. if 'config_h_features' not in info_data:
  68. info_data['config_h_features'] = {}
  69. if 'features' not in info_data:
  70. info_data['features'] = {}
  71. if key in info_data['features']:
  72. info_log_warning(info_data, 'Feature %s is specified in both info.json and rules.mk, the rules.mk value wins.' % (key,))
  73. info_data['features'][key] = value
  74. info_data['config_h_features'][key] = value
  75. return info_data
  76. def _pin_name(pin):
  77. """Returns the proper representation for a pin.
  78. """
  79. pin = pin.strip()
  80. if not pin:
  81. return None
  82. elif pin.isdigit():
  83. return int(pin)
  84. elif pin == 'NO_PIN':
  85. return None
  86. return pin
  87. def _extract_pins(pins):
  88. """Returns a list of pins from a comma separated string of pins.
  89. """
  90. return [_pin_name(pin) for pin in pins.split(',')]
  91. def _extract_direct_matrix(info_data, direct_pins):
  92. """
  93. """
  94. info_data['matrix_pins'] = {}
  95. direct_pin_array = []
  96. while direct_pins[-1] != '}':
  97. direct_pins = direct_pins[:-1]
  98. for row in direct_pins.split('},{'):
  99. if row.startswith('{'):
  100. row = row[1:]
  101. if row.endswith('}'):
  102. row = row[:-1]
  103. direct_pin_array.append([])
  104. for pin in row.split(','):
  105. if pin == 'NO_PIN':
  106. pin = None
  107. direct_pin_array[-1].append(pin)
  108. return direct_pin_array
  109. def _extract_matrix_info(info_data, config_c):
  110. """Populate the matrix information.
  111. """
  112. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  113. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  114. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  115. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  116. if 'matrix_size' in info_data:
  117. info_log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  118. info_data['matrix_size'] = {
  119. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  120. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  121. }
  122. if row_pins and col_pins:
  123. if 'matrix_pins' in info_data:
  124. info_log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  125. info_data['matrix_pins'] = {
  126. 'cols': _extract_pins(col_pins),
  127. 'rows': _extract_pins(row_pins),
  128. }
  129. if direct_pins:
  130. if 'matrix_pins' in info_data:
  131. info_log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  132. info_data['matrix_pins']['direct'] = _extract_direct_matrix(info_data, direct_pins)
  133. return info_data
  134. def _extract_config_h(info_data):
  135. """Pull some keyboard information from existing config.h files
  136. """
  137. config_c = config_h(info_data['keyboard_folder'])
  138. # Pull in data from the json map
  139. dotty_info = dotty(info_data)
  140. info_config_map = json_load(Path('data/mappings/info_config.json'))
  141. for config_key, info_dict in info_config_map.items():
  142. info_key = info_dict['info_key']
  143. key_type = info_dict.get('value_type', 'str')
  144. try:
  145. if config_key in config_c and info_dict.get('to_json', True):
  146. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  147. info_log_warning(info_data, '%s in config.h is overwriting %s in info.json' % (config_key, info_key))
  148. if key_type.startswith('array'):
  149. if '.' in key_type:
  150. key_type, array_type = key_type.split('.', 1)
  151. else:
  152. array_type = None
  153. config_value = config_c[config_key].replace('{', '').replace('}', '').strip()
  154. if array_type == 'int':
  155. dotty_info[info_key] = list(map(int, config_value.split(',')))
  156. else:
  157. dotty_info[info_key] = config_value.split(',')
  158. elif key_type == 'bool':
  159. dotty_info[info_key] = config_c[config_key] in true_values
  160. elif key_type == 'hex':
  161. dotty_info[info_key] = '0x' + config_c[config_key][2:].upper()
  162. elif key_type == 'list':
  163. dotty_info[info_key] = config_c[config_key].split()
  164. elif key_type == 'int':
  165. dotty_info[info_key] = int(config_c[config_key])
  166. else:
  167. dotty_info[info_key] = config_c[config_key]
  168. except Exception as e:
  169. info_log_warning(info_data, f'{config_key}->{info_key}: {e}')
  170. info_data.update(dotty_info)
  171. # Pull data that easily can't be mapped in json
  172. _extract_matrix_info(info_data, config_c)
  173. return info_data
  174. def _extract_rules_mk(info_data):
  175. """Pull some keyboard information from existing rules.mk files
  176. """
  177. rules = rules_mk(info_data['keyboard_folder'])
  178. info_data['processor'] = rules.get('MCU', info_data.get('processor', 'atmega32u4'))
  179. if info_data['processor'] in CHIBIOS_PROCESSORS:
  180. arm_processor_rules(info_data, rules)
  181. elif info_data['processor'] in LUFA_PROCESSORS + VUSB_PROCESSORS:
  182. avr_processor_rules(info_data, rules)
  183. else:
  184. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], info_data['processor']))
  185. unknown_processor_rules(info_data, rules)
  186. # Pull in data from the json map
  187. dotty_info = dotty(info_data)
  188. info_rules_map = json_load(Path('data/mappings/info_rules.json'))
  189. for rules_key, info_dict in info_rules_map.items():
  190. info_key = info_dict['info_key']
  191. key_type = info_dict.get('value_type', 'str')
  192. try:
  193. if rules_key in rules and info_dict.get('to_json', True):
  194. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  195. info_log_warning(info_data, '%s in rules.mk is overwriting %s in info.json' % (rules_key, info_key))
  196. if key_type.startswith('array'):
  197. if '.' in key_type:
  198. key_type, array_type = key_type.split('.', 1)
  199. else:
  200. array_type = None
  201. rules_value = rules[rules_key].replace('{', '').replace('}', '').strip()
  202. if array_type == 'int':
  203. dotty_info[info_key] = list(map(int, rules_value.split(',')))
  204. else:
  205. dotty_info[info_key] = rules_value.split(',')
  206. elif key_type == 'list':
  207. dotty_info[info_key] = rules[rules_key].split()
  208. elif key_type == 'bool':
  209. dotty_info[info_key] = rules[rules_key] in true_values
  210. elif key_type == 'hex':
  211. dotty_info[info_key] = '0x' + rules[rules_key][2:].upper()
  212. elif key_type == 'int':
  213. dotty_info[info_key] = int(rules[rules_key])
  214. else:
  215. dotty_info[info_key] = rules[rules_key]
  216. except Exception as e:
  217. info_log_warning(info_data, f'{rules_key}->{info_key}: {e}')
  218. info_data.update(dotty_info)
  219. # Merge in config values that can't be easily mapped
  220. _extract_features(info_data, rules)
  221. return info_data
  222. def _search_keyboard_h(path):
  223. current_path = Path('keyboards/')
  224. aliases = {}
  225. layouts = {}
  226. for directory in path.parts:
  227. current_path = current_path / directory
  228. keyboard_h = '%s.h' % (directory,)
  229. keyboard_h_path = current_path / keyboard_h
  230. if keyboard_h_path.exists():
  231. new_layouts, new_aliases = find_layouts(keyboard_h_path)
  232. layouts.update(new_layouts)
  233. for alias, alias_text in new_aliases.items():
  234. if alias_text in layouts:
  235. aliases[alias] = alias_text
  236. return layouts, aliases
  237. def _find_all_layouts(info_data, keyboard):
  238. """Looks for layout macros associated with this keyboard.
  239. """
  240. layouts, aliases = _search_keyboard_h(Path(keyboard))
  241. if not layouts:
  242. # If we don't find any layouts from info.json or keyboard.h we widen our search. This is error prone which is why we want to encourage people to follow the standard above.
  243. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  244. for file in glob('keyboards/%s/*.h' % keyboard):
  245. if file.endswith('.h'):
  246. these_layouts, these_aliases = find_layouts(file)
  247. if these_layouts:
  248. layouts.update(these_layouts)
  249. for alias, alias_text in these_aliases.items():
  250. if alias_text in layouts:
  251. aliases[alias] = alias_text
  252. return layouts, aliases
  253. def info_log_error(info_data, message):
  254. """Send an error message to both JSON and the log.
  255. """
  256. info_data['parse_errors'].append(message)
  257. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  258. def info_log_warning(info_data, message):
  259. """Send a warning message to both JSON and the log.
  260. """
  261. info_data['parse_warnings'].append(message)
  262. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  263. def arm_processor_rules(info_data, rules):
  264. """Setup the default info for an ARM board.
  265. """
  266. info_data['processor_type'] = 'arm'
  267. info_data['protocol'] = 'ChibiOS'
  268. if 'bootloader' not in info_data:
  269. if 'STM32' in info_data['processor']:
  270. info_data['bootloader'] = 'stm32-dfu'
  271. else:
  272. info_data['bootloader'] = 'unknown'
  273. if 'STM32' in info_data['processor']:
  274. info_data['platform'] = 'STM32'
  275. elif 'MCU_SERIES' in rules:
  276. info_data['platform'] = rules['MCU_SERIES']
  277. elif 'ARM_ATSAM' in rules:
  278. info_data['platform'] = 'ARM_ATSAM'
  279. return info_data
  280. def avr_processor_rules(info_data, rules):
  281. """Setup the default info for an AVR board.
  282. """
  283. info_data['processor_type'] = 'avr'
  284. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  285. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  286. if 'bootloader' not in info_data:
  287. info_data['bootloader'] = 'atmel-dfu'
  288. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  289. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  290. return info_data
  291. def unknown_processor_rules(info_data, rules):
  292. """Setup the default keyboard info for unknown boards.
  293. """
  294. info_data['bootloader'] = 'unknown'
  295. info_data['platform'] = 'unknown'
  296. info_data['processor'] = 'unknown'
  297. info_data['processor_type'] = 'unknown'
  298. info_data['protocol'] = 'unknown'
  299. return info_data
  300. def merge_info_jsons(keyboard, info_data):
  301. """Return a merged copy of all the info.json files for a keyboard.
  302. """
  303. for info_file in find_info_json(keyboard):
  304. # Load and validate the JSON data
  305. new_info_data = json_load(info_file)
  306. if not isinstance(new_info_data, dict):
  307. info_log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  308. continue
  309. try:
  310. validate(new_info_data, 'qmk.keyboard.v1')
  311. except jsonschema.ValidationError as e:
  312. json_path = '.'.join([str(p) for p in e.absolute_path])
  313. cli.log.error('Not including data from file: %s', info_file)
  314. cli.log.error('\t%s: %s', json_path, e.message)
  315. continue
  316. # Merge layout data in
  317. if 'layout_aliases' in new_info_data:
  318. info_data['layout_aliases'] = {**info_data.get('layout_aliases', {}), **new_info_data['layout_aliases']}
  319. del new_info_data['layout_aliases']
  320. for layout_name, layout in new_info_data.get('layouts', {}).items():
  321. if layout_name in info_data.get('layout_aliases', {}):
  322. info_log_warning(info_data, f"info.json uses alias name {layout_name} instead of {info_data['layout_aliases'][layout_name]}")
  323. layout_name = info_data['layout_aliases'][layout_name]
  324. if layout_name in info_data['layouts']:
  325. for new_key, existing_key in zip(layout['layout'], info_data['layouts'][layout_name]['layout']):
  326. existing_key.update(new_key)
  327. else:
  328. layout['c_macro'] = False
  329. info_data['layouts'][layout_name] = layout
  330. # Update info_data with the new data
  331. if 'layouts' in new_info_data:
  332. del new_info_data['layouts']
  333. deep_update(info_data, new_info_data)
  334. return info_data
  335. def find_info_json(keyboard):
  336. """Finds all the info.json files associated with a keyboard.
  337. """
  338. # Find the most specific first
  339. base_path = Path('keyboards')
  340. keyboard_path = base_path / keyboard
  341. keyboard_parent = keyboard_path.parent
  342. info_jsons = [keyboard_path / 'info.json']
  343. # Add DEFAULT_FOLDER before parents, if present
  344. rules = rules_mk(keyboard)
  345. if 'DEFAULT_FOLDER' in rules:
  346. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  347. # Add in parent folders for least specific
  348. for _ in range(5):
  349. info_jsons.append(keyboard_parent / 'info.json')
  350. if keyboard_parent.parent == base_path:
  351. break
  352. keyboard_parent = keyboard_parent.parent
  353. # Return a list of the info.json files that actually exist
  354. return [info_json for info_json in info_jsons if info_json.exists()]