info.py 22 KB

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