metadata.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. @lru_cache(maxsize=None)
  77. def _pin_name(pin):
  78. """Returns the proper representation for a pin.
  79. """
  80. pin = pin.strip()
  81. if not pin:
  82. return None
  83. elif pin.isdigit():
  84. return int(pin)
  85. elif pin == 'NO_PIN':
  86. return None
  87. return pin
  88. @lru_cache(maxsize=None)
  89. def _extract_pins(pins):
  90. """Returns a list of pins from a comma separated string of pins.
  91. """
  92. return [_pin_name(pin) for pin in pins.split(',')]
  93. def _extract_direct_matrix(info_data, direct_pins):
  94. """
  95. """
  96. info_data['matrix_pins'] = {}
  97. direct_pin_array = []
  98. while direct_pins[-1] != '}':
  99. direct_pins = direct_pins[:-1]
  100. for row in direct_pins.split('},{'):
  101. if row.startswith('{'):
  102. row = row[1:]
  103. if row.endswith('}'):
  104. row = row[:-1]
  105. direct_pin_array.append([])
  106. for pin in row.split(','):
  107. if pin == 'NO_PIN':
  108. pin = None
  109. direct_pin_array[-1].append(pin)
  110. return direct_pin_array
  111. def _extract_matrix_info(info_data, config_c):
  112. """Populate the matrix information.
  113. """
  114. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  115. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  116. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  117. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  118. if 'matrix_size' in info_data:
  119. info_log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  120. info_data['matrix_size'] = {
  121. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  122. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  123. }
  124. if row_pins and col_pins:
  125. if 'matrix_pins' in info_data:
  126. info_log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  127. info_data['matrix_pins'] = {
  128. 'cols': _extract_pins(col_pins),
  129. 'rows': _extract_pins(row_pins),
  130. }
  131. if direct_pins:
  132. if 'matrix_pins' in info_data:
  133. info_log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  134. info_data['matrix_pins']['direct'] = _extract_direct_matrix(info_data, direct_pins)
  135. return info_data
  136. def _extract_config_h(info_data):
  137. """Pull some keyboard information from existing config.h files
  138. """
  139. config_c = config_h(info_data['keyboard_folder'])
  140. # Pull in data from the json map
  141. dotty_info = dotty(info_data)
  142. info_config_map = json_load(Path('data/mappings/info_config.json'))
  143. for config_key, info_dict in info_config_map.items():
  144. info_key = info_dict['info_key']
  145. key_type = info_dict.get('value_type', 'str')
  146. try:
  147. if config_key in config_c and info_dict.get('to_json', True):
  148. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  149. info_log_warning(info_data, '%s in config.h is overwriting %s in info.json' % (config_key, info_key))
  150. if key_type.startswith('array'):
  151. if '.' in key_type:
  152. key_type, array_type = key_type.split('.', 1)
  153. else:
  154. array_type = None
  155. config_value = config_c[config_key].replace('{', '').replace('}', '').strip()
  156. if array_type == 'int':
  157. dotty_info[info_key] = list(map(int, config_value.split(',')))
  158. else:
  159. dotty_info[info_key] = config_value.split(',')
  160. elif key_type == 'bool':
  161. dotty_info[info_key] = config_c[config_key] in true_values
  162. elif key_type == 'hex':
  163. dotty_info[info_key] = '0x' + config_c[config_key][2:].upper()
  164. elif key_type == 'list':
  165. dotty_info[info_key] = config_c[config_key].split()
  166. elif key_type == 'int':
  167. dotty_info[info_key] = int(config_c[config_key])
  168. else:
  169. dotty_info[info_key] = config_c[config_key]
  170. except Exception as e:
  171. info_log_warning(info_data, f'{config_key}->{info_key}: {e}')
  172. info_data.update(dotty_info)
  173. # Pull data that easily can't be mapped in json
  174. _extract_matrix_info(info_data, config_c)
  175. return info_data
  176. def _extract_rules_mk(info_data):
  177. """Pull some keyboard information from existing rules.mk files
  178. """
  179. rules = rules_mk(info_data['keyboard_folder'])
  180. info_data['processor'] = rules.get('MCU', info_data.get('processor', 'atmega32u4'))
  181. if info_data['processor'] in CHIBIOS_PROCESSORS:
  182. arm_processor_rules(info_data, rules)
  183. elif info_data['processor'] in LUFA_PROCESSORS + VUSB_PROCESSORS:
  184. avr_processor_rules(info_data, rules)
  185. else:
  186. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], info_data['processor']))
  187. unknown_processor_rules(info_data, rules)
  188. # Pull in data from the json map
  189. dotty_info = dotty(info_data)
  190. info_rules_map = json_load(Path('data/mappings/info_rules.json'))
  191. for rules_key, info_dict in info_rules_map.items():
  192. info_key = info_dict['info_key']
  193. key_type = info_dict.get('value_type', 'str')
  194. try:
  195. if rules_key in rules and info_dict.get('to_json', True):
  196. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  197. info_log_warning(info_data, '%s in rules.mk is overwriting %s in info.json' % (rules_key, info_key))
  198. if key_type.startswith('array'):
  199. if '.' in key_type:
  200. key_type, array_type = key_type.split('.', 1)
  201. else:
  202. array_type = None
  203. rules_value = rules[rules_key].replace('{', '').replace('}', '').strip()
  204. if array_type == 'int':
  205. dotty_info[info_key] = list(map(int, rules_value.split(',')))
  206. else:
  207. dotty_info[info_key] = rules_value.split(',')
  208. elif key_type == 'list':
  209. dotty_info[info_key] = rules[rules_key].split()
  210. elif key_type == 'bool':
  211. dotty_info[info_key] = rules[rules_key] in true_values
  212. elif key_type == 'hex':
  213. dotty_info[info_key] = '0x' + rules[rules_key][2:].upper()
  214. elif key_type == 'int':
  215. dotty_info[info_key] = int(rules[rules_key])
  216. else:
  217. dotty_info[info_key] = rules[rules_key]
  218. except Exception as e:
  219. info_log_warning(info_data, f'{rules_key}->{info_key}: {e}')
  220. info_data.update(dotty_info)
  221. # Merge in config values that can't be easily mapped
  222. _extract_features(info_data, rules)
  223. return info_data
  224. @lru_cache(maxsize=None)
  225. def _search_keyboard_h(path):
  226. current_path = Path('keyboards/')
  227. aliases = {}
  228. layouts = {}
  229. for directory in path.parts:
  230. current_path = current_path / directory
  231. keyboard_h = '%s.h' % (directory,)
  232. keyboard_h_path = current_path / keyboard_h
  233. if keyboard_h_path.exists():
  234. new_layouts, new_aliases = find_layouts(keyboard_h_path)
  235. layouts.update(new_layouts)
  236. for alias, alias_text in new_aliases.items():
  237. if alias_text in layouts:
  238. aliases[alias] = alias_text
  239. return layouts, aliases
  240. def _find_all_layouts(info_data, keyboard):
  241. """Looks for layout macros associated with this keyboard.
  242. """
  243. layouts, aliases = _search_keyboard_h(Path(keyboard))
  244. if not layouts:
  245. # 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.
  246. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  247. layouts, new_aliases = _deep_search_layouts(keyboard)
  248. aliases.update(new_aliases)
  249. return layouts, aliases
  250. @lru_cache(maxsize=None)
  251. def _deep_search_layouts(keyboard):
  252. """Do a wider (error-prone) search for layout macros.
  253. """
  254. layouts = {}
  255. aliases = {}
  256. for file in glob('keyboards/%s/*.h' % keyboard):
  257. if file.endswith('.h'):
  258. these_layouts, these_aliases = find_layouts(file)
  259. if these_layouts:
  260. layouts.update(these_layouts)
  261. for alias, alias_text in these_aliases.items():
  262. if alias_text in layouts:
  263. aliases[alias] = alias_text
  264. return layouts, aliases
  265. def info_log_error(info_data, message):
  266. """Send an error message to both JSON and the log.
  267. """
  268. info_data['parse_errors'].append(message)
  269. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  270. def info_log_warning(info_data, message):
  271. """Send a warning message to both JSON and the log.
  272. """
  273. info_data['parse_warnings'].append(message)
  274. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  275. def arm_processor_rules(info_data, rules):
  276. """Setup the default info for an ARM board.
  277. """
  278. info_data['processor_type'] = 'arm'
  279. info_data['protocol'] = 'ChibiOS'
  280. if 'bootloader' not in info_data:
  281. if 'STM32' in info_data['processor']:
  282. info_data['bootloader'] = 'stm32-dfu'
  283. else:
  284. info_data['bootloader'] = 'unknown'
  285. if 'STM32' in info_data['processor']:
  286. info_data['platform'] = 'STM32'
  287. elif 'MCU_SERIES' in rules:
  288. info_data['platform'] = rules['MCU_SERIES']
  289. elif 'ARM_ATSAM' in rules:
  290. info_data['platform'] = 'ARM_ATSAM'
  291. return info_data
  292. def avr_processor_rules(info_data, rules):
  293. """Setup the default info for an AVR board.
  294. """
  295. info_data['processor_type'] = 'avr'
  296. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  297. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  298. if 'bootloader' not in info_data:
  299. info_data['bootloader'] = 'atmel-dfu'
  300. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  301. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  302. return info_data
  303. def unknown_processor_rules(info_data, rules):
  304. """Setup the default keyboard info for unknown boards.
  305. """
  306. info_data['bootloader'] = 'unknown'
  307. info_data['platform'] = 'unknown'
  308. info_data['processor'] = 'unknown'
  309. info_data['processor_type'] = 'unknown'
  310. info_data['protocol'] = 'unknown'
  311. return info_data
  312. def merge_info_jsons(keyboard, info_data):
  313. """Return a merged copy of all the info.json files for a keyboard.
  314. """
  315. for info_file in find_info_json(keyboard):
  316. # Load and validate the JSON data
  317. new_info_data = json_load(info_file)
  318. if not isinstance(new_info_data, dict):
  319. info_log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  320. continue
  321. try:
  322. validate(new_info_data, 'qmk.keyboard.v1')
  323. except jsonschema.ValidationError as e:
  324. json_path = '.'.join([str(p) for p in e.absolute_path])
  325. cli.log.error('Not including data from file: %s', info_file)
  326. cli.log.error('\t%s: %s', json_path, e.message)
  327. continue
  328. # Merge layout data in
  329. if 'layout_aliases' in new_info_data:
  330. info_data['layout_aliases'] = {**info_data.get('layout_aliases', {}), **new_info_data['layout_aliases']}
  331. del new_info_data['layout_aliases']
  332. for layout_name, layout in new_info_data.get('layouts', {}).items():
  333. if layout_name in info_data.get('layout_aliases', {}):
  334. info_log_warning(info_data, f"info.json uses alias name {layout_name} instead of {info_data['layout_aliases'][layout_name]}")
  335. layout_name = info_data['layout_aliases'][layout_name]
  336. if layout_name in info_data['layouts']:
  337. for new_key, existing_key in zip(layout['layout'], info_data['layouts'][layout_name]['layout']):
  338. existing_key.update(new_key)
  339. else:
  340. layout['c_macro'] = False
  341. info_data['layouts'][layout_name] = layout
  342. # Update info_data with the new data
  343. if 'layouts' in new_info_data:
  344. del new_info_data['layouts']
  345. deep_update(info_data, new_info_data)
  346. return info_data
  347. @lru_cache(maxsize=None)
  348. def find_info_json(keyboard):
  349. """Finds all the info.json files associated with a keyboard.
  350. """
  351. # Find the most specific first
  352. base_path = Path('keyboards')
  353. keyboard_path = base_path / keyboard
  354. keyboard_parent = keyboard_path.parent
  355. info_jsons = [keyboard_path / 'info.json']
  356. # Add DEFAULT_FOLDER before parents, if present
  357. rules = rules_mk(keyboard)
  358. if 'DEFAULT_FOLDER' in rules:
  359. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  360. # Add in parent folders for least specific
  361. for _ in range(5):
  362. info_jsons.append(keyboard_parent / 'info.json')
  363. if keyboard_parent.parent == base_path:
  364. break
  365. keyboard_parent = keyboard_parent.parent
  366. # Return a list of the info.json files that actually exist
  367. return [info_json for info_json in info_jsons if info_json.exists()]