info.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. """Functions that help us generate and use info.json files.
  2. """
  3. import json
  4. from collections.abc import Mapping
  5. from glob import glob
  6. from pathlib import Path
  7. import hjson
  8. import jsonschema
  9. from dotty_dict import dotty
  10. from milc import cli
  11. from qmk.constants import CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS
  12. from qmk.c_parse import find_layouts
  13. from qmk.keyboard import config_h, rules_mk
  14. from qmk.keymap import list_keymaps
  15. from qmk.makefile import parse_rules_mk_file
  16. from qmk.math import compute
  17. true_values = ['1', 'on', 'yes']
  18. false_values = ['0', 'off', 'no']
  19. def info_json(keyboard):
  20. """Generate the info.json data for a specific keyboard.
  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 the list of JSON keymaps
  37. for keymap in list_keymaps(keyboard, c=False, fullpath=True):
  38. info_data['keymaps'][keymap.name] = {'url': f'https://raw.githubusercontent.com/qmk/qmk_firmware/master/{keymap}/keymap.json'}
  39. # Populate layout data
  40. for layout_name, layout_json in _find_all_layouts(info_data, keyboard).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. # Validate against the jsonschema
  49. try:
  50. keyboard_api_validate(info_data)
  51. except jsonschema.ValidationError as e:
  52. json_path = '.'.join([str(p) for p in e.absolute_path])
  53. cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
  54. exit()
  55. # Make sure we have at least one layout
  56. if not info_data.get('layouts'):
  57. _log_error(info_data, 'No LAYOUTs defined! Need at least one layout defined in the keyboard.h or info.json.')
  58. # Make sure we supply layout macros for the community layouts we claim to support
  59. # FIXME(skullydazed): This should be populated into info.json and read from there instead
  60. if 'LAYOUTS' in rules and info_data.get('layouts'):
  61. # Match these up against the supplied layouts
  62. supported_layouts = rules['LAYOUTS'].strip().split()
  63. for layout_name in sorted(info_data['layouts']):
  64. layout_name = layout_name[7:]
  65. if layout_name in supported_layouts:
  66. supported_layouts.remove(layout_name)
  67. if supported_layouts:
  68. for supported_layout in supported_layouts:
  69. _log_error(info_data, 'Claims to support community layout %s but no LAYOUT_%s() macro found' % (supported_layout, supported_layout))
  70. return info_data
  71. def _json_load(json_file):
  72. """Load a json file from disk.
  73. Note: file must be a Path object.
  74. """
  75. try:
  76. return hjson.load(json_file.open())
  77. except json.decoder.JSONDecodeError as e:
  78. cli.log.error('Invalid JSON encountered attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
  79. exit(1)
  80. def _jsonschema(schema_name):
  81. """Read a jsonschema file from disk.
  82. FIXME(skullydazed/anyone): Refactor to make this a public function.
  83. """
  84. schema_path = Path(f'data/schemas/{schema_name}.jsonschema')
  85. if not schema_path.exists():
  86. schema_path = Path('data/schemas/false.jsonschema')
  87. return _json_load(schema_path)
  88. def keyboard_validate(data):
  89. """Validates data against the keyboard jsonschema.
  90. """
  91. schema = _jsonschema('keyboard')
  92. validator = jsonschema.Draft7Validator(schema).validate
  93. return validator(data)
  94. def keyboard_api_validate(data):
  95. """Validates data against the api_keyboard jsonschema.
  96. """
  97. base = _jsonschema('keyboard')
  98. relative = _jsonschema('api_keyboard')
  99. resolver = jsonschema.RefResolver.from_schema(base)
  100. validator = jsonschema.Draft7Validator(relative, resolver=resolver).validate
  101. return validator(data)
  102. def _extract_features(info_data, rules):
  103. """Find all the features enabled in rules.mk.
  104. """
  105. # Special handling for bootmagic which also supports a "lite" mode.
  106. if rules.get('BOOTMAGIC_ENABLE') == 'lite':
  107. rules['BOOTMAGIC_LITE_ENABLE'] = 'on'
  108. del rules['BOOTMAGIC_ENABLE']
  109. if rules.get('BOOTMAGIC_ENABLE') == 'full':
  110. rules['BOOTMAGIC_ENABLE'] = 'on'
  111. # Skip non-boolean features we haven't implemented special handling for
  112. for feature in 'HAPTIC_ENABLE', 'QWIIC_ENABLE':
  113. if rules.get(feature):
  114. del rules[feature]
  115. # Process the rest of the rules as booleans
  116. for key, value in rules.items():
  117. if key.endswith('_ENABLE'):
  118. key = '_'.join(key.split('_')[:-1]).lower()
  119. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  120. if 'config_h_features' not in info_data:
  121. info_data['config_h_features'] = {}
  122. if 'features' not in info_data:
  123. info_data['features'] = {}
  124. if key in info_data['features']:
  125. _log_warning(info_data, 'Feature %s is specified in both info.json and rules.mk, the rules.mk value wins.' % (key,))
  126. info_data['features'][key] = value
  127. info_data['config_h_features'][key] = value
  128. return info_data
  129. def _pin_name(pin):
  130. """Returns the proper representation for a pin.
  131. """
  132. pin = pin.strip()
  133. if not pin:
  134. return None
  135. elif pin.isdigit():
  136. return int(pin)
  137. elif pin == 'NO_PIN':
  138. return None
  139. elif pin[0] in 'ABCDEFGHIJK' and pin[1].isdigit():
  140. return pin
  141. raise ValueError(f'Invalid pin: {pin}')
  142. def _extract_pins(pins):
  143. """Returns a list of pins from a comma separated string of pins.
  144. """
  145. return [_pin_name(pin) for pin in pins.split(',')]
  146. def _extract_direct_matrix(info_data, direct_pins):
  147. """
  148. """
  149. info_data['matrix_pins'] = {}
  150. direct_pin_array = []
  151. while direct_pins[-1] != '}':
  152. direct_pins = direct_pins[:-1]
  153. for row in direct_pins.split('},{'):
  154. if row.startswith('{'):
  155. row = row[1:]
  156. if row.endswith('}'):
  157. row = row[:-1]
  158. direct_pin_array.append([])
  159. for pin in row.split(','):
  160. if pin == 'NO_PIN':
  161. pin = None
  162. direct_pin_array[-1].append(pin)
  163. return direct_pin_array
  164. def _extract_matrix_info(info_data, config_c):
  165. """Populate the matrix information.
  166. """
  167. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  168. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  169. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  170. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  171. if 'matrix_size' in info_data:
  172. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  173. info_data['matrix_size'] = {
  174. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  175. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  176. }
  177. if row_pins and col_pins:
  178. if 'matrix_pins' in info_data:
  179. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  180. info_data['matrix_pins'] = {
  181. 'cols': _extract_pins(col_pins),
  182. 'rows': _extract_pins(row_pins),
  183. }
  184. if direct_pins:
  185. if 'matrix_pins' in info_data:
  186. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  187. info_data['matrix_pins']['direct'] = _extract_direct_matrix(info_data, direct_pins)
  188. return info_data
  189. def _extract_config_h(info_data):
  190. """Pull some keyboard information from existing config.h files
  191. """
  192. config_c = config_h(info_data['keyboard_folder'])
  193. # Pull in data from the json map
  194. dotty_info = dotty(info_data)
  195. info_config_map = _json_load(Path('data/mappings/info_config.json'))
  196. for config_key, info_dict in info_config_map.items():
  197. info_key = info_dict['info_key']
  198. key_type = info_dict.get('value_type', 'str')
  199. try:
  200. if config_key in config_c and info_dict.get('to_json', True):
  201. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  202. _log_warning(info_data, '%s in config.h is overwriting %s in info.json' % (config_key, info_key))
  203. if key_type.startswith('array'):
  204. if '.' in key_type:
  205. key_type, array_type = key_type.split('.', 1)
  206. else:
  207. array_type = None
  208. config_value = config_c[config_key].replace('{', '').replace('}', '').strip()
  209. if array_type == 'int':
  210. dotty_info[info_key] = list(map(int, config_value.split(',')))
  211. else:
  212. dotty_info[info_key] = config_value.split(',')
  213. elif key_type == 'bool':
  214. dotty_info[info_key] = config_c[config_key] in true_values
  215. elif key_type == 'hex':
  216. dotty_info[info_key] = '0x' + config_c[config_key][2:].upper()
  217. elif key_type == 'list':
  218. dotty_info[info_key] = config_c[config_key].split()
  219. elif key_type == 'int':
  220. dotty_info[info_key] = int(config_c[config_key])
  221. else:
  222. dotty_info[info_key] = config_c[config_key]
  223. except Exception as e:
  224. _log_warning(info_data, f'{config_key}->{info_key}: {e}')
  225. info_data.update(dotty_info)
  226. # Pull data that easily can't be mapped in json
  227. _extract_matrix_info(info_data, config_c)
  228. return info_data
  229. def _extract_rules_mk(info_data):
  230. """Pull some keyboard information from existing rules.mk files
  231. """
  232. rules = rules_mk(info_data['keyboard_folder'])
  233. info_data['processor'] = rules.get('MCU', info_data.get('processor', 'atmega32u4'))
  234. if info_data['processor'] in CHIBIOS_PROCESSORS:
  235. arm_processor_rules(info_data, rules)
  236. elif info_data['processor'] in LUFA_PROCESSORS + VUSB_PROCESSORS:
  237. avr_processor_rules(info_data, rules)
  238. else:
  239. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], info_data['processor']))
  240. unknown_processor_rules(info_data, rules)
  241. # Pull in data from the json map
  242. dotty_info = dotty(info_data)
  243. info_rules_map = _json_load(Path('data/mappings/info_rules.json'))
  244. for rules_key, info_dict in info_rules_map.items():
  245. info_key = info_dict['info_key']
  246. key_type = info_dict.get('value_type', 'str')
  247. try:
  248. if rules_key in rules and info_dict.get('to_json', True):
  249. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  250. _log_warning(info_data, '%s in rules.mk is overwriting %s in info.json' % (rules_key, info_key))
  251. if key_type.startswith('array'):
  252. if '.' in key_type:
  253. key_type, array_type = key_type.split('.', 1)
  254. else:
  255. array_type = None
  256. rules_value = rules[rules_key].replace('{', '').replace('}', '').strip()
  257. if array_type == 'int':
  258. dotty_info[info_key] = list(map(int, rules_value.split(',')))
  259. else:
  260. dotty_info[info_key] = rules_value.split(',')
  261. elif key_type == 'list':
  262. dotty_info[info_key] = rules[rules_key].split()
  263. elif key_type == 'bool':
  264. dotty_info[info_key] = rules[rules_key] in true_values
  265. elif key_type == 'hex':
  266. dotty_info[info_key] = '0x' + rules[rules_key][2:].upper()
  267. elif key_type == 'int':
  268. dotty_info[info_key] = int(rules[rules_key])
  269. else:
  270. dotty_info[info_key] = rules[rules_key]
  271. except Exception as e:
  272. _log_warning(info_data, f'{rules_key}->{info_key}: {e}')
  273. info_data.update(dotty_info)
  274. # Merge in config values that can't be easily mapped
  275. _extract_features(info_data, rules)
  276. return info_data
  277. def _merge_layouts(info_data, new_info_data):
  278. """Merge new_info_data into info_data in an intelligent way.
  279. """
  280. for layout_name, layout_json in new_info_data['layouts'].items():
  281. if layout_name in info_data['layouts']:
  282. # Pull in layouts we have a macro for
  283. if len(info_data['layouts'][layout_name]['layout']) != len(layout_json['layout']):
  284. msg = '%s: %s: Number of elements in info.json does not match! info.json:%s != %s:%s'
  285. _log_error(info_data, msg % (info_data['keyboard_folder'], layout_name, len(layout_json['layout']), layout_name, len(info_data['layouts'][layout_name]['layout'])))
  286. else:
  287. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  288. key.update(layout_json['layout'][i])
  289. else:
  290. # Pull in layouts that have matrix data
  291. missing_matrix = False
  292. for key in layout_json.get('layout', {}):
  293. if 'matrix' not in key:
  294. missing_matrix = True
  295. if not missing_matrix:
  296. if layout_name in info_data['layouts']:
  297. # Update an existing layout with new data
  298. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  299. key.update(layout_json['layout'][i])
  300. else:
  301. # Copy in the new layout wholesale
  302. layout_json['c_macro'] = False
  303. info_data['layouts'][layout_name] = layout_json
  304. return info_data
  305. def _search_keyboard_h(path):
  306. current_path = Path('keyboards/')
  307. layouts = {}
  308. for directory in path.parts:
  309. current_path = current_path / directory
  310. keyboard_h = '%s.h' % (directory,)
  311. keyboard_h_path = current_path / keyboard_h
  312. if keyboard_h_path.exists():
  313. layouts.update(find_layouts(keyboard_h_path))
  314. return layouts
  315. def _find_all_layouts(info_data, keyboard):
  316. """Looks for layout macros associated with this keyboard.
  317. """
  318. layouts = _search_keyboard_h(Path(keyboard))
  319. if not layouts:
  320. # 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.
  321. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  322. for file in glob('keyboards/%s/*.h' % keyboard):
  323. if file.endswith('.h'):
  324. these_layouts = find_layouts(file)
  325. if these_layouts:
  326. layouts.update(these_layouts)
  327. return layouts
  328. def _log_error(info_data, message):
  329. """Send an error message to both JSON and the log.
  330. """
  331. info_data['parse_errors'].append(message)
  332. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  333. def _log_warning(info_data, message):
  334. """Send a warning message to both JSON and the log.
  335. """
  336. info_data['parse_warnings'].append(message)
  337. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  338. def arm_processor_rules(info_data, rules):
  339. """Setup the default info for an ARM board.
  340. """
  341. info_data['processor_type'] = 'arm'
  342. info_data['protocol'] = 'ChibiOS'
  343. if 'bootloader' not in info_data:
  344. if 'STM32' in info_data['processor']:
  345. info_data['bootloader'] = 'stm32-dfu'
  346. else:
  347. info_data['bootloader'] = 'unknown'
  348. if 'STM32' in info_data['processor']:
  349. info_data['platform'] = 'STM32'
  350. elif 'MCU_SERIES' in rules:
  351. info_data['platform'] = rules['MCU_SERIES']
  352. elif 'ARM_ATSAM' in rules:
  353. info_data['platform'] = 'ARM_ATSAM'
  354. return info_data
  355. def avr_processor_rules(info_data, rules):
  356. """Setup the default info for an AVR board.
  357. """
  358. info_data['processor_type'] = 'avr'
  359. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  360. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  361. if 'bootloader' not in info_data:
  362. info_data['bootloader'] = 'atmel-dfu'
  363. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  364. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  365. return info_data
  366. def unknown_processor_rules(info_data, rules):
  367. """Setup the default keyboard info for unknown boards.
  368. """
  369. info_data['bootloader'] = 'unknown'
  370. info_data['platform'] = 'unknown'
  371. info_data['processor'] = 'unknown'
  372. info_data['processor_type'] = 'unknown'
  373. info_data['protocol'] = 'unknown'
  374. return info_data
  375. def deep_update(origdict, newdict):
  376. """Update a dictionary in place, recursing to do a deep copy.
  377. """
  378. for key, value in newdict.items():
  379. if isinstance(value, Mapping):
  380. origdict[key] = deep_update(origdict.get(key, {}), value)
  381. else:
  382. origdict[key] = value
  383. return origdict
  384. def merge_info_jsons(keyboard, info_data):
  385. """Return a merged copy of all the info.json files for a keyboard.
  386. """
  387. for info_file in find_info_json(keyboard):
  388. # Load and validate the JSON data
  389. new_info_data = _json_load(info_file)
  390. if not isinstance(new_info_data, dict):
  391. _log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  392. continue
  393. try:
  394. keyboard_validate(new_info_data)
  395. except jsonschema.ValidationError as e:
  396. json_path = '.'.join([str(p) for p in e.absolute_path])
  397. cli.log.error('Not including data from file: %s', info_file)
  398. cli.log.error('\t%s: %s', json_path, e.message)
  399. continue
  400. # Mark the layouts as coming from json
  401. for layout in new_info_data.get('layouts', {}).values():
  402. layout['c_macro'] = False
  403. # Update info_data with the new data
  404. deep_update(info_data, new_info_data)
  405. return info_data
  406. def find_info_json(keyboard):
  407. """Finds all the info.json files associated with a keyboard.
  408. """
  409. # Find the most specific first
  410. base_path = Path('keyboards')
  411. keyboard_path = base_path / keyboard
  412. keyboard_parent = keyboard_path.parent
  413. info_jsons = [keyboard_path / 'info.json']
  414. # Add DEFAULT_FOLDER before parents, if present
  415. rules = rules_mk(keyboard)
  416. if 'DEFAULT_FOLDER' in rules:
  417. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  418. # Add in parent folders for least specific
  419. for _ in range(5):
  420. info_jsons.append(keyboard_parent / 'info.json')
  421. if keyboard_parent.parent == base_path:
  422. break
  423. keyboard_parent = keyboard_parent.parent
  424. # Return a list of the info.json files that actually exist
  425. return [info_json for info_json in info_jsons if info_json.exists()]