info.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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_matrix_info(info_data, config_c):
  254. """Populate the matrix information.
  255. """
  256. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  257. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  258. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  259. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  260. if 'matrix_size' in info_data:
  261. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  262. info_data['matrix_size'] = {
  263. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  264. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  265. }
  266. if row_pins and col_pins:
  267. if 'matrix_pins' in info_data:
  268. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  269. info_data['matrix_pins'] = {}
  270. # FIXME(skullydazed/anyone): Should really check every pin, not just the first
  271. if row_pins:
  272. row_pins = [pin.strip() for pin in row_pins.split(',') if pin]
  273. if row_pins[0][0] in 'ABCDEFGHIJK' and row_pins[0][1].isdigit():
  274. info_data['matrix_pins']['rows'] = row_pins
  275. if col_pins:
  276. col_pins = [pin.strip() for pin in col_pins.split(',') if pin]
  277. if col_pins[0][0] in 'ABCDEFGHIJK' and col_pins[0][1].isdigit():
  278. info_data['matrix_pins']['cols'] = col_pins
  279. if direct_pins:
  280. if 'matrix_pins' in info_data:
  281. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  282. info_data['matrix_pins'] = {}
  283. direct_pin_array = []
  284. while direct_pins[-1] != '}':
  285. direct_pins = direct_pins[:-1]
  286. for row in direct_pins.split('},{'):
  287. if row.startswith('{'):
  288. row = row[1:]
  289. if row.endswith('}'):
  290. row = row[:-1]
  291. direct_pin_array.append([])
  292. for pin in row.split(','):
  293. if pin == 'NO_PIN':
  294. pin = None
  295. direct_pin_array[-1].append(pin)
  296. info_data['matrix_pins']['direct'] = direct_pin_array
  297. return info_data
  298. def _extract_usb_info(info_data, config_c):
  299. """Populate the USB information.
  300. """
  301. if 'usb' not in info_data:
  302. info_data['usb'] = {}
  303. for info_name, config_name in usb_properties.items():
  304. if config_name in config_c:
  305. if info_name in info_data['usb']:
  306. _log_warning(info_data, '%s in config.h is overwriting usb.%s in info.json' % (config_name, info_name))
  307. info_data['usb'][info_name] = '0x' + config_c[config_name][2:].upper()
  308. return info_data
  309. def _extract_config_h(info_data):
  310. """Pull some keyboard information from existing config.h files
  311. """
  312. config_c = config_h(info_data['keyboard_folder'])
  313. _extract_debounce(info_data, config_c)
  314. _extract_diode_direction(info_data, config_c)
  315. _extract_indicators(info_data, config_c)
  316. _extract_matrix_info(info_data, config_c)
  317. _extract_usb_info(info_data, config_c)
  318. _extract_led_matrix(info_data, config_c)
  319. _extract_rgblight(info_data, config_c)
  320. return info_data
  321. def _extract_rules_mk(info_data):
  322. """Pull some keyboard information from existing rules.mk files
  323. """
  324. rules = rules_mk(info_data['keyboard_folder'])
  325. mcu = rules.get('MCU')
  326. if mcu in CHIBIOS_PROCESSORS:
  327. arm_processor_rules(info_data, rules)
  328. elif mcu in LUFA_PROCESSORS + VUSB_PROCESSORS:
  329. avr_processor_rules(info_data, rules)
  330. else:
  331. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], mcu))
  332. unknown_processor_rules(info_data, rules)
  333. _extract_community_layouts(info_data, rules)
  334. _extract_features(info_data, rules)
  335. _extract_led_drivers(info_data, rules)
  336. return info_data
  337. def _merge_layouts(info_data, new_info_data):
  338. """Merge new_info_data into info_data in an intelligent way.
  339. """
  340. for layout_name, layout_json in new_info_data['layouts'].items():
  341. if layout_name in info_data['layouts']:
  342. # Pull in layouts we have a macro for
  343. if len(info_data['layouts'][layout_name]['layout']) != len(layout_json['layout']):
  344. msg = '%s: %s: Number of elements in info.json does not match! info.json:%s != %s:%s'
  345. _log_error(info_data, msg % (info_data['keyboard_folder'], layout_name, len(layout_json['layout']), layout_name, len(info_data['layouts'][layout_name]['layout'])))
  346. else:
  347. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  348. key.update(layout_json['layout'][i])
  349. else:
  350. # Pull in layouts that have matrix data
  351. missing_matrix = False
  352. for key in layout_json.get('layout', {}):
  353. if 'matrix' not in key:
  354. missing_matrix = True
  355. if not missing_matrix:
  356. if layout_name in info_data['layouts']:
  357. # Update an existing layout with new data
  358. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  359. key.update(layout_json['layout'][i])
  360. else:
  361. # Copy in the new layout wholesale
  362. layout_json['c_macro'] = False
  363. info_data['layouts'][layout_name] = layout_json
  364. return info_data
  365. def _search_keyboard_h(path):
  366. current_path = Path('keyboards/')
  367. layouts = {}
  368. for directory in path.parts:
  369. current_path = current_path / directory
  370. keyboard_h = '%s.h' % (directory,)
  371. keyboard_h_path = current_path / keyboard_h
  372. if keyboard_h_path.exists():
  373. layouts.update(find_layouts(keyboard_h_path))
  374. return layouts
  375. def _find_all_layouts(info_data, keyboard):
  376. """Looks for layout macros associated with this keyboard.
  377. """
  378. layouts = _search_keyboard_h(Path(keyboard))
  379. if not layouts:
  380. # 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.
  381. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  382. for file in glob('keyboards/%s/*.h' % keyboard):
  383. if file.endswith('.h'):
  384. these_layouts = find_layouts(file)
  385. if these_layouts:
  386. layouts.update(these_layouts)
  387. return layouts
  388. def _log_error(info_data, message):
  389. """Send an error message to both JSON and the log.
  390. """
  391. info_data['parse_errors'].append(message)
  392. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  393. def _log_warning(info_data, message):
  394. """Send a warning message to both JSON and the log.
  395. """
  396. info_data['parse_warnings'].append(message)
  397. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  398. def arm_processor_rules(info_data, rules):
  399. """Setup the default info for an ARM board.
  400. """
  401. info_data['processor_type'] = 'arm'
  402. info_data['protocol'] = 'ChibiOS'
  403. if 'MCU' in rules:
  404. if 'processor' in info_data:
  405. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  406. info_data['processor'] = rules['MCU']
  407. elif 'processor' not in info_data:
  408. info_data['processor'] = 'unknown'
  409. if 'BOOTLOADER' in rules:
  410. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  411. # if 'bootloader' in info_data:
  412. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  413. info_data['bootloader'] = rules['BOOTLOADER']
  414. else:
  415. if 'STM32' in info_data['processor']:
  416. info_data['bootloader'] = 'stm32-dfu'
  417. else:
  418. info_data['bootloader'] = 'unknown'
  419. if 'STM32' in info_data['processor']:
  420. info_data['platform'] = 'STM32'
  421. elif 'MCU_SERIES' in rules:
  422. info_data['platform'] = rules['MCU_SERIES']
  423. elif 'ARM_ATSAM' in rules:
  424. info_data['platform'] = 'ARM_ATSAM'
  425. return info_data
  426. def avr_processor_rules(info_data, rules):
  427. """Setup the default info for an AVR board.
  428. """
  429. info_data['processor_type'] = 'avr'
  430. info_data['bootloader'] = rules['BOOTLOADER'] if 'BOOTLOADER' in rules else 'atmel-dfu'
  431. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  432. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  433. if 'MCU' in rules:
  434. if 'processor' in info_data:
  435. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  436. info_data['processor'] = rules['MCU']
  437. elif 'processor' not in info_data:
  438. info_data['processor'] = 'unknown'
  439. if 'BOOTLOADER' in rules:
  440. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  441. # if 'bootloader' in info_data:
  442. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  443. info_data['bootloader'] = rules['BOOTLOADER']
  444. else:
  445. info_data['bootloader'] = 'atmel-dfu'
  446. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  447. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  448. return info_data
  449. def unknown_processor_rules(info_data, rules):
  450. """Setup the default keyboard info for unknown boards.
  451. """
  452. info_data['bootloader'] = 'unknown'
  453. info_data['platform'] = 'unknown'
  454. info_data['processor'] = 'unknown'
  455. info_data['processor_type'] = 'unknown'
  456. info_data['protocol'] = 'unknown'
  457. return info_data
  458. def merge_info_jsons(keyboard, info_data):
  459. """Return a merged copy of all the info.json files for a keyboard.
  460. """
  461. for info_file in find_info_json(keyboard):
  462. # Load and validate the JSON data
  463. try:
  464. new_info_data = _json_load(info_file)
  465. keyboard_validate(new_info_data)
  466. except jsonschema.ValidationError as e:
  467. json_path = '.'.join([str(p) for p in e.absolute_path])
  468. cli.log.error('Invalid info.json data: %s: %s: %s', info_file, json_path, e.message)
  469. continue
  470. if not isinstance(new_info_data, dict):
  471. _log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  472. continue
  473. # Copy whitelisted keys into `info_data`
  474. for key in ('debounce', 'diode_direction', 'indicators', 'keyboard_name', 'manufacturer', 'identifier', 'url', 'maintainer', 'processor', 'bootloader', 'width', 'height'):
  475. if key in new_info_data:
  476. info_data[key] = new_info_data[key]
  477. # Deep merge certain keys
  478. # 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.
  479. for key in ('features', 'layout_aliases', 'led_matrix', 'matrix_pins', 'rgblight', 'usb'):
  480. if key in new_info_data:
  481. if key not in info_data:
  482. info_data[key] = {}
  483. info_data[key].update(new_info_data[key])
  484. # Merge the layouts
  485. if 'community_layouts' in new_info_data:
  486. if 'community_layouts' in info_data:
  487. for layout in new_info_data['community_layouts']:
  488. if layout not in info_data['community_layouts']:
  489. info_data['community_layouts'].append(layout)
  490. else:
  491. info_data['community_layouts'] = new_info_data['community_layouts']
  492. if 'layouts' in new_info_data:
  493. _merge_layouts(info_data, new_info_data)
  494. return info_data
  495. def find_info_json(keyboard):
  496. """Finds all the info.json files associated with a keyboard.
  497. """
  498. # Find the most specific first
  499. base_path = Path('keyboards')
  500. keyboard_path = base_path / keyboard
  501. keyboard_parent = keyboard_path.parent
  502. info_jsons = [keyboard_path / 'info.json']
  503. # Add DEFAULT_FOLDER before parents, if present
  504. rules = rules_mk(keyboard)
  505. if 'DEFAULT_FOLDER' in rules:
  506. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  507. # Add in parent folders for least specific
  508. for _ in range(5):
  509. info_jsons.append(keyboard_parent / 'info.json')
  510. if keyboard_parent.parent == base_path:
  511. break
  512. keyboard_parent = keyboard_parent.parent
  513. # Return a list of the info.json files that actually exist
  514. return [info_json for info_json in info_jsons if info_json.exists()]