info.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. """Functions that help us generate and use info.json files.
  2. """
  3. import json
  4. from glob import glob
  5. from pathlib import Path
  6. import jsonschema
  7. from milc import cli
  8. from qmk.constants import CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS, LED_INDICATORS
  9. from qmk.c_parse import find_layouts
  10. from qmk.keyboard import config_h, rules_mk
  11. from qmk.keymap import list_keymaps
  12. from qmk.makefile import parse_rules_mk_file
  13. from qmk.math import compute
  14. led_matrix_properties = {
  15. 'driver_count': 'LED_DRIVER_COUNT',
  16. 'driver_addr1': 'LED_DRIVER_ADDR_1',
  17. 'driver_addr2': 'LED_DRIVER_ADDR_2',
  18. 'driver_addr3': 'LED_DRIVER_ADDR_3',
  19. 'driver_addr4': 'LED_DRIVER_ADDR_4',
  20. 'led_count': 'LED_DRIVER_LED_COUNT',
  21. 'timeout': 'ISSI_TIMEOUT',
  22. 'persistence': 'ISSI_PERSISTENCE'
  23. }
  24. rgblight_properties = {
  25. 'led_count': ('RGBLED_NUM', int),
  26. 'pin': ('RGB_DI_PIN', str),
  27. 'max_brightness': ('RGBLIGHT_LIMIT_VAL', int),
  28. 'hue_steps': ('RGBLIGHT_HUE_STEP', int),
  29. 'saturation_steps': ('RGBLIGHT_SAT_STEP', int),
  30. 'brightness_steps': ('RGBLIGHT_VAL_STEP', int)
  31. }
  32. rgblight_toggles = {
  33. 'sleep': 'RGBLIGHT_SLEEP',
  34. 'split': 'RGBLIGHT_SPLIT',
  35. }
  36. rgblight_animations = {
  37. 'all': 'RGBLIGHT_ANIMATIONS',
  38. 'alternating': 'RGBLIGHT_EFFECT_ALTERNATING',
  39. 'breathing': 'RGBLIGHT_EFFECT_BREATHING',
  40. 'christmas': 'RGBLIGHT_EFFECT_CHRISTMAS',
  41. 'knight': 'RGBLIGHT_EFFECT_KNIGHT',
  42. 'rainbow_mood': 'RGBLIGHT_EFFECT_RAINBOW_MOOD',
  43. 'rainbow_swirl': 'RGBLIGHT_EFFECT_RAINBOW_SWIRL',
  44. 'rgb_test': 'RGBLIGHT_EFFECT_RGB_TEST',
  45. 'snake': 'RGBLIGHT_EFFECT_SNAKE',
  46. 'static_gradient': 'RGBLIGHT_EFFECT_STATIC_GRADIENT',
  47. 'twinkle': 'RGBLIGHT_EFFECT_TWINKLE'
  48. }
  49. usb_properties = {'vid': 'VENDOR_ID', 'pid': 'PRODUCT_ID', 'device_ver': 'DEVICE_VER'}
  50. true_values = ['1', 'on', 'yes']
  51. false_values = ['0', 'off', 'no']
  52. def info_json(keyboard):
  53. """Generate the info.json data for a specific keyboard.
  54. """
  55. cur_dir = Path('keyboards')
  56. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  57. if 'DEFAULT_FOLDER' in rules:
  58. keyboard = rules['DEFAULT_FOLDER']
  59. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk', rules)
  60. info_data = {
  61. 'keyboard_name': str(keyboard),
  62. 'keyboard_folder': str(keyboard),
  63. 'keymaps': {},
  64. 'layouts': {},
  65. 'parse_errors': [],
  66. 'parse_warnings': [],
  67. 'maintainer': 'qmk',
  68. }
  69. # Populate the list of JSON keymaps
  70. for keymap in list_keymaps(keyboard, c=False, fullpath=True):
  71. info_data['keymaps'][keymap.name] = {'url': f'https://raw.githubusercontent.com/qmk/qmk_firmware/master/{keymap}/keymap.json'}
  72. # Populate layout data
  73. for layout_name, layout_json in _find_all_layouts(info_data, keyboard).items():
  74. if not layout_name.startswith('LAYOUT_kc'):
  75. layout_json['c_macro'] = True
  76. info_data['layouts'][layout_name] = layout_json
  77. # Merge in the data from info.json, config.h, and rules.mk
  78. info_data = merge_info_jsons(keyboard, info_data)
  79. info_data = _extract_config_h(info_data)
  80. info_data = _extract_rules_mk(info_data)
  81. # Validate against the jsonschema
  82. try:
  83. keyboard_api_validate(info_data)
  84. except jsonschema.ValidationError as e:
  85. json_path = '.'.join([str(p) for p in e.absolute_path])
  86. cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
  87. print(dir(e))
  88. exit()
  89. # Make sure we have at least one layout
  90. if not info_data.get('layouts'):
  91. _log_error(info_data, 'No LAYOUTs defined! Need at least one layout defined in the keyboard.h or info.json.')
  92. # Make sure we supply layout macros for the community layouts we claim to support
  93. # FIXME(skullydazed): This should be populated into info.json and read from there instead
  94. if 'LAYOUTS' in rules and info_data.get('layouts'):
  95. # Match these up against the supplied layouts
  96. supported_layouts = rules['LAYOUTS'].strip().split()
  97. for layout_name in sorted(info_data['layouts']):
  98. layout_name = layout_name[7:]
  99. if layout_name in supported_layouts:
  100. supported_layouts.remove(layout_name)
  101. if supported_layouts:
  102. for supported_layout in supported_layouts:
  103. _log_error(info_data, 'Claims to support community layout %s but no LAYOUT_%s() macro found' % (supported_layout, supported_layout))
  104. return info_data
  105. def _json_load(json_file):
  106. """Load a json file from disk.
  107. Note: file must be a Path object.
  108. """
  109. try:
  110. return json.load(json_file.open())
  111. except json.decoder.JSONDecodeError as e:
  112. cli.log.error('Invalid JSON encountered attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
  113. exit(1)
  114. def _jsonschema(schema_name):
  115. """Read a jsonschema file from disk.
  116. """
  117. schema_path = Path(f'data/schemas/{schema_name}.jsonschema')
  118. if not schema_path.exists():
  119. schema_path = Path('data/schemas/false.jsonschema')
  120. return _json_load(schema_path)
  121. def keyboard_validate(data):
  122. """Validates data against the keyboard jsonschema.
  123. """
  124. schema = _jsonschema('keyboard')
  125. validator = jsonschema.Draft7Validator(schema).validate
  126. return validator(data)
  127. def keyboard_api_validate(data):
  128. """Validates data against the api_keyboard jsonschema.
  129. """
  130. base = _jsonschema('keyboard')
  131. relative = _jsonschema('api_keyboard')
  132. resolver = jsonschema.RefResolver.from_schema(base)
  133. validator = jsonschema.Draft7Validator(relative, resolver=resolver).validate
  134. return validator(data)
  135. def _extract_debounce(info_data, config_c):
  136. """Handle debounce.
  137. """
  138. if 'debounce' in info_data and 'DEBOUNCE' in config_c:
  139. _log_warning(info_data, 'Debounce is specified in both info.json and config.h, the config.h value wins.')
  140. if 'DEBOUNCE' in config_c:
  141. info_data['debounce'] = int(config_c['DEBOUNCE'])
  142. return info_data
  143. def _extract_diode_direction(info_data, config_c):
  144. """Handle the diode direction.
  145. """
  146. if 'diode_direction' in info_data and 'DIODE_DIRECTION' in config_c:
  147. _log_warning(info_data, 'Diode direction is specified in both info.json and config.h, the config.h value wins.')
  148. if 'DIODE_DIRECTION' in config_c:
  149. info_data['diode_direction'] = config_c.get('DIODE_DIRECTION')
  150. return info_data
  151. def _extract_indicators(info_data, config_c):
  152. """Find the LED indicator information.
  153. """
  154. for json_key, config_key in LED_INDICATORS.items():
  155. if json_key in info_data.get('indicators', []) and config_key in config_c:
  156. _log_warning(info_data, f'Indicator {json_key} is specified in both info.json and config.h, the config.h value wins.')
  157. if 'indicators' not in info_data:
  158. info_data['indicators'] = {}
  159. if config_key in config_c:
  160. if 'indicators' not in info_data:
  161. info_data['indicators'] = {}
  162. info_data['indicators'][json_key] = config_c.get(config_key)
  163. return info_data
  164. def _extract_community_layouts(info_data, rules):
  165. """Find the community layouts in rules.mk.
  166. """
  167. community_layouts = rules['LAYOUTS'].split() if 'LAYOUTS' in rules else []
  168. if 'community_layouts' in info_data:
  169. for layout in community_layouts:
  170. if layout not in info_data['community_layouts']:
  171. community_layouts.append(layout)
  172. else:
  173. info_data['community_layouts'] = community_layouts
  174. return info_data
  175. def _extract_features(info_data, rules):
  176. """Find all the features enabled in rules.mk.
  177. """
  178. # Special handling for bootmagic which also supports a "lite" mode.
  179. if rules.get('BOOTMAGIC_ENABLE') == 'lite':
  180. rules['BOOTMAGIC_LITE_ENABLE'] = 'on'
  181. del rules['BOOTMAGIC_ENABLE']
  182. if rules.get('BOOTMAGIC_ENABLE') == 'full':
  183. rules['BOOTMAGIC_ENABLE'] = 'on'
  184. # Skip non-boolean features we haven't implemented special handling for
  185. for feature in 'HAPTIC_ENABLE', 'QWIIC_ENABLE':
  186. if rules.get(feature):
  187. del rules[feature]
  188. # Process the rest of the rules as booleans
  189. for key, value in rules.items():
  190. if key.endswith('_ENABLE'):
  191. key = '_'.join(key.split('_')[:-1]).lower()
  192. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  193. if 'config_h_features' not in info_data:
  194. info_data['config_h_features'] = {}
  195. if 'features' not in info_data:
  196. info_data['features'] = {}
  197. if key in info_data['features']:
  198. _log_warning(info_data, 'Feature %s is specified in both info.json and rules.mk, the rules.mk value wins.' % (key,))
  199. info_data['features'][key] = value
  200. info_data['config_h_features'][key] = value
  201. return info_data
  202. def _extract_led_drivers(info_data, rules):
  203. """Find all the LED drivers set in rules.mk.
  204. """
  205. if 'LED_MATRIX_DRIVER' in rules:
  206. if 'led_matrix' not in info_data:
  207. info_data['led_matrix'] = {}
  208. if info_data['led_matrix'].get('driver'):
  209. _log_warning(info_data, 'LED Matrix driver is specified in both info.json and rules.mk, the rules.mk value wins.')
  210. info_data['led_matrix']['driver'] = rules['LED_MATRIX_DRIVER']
  211. return info_data
  212. def _extract_led_matrix(info_data, config_c):
  213. """Handle the led_matrix configuration.
  214. """
  215. led_matrix = info_data.get('led_matrix', {})
  216. for json_key, config_key in led_matrix_properties.items():
  217. if config_key in config_c:
  218. if json_key in led_matrix:
  219. _log_warning(info_data, 'LED Matrix: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  220. led_matrix[json_key] = config_c[config_key]
  221. def _extract_rgblight(info_data, config_c):
  222. """Handle the rgblight configuration.
  223. """
  224. rgblight = info_data.get('rgblight', {})
  225. animations = rgblight.get('animations', {})
  226. if 'RGBLED_SPLIT' in config_c:
  227. raw_split = config_c.get('RGBLED_SPLIT', '').replace('{', '').replace('}', '').strip()
  228. rgblight['split_count'] = [int(i) for i in raw_split.split(',')]
  229. for json_key, config_key_type in rgblight_properties.items():
  230. config_key, config_type = config_key_type
  231. if config_key in config_c:
  232. if json_key in rgblight:
  233. _log_warning(info_data, 'RGB Light: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  234. try:
  235. rgblight[json_key] = config_type(config_c[config_key])
  236. except ValueError as e:
  237. cli.log.error('%s: config.h: Could not convert "%s" to %s: %s', info_data['keyboard_folder'], config_c[config_key], config_type.__name__, e)
  238. for json_key, config_key in rgblight_toggles.items():
  239. if config_key in config_c:
  240. if json_key in rgblight:
  241. _log_warning(info_data, 'RGB Light: %s is specified in both info.json and config.h, the config.h value wins.', json_key)
  242. rgblight[json_key] = config_c[config_key]
  243. for json_key, config_key in rgblight_animations.items():
  244. if config_key in config_c:
  245. if json_key in animations:
  246. _log_warning(info_data, 'RGB Light: animations: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  247. animations[json_key] = config_c[config_key]
  248. if animations:
  249. rgblight['animations'] = animations
  250. if rgblight:
  251. info_data['rgblight'] = rgblight
  252. return info_data
  253. def _extract_pins(pins):
  254. """Returns a list of pins from a comma separated string of pins.
  255. """
  256. pins = [pin.strip() for pin in pins.split(',') if pin]
  257. for pin in pins:
  258. if pin[0] not in 'ABCDEFGHIJK' or not pin[1].isdigit():
  259. cli.log.warning(f'Nonstandard pin format: {pin}')
  260. return pins
  261. def _extract_direct_matrix(info_data, direct_pins):
  262. """
  263. """
  264. info_data['matrix_pins'] = {}
  265. direct_pin_array = []
  266. while direct_pins[-1] != '}':
  267. direct_pins = direct_pins[:-1]
  268. for row in direct_pins.split('},{'):
  269. if row.startswith('{'):
  270. row = row[1:]
  271. if row.endswith('}'):
  272. row = row[:-1]
  273. direct_pin_array.append([])
  274. for pin in row.split(','):
  275. if pin == 'NO_PIN':
  276. pin = None
  277. direct_pin_array[-1].append(pin)
  278. return direct_pin_array
  279. def _extract_matrix_info(info_data, config_c):
  280. """Populate the matrix information.
  281. """
  282. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  283. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  284. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  285. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  286. if 'matrix_size' in info_data:
  287. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  288. info_data['matrix_size'] = {
  289. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  290. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  291. }
  292. if row_pins and col_pins:
  293. if 'matrix_pins' in info_data:
  294. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  295. info_data['matrix_pins'] = {
  296. 'cols': _extract_pins(col_pins),
  297. 'rows': _extract_pins(row_pins),
  298. }
  299. if direct_pins:
  300. if 'matrix_pins' in info_data:
  301. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  302. info_data['matrix_pins']['direct'] = _extract_direct_matrix(info_data, direct_pins)
  303. return info_data
  304. def _extract_usb_info(info_data, config_c):
  305. """Populate the USB information.
  306. """
  307. if 'usb' not in info_data:
  308. info_data['usb'] = {}
  309. for info_name, config_name in usb_properties.items():
  310. if config_name in config_c:
  311. if info_name in info_data['usb']:
  312. _log_warning(info_data, '%s in config.h is overwriting usb.%s in info.json' % (config_name, info_name))
  313. info_data['usb'][info_name] = '0x' + config_c[config_name][2:].upper()
  314. return info_data
  315. def _extract_config_h(info_data):
  316. """Pull some keyboard information from existing config.h files
  317. """
  318. config_c = config_h(info_data['keyboard_folder'])
  319. _extract_debounce(info_data, config_c)
  320. _extract_diode_direction(info_data, config_c)
  321. _extract_indicators(info_data, config_c)
  322. _extract_matrix_info(info_data, config_c)
  323. _extract_usb_info(info_data, config_c)
  324. _extract_led_matrix(info_data, config_c)
  325. _extract_rgblight(info_data, config_c)
  326. return info_data
  327. def _extract_rules_mk(info_data):
  328. """Pull some keyboard information from existing rules.mk files
  329. """
  330. rules = rules_mk(info_data['keyboard_folder'])
  331. mcu = rules.get('MCU')
  332. if mcu in CHIBIOS_PROCESSORS:
  333. arm_processor_rules(info_data, rules)
  334. elif mcu in LUFA_PROCESSORS + VUSB_PROCESSORS:
  335. avr_processor_rules(info_data, rules)
  336. else:
  337. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], mcu))
  338. unknown_processor_rules(info_data, rules)
  339. _extract_community_layouts(info_data, rules)
  340. _extract_features(info_data, rules)
  341. _extract_led_drivers(info_data, rules)
  342. return info_data
  343. def _merge_layouts(info_data, new_info_data):
  344. """Merge new_info_data into info_data in an intelligent way.
  345. """
  346. for layout_name, layout_json in new_info_data['layouts'].items():
  347. if layout_name in info_data['layouts']:
  348. # Pull in layouts we have a macro for
  349. if len(info_data['layouts'][layout_name]['layout']) != len(layout_json['layout']):
  350. msg = '%s: %s: Number of elements in info.json does not match! info.json:%s != %s:%s'
  351. _log_error(info_data, msg % (info_data['keyboard_folder'], layout_name, len(layout_json['layout']), layout_name, len(info_data['layouts'][layout_name]['layout'])))
  352. else:
  353. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  354. key.update(layout_json['layout'][i])
  355. else:
  356. # Pull in layouts that have matrix data
  357. missing_matrix = False
  358. for key in layout_json.get('layout', {}):
  359. if 'matrix' not in key:
  360. missing_matrix = True
  361. if not missing_matrix:
  362. if layout_name in info_data['layouts']:
  363. # Update an existing layout with new data
  364. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  365. key.update(layout_json['layout'][i])
  366. else:
  367. # Copy in the new layout wholesale
  368. layout_json['c_macro'] = False
  369. info_data['layouts'][layout_name] = layout_json
  370. return info_data
  371. def _search_keyboard_h(path):
  372. current_path = Path('keyboards/')
  373. layouts = {}
  374. for directory in path.parts:
  375. current_path = current_path / directory
  376. keyboard_h = '%s.h' % (directory,)
  377. keyboard_h_path = current_path / keyboard_h
  378. if keyboard_h_path.exists():
  379. layouts.update(find_layouts(keyboard_h_path))
  380. return layouts
  381. def _find_all_layouts(info_data, keyboard):
  382. """Looks for layout macros associated with this keyboard.
  383. """
  384. layouts = _search_keyboard_h(Path(keyboard))
  385. if not layouts:
  386. # 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.
  387. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  388. for file in glob('keyboards/%s/*.h' % keyboard):
  389. if file.endswith('.h'):
  390. these_layouts = find_layouts(file)
  391. if these_layouts:
  392. layouts.update(these_layouts)
  393. return layouts
  394. def _log_error(info_data, message):
  395. """Send an error message to both JSON and the log.
  396. """
  397. info_data['parse_errors'].append(message)
  398. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  399. def _log_warning(info_data, message):
  400. """Send a warning message to both JSON and the log.
  401. """
  402. info_data['parse_warnings'].append(message)
  403. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  404. def arm_processor_rules(info_data, rules):
  405. """Setup the default info for an ARM board.
  406. """
  407. info_data['processor_type'] = 'arm'
  408. info_data['protocol'] = 'ChibiOS'
  409. if 'MCU' in rules:
  410. if 'processor' in info_data:
  411. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  412. info_data['processor'] = rules['MCU']
  413. elif 'processor' not in info_data:
  414. info_data['processor'] = 'unknown'
  415. if 'BOOTLOADER' in rules:
  416. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  417. # if 'bootloader' in info_data:
  418. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  419. info_data['bootloader'] = rules['BOOTLOADER']
  420. else:
  421. if 'STM32' in info_data['processor']:
  422. info_data['bootloader'] = 'stm32-dfu'
  423. else:
  424. info_data['bootloader'] = 'unknown'
  425. if 'STM32' in info_data['processor']:
  426. info_data['platform'] = 'STM32'
  427. elif 'MCU_SERIES' in rules:
  428. info_data['platform'] = rules['MCU_SERIES']
  429. elif 'ARM_ATSAM' in rules:
  430. info_data['platform'] = 'ARM_ATSAM'
  431. return info_data
  432. def avr_processor_rules(info_data, rules):
  433. """Setup the default info for an AVR board.
  434. """
  435. info_data['processor_type'] = 'avr'
  436. info_data['bootloader'] = rules['BOOTLOADER'] if 'BOOTLOADER' in rules else 'atmel-dfu'
  437. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  438. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  439. if 'MCU' in rules:
  440. if 'processor' in info_data:
  441. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  442. info_data['processor'] = rules['MCU']
  443. elif 'processor' not in info_data:
  444. info_data['processor'] = 'unknown'
  445. if 'BOOTLOADER' in rules:
  446. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  447. # if 'bootloader' in info_data:
  448. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  449. info_data['bootloader'] = rules['BOOTLOADER']
  450. else:
  451. info_data['bootloader'] = 'atmel-dfu'
  452. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  453. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  454. return info_data
  455. def unknown_processor_rules(info_data, rules):
  456. """Setup the default keyboard info for unknown boards.
  457. """
  458. info_data['bootloader'] = 'unknown'
  459. info_data['platform'] = 'unknown'
  460. info_data['processor'] = 'unknown'
  461. info_data['processor_type'] = 'unknown'
  462. info_data['protocol'] = 'unknown'
  463. return info_data
  464. def merge_info_jsons(keyboard, info_data):
  465. """Return a merged copy of all the info.json files for a keyboard.
  466. """
  467. for info_file in find_info_json(keyboard):
  468. # Load and validate the JSON data
  469. try:
  470. new_info_data = _json_load(info_file)
  471. keyboard_validate(new_info_data)
  472. except jsonschema.ValidationError as e:
  473. json_path = '.'.join([str(p) for p in e.absolute_path])
  474. cli.log.error('Invalid info.json data: %s: %s: %s', info_file, json_path, e.message)
  475. continue
  476. if not isinstance(new_info_data, dict):
  477. _log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  478. continue
  479. # Copy whitelisted keys into `info_data`
  480. for key in ('debounce', 'diode_direction', 'indicators', 'keyboard_name', 'manufacturer', 'identifier', 'url', 'maintainer', 'processor', 'bootloader', 'width', 'height'):
  481. if key in new_info_data:
  482. info_data[key] = new_info_data[key]
  483. # Deep merge certain keys
  484. # FIXME(skullydazed/anyone): this should be generalized more so that we can inteligently merge more than one level deep. It would be nice if we could filter on valid keys too. That may have to wait for a future where we use openapi or something.
  485. for key in ('features', 'layout_aliases', 'led_matrix', 'matrix_pins', 'rgblight', 'usb'):
  486. if key in new_info_data:
  487. if key not in info_data:
  488. info_data[key] = {}
  489. info_data[key].update(new_info_data[key])
  490. # Merge the layouts
  491. if 'community_layouts' in new_info_data:
  492. if 'community_layouts' in info_data:
  493. for layout in new_info_data['community_layouts']:
  494. if layout not in info_data['community_layouts']:
  495. info_data['community_layouts'].append(layout)
  496. else:
  497. info_data['community_layouts'] = new_info_data['community_layouts']
  498. if 'layouts' in new_info_data:
  499. _merge_layouts(info_data, new_info_data)
  500. return info_data
  501. def find_info_json(keyboard):
  502. """Finds all the info.json files associated with a keyboard.
  503. """
  504. # Find the most specific first
  505. base_path = Path('keyboards')
  506. keyboard_path = base_path / keyboard
  507. keyboard_parent = keyboard_path.parent
  508. info_jsons = [keyboard_path / 'info.json']
  509. # Add DEFAULT_FOLDER before parents, if present
  510. rules = rules_mk(keyboard)
  511. if 'DEFAULT_FOLDER' in rules:
  512. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  513. # Add in parent folders for least specific
  514. for _ in range(5):
  515. info_jsons.append(keyboard_parent / 'info.json')
  516. if keyboard_parent.parent == base_path:
  517. break
  518. keyboard_parent = keyboard_parent.parent
  519. # Return a list of the info.json files that actually exist
  520. return [info_json for info_json in info_jsons if info_json.exists()]