info.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. """Functions that help us generate and use info.json files.
  2. """
  3. import re
  4. import os
  5. from pathlib import Path
  6. import jsonschema
  7. from dotty_dict import dotty
  8. from milc import cli
  9. from qmk.constants import COL_LETTERS, ROW_LETTERS, CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS, JOYSTICK_AXES
  10. from qmk.c_parse import find_layouts, parse_config_h_file, find_led_config
  11. from qmk.json_schema import deep_update, json_load, validate
  12. from qmk.keyboard import config_h, rules_mk
  13. from qmk.commands import parse_configurator_json
  14. from qmk.makefile import parse_rules_mk_file
  15. from qmk.math import compute
  16. from qmk.util import maybe_exit, truthy
  17. true_values = ['1', 'on', 'yes']
  18. false_values = ['0', 'off', 'no']
  19. def _keyboard_in_layout_name(keyboard, layout):
  20. """Validate that a layout macro does not contain name of keyboard
  21. """
  22. # TODO: reduce this list down
  23. safe_layout_tokens = {
  24. 'ansi',
  25. 'iso',
  26. 'jp',
  27. 'jis',
  28. 'ortho',
  29. 'wkl',
  30. 'tkl',
  31. 'preonic',
  32. 'planck',
  33. }
  34. # Ignore tokens like 'split_3x7_4' or just '2x4'
  35. layout = re.sub(r"_split_\d+x\d+_\d+", '', layout)
  36. layout = re.sub(r"_\d+x\d+", '', layout)
  37. name_fragments = set(keyboard.split('/')) - safe_layout_tokens
  38. return any(fragment in layout for fragment in name_fragments)
  39. def _valid_community_layout(layout):
  40. """Validate that a declared community list exists
  41. """
  42. return (Path('layouts/default') / layout).exists()
  43. def _get_key_left_position(key):
  44. # Special case for ISO enter
  45. return key['x'] - 0.25 if key.get('h', 1) == 2 and key.get('w', 1) == 1.25 else key['x']
  46. def _find_invalid_encoder_index(info_data):
  47. """Perform additional validation of encoders
  48. """
  49. enc_left = info_data.get('encoder', {}).get('rotary', [])
  50. enc_right = []
  51. if info_data.get('split', {}).get('enabled', False):
  52. enc_right = info_data.get('split', {}).get('encoder', {}).get('right', {}).get('rotary', enc_left)
  53. enc_count = len(enc_left) + len(enc_right)
  54. ret = []
  55. layouts = info_data.get('layouts', {})
  56. for layout_name, layout_data in layouts.items():
  57. found = set()
  58. for key in layout_data['layout']:
  59. if 'encoder' in key:
  60. if enc_count == 0:
  61. ret.append((layout_name, key['encoder'], 'non-configured'))
  62. elif key['encoder'] >= enc_count:
  63. ret.append((layout_name, key['encoder'], 'out of bounds'))
  64. elif key['encoder'] in found:
  65. ret.append((layout_name, key['encoder'], 'duplicate'))
  66. found.add(key['encoder'])
  67. return ret
  68. def _validate_build_target(keyboard, info_data):
  69. """Non schema checks
  70. """
  71. keyboard_json_path = Path('keyboards') / keyboard / 'keyboard.json'
  72. config_files = find_info_json(keyboard)
  73. # keyboard.json can only exist at the deepest part of the tree
  74. keyboard_json_count = 0
  75. for info_file in config_files:
  76. if info_file.name == 'keyboard.json':
  77. keyboard_json_count += 1
  78. if info_file != keyboard_json_path:
  79. _log_error(info_data, f'Invalid keyboard.json location detected: {info_file}.')
  80. # No keyboard.json next to info.json
  81. for conf_file in config_files:
  82. if conf_file.name == 'keyboard.json':
  83. info_file = conf_file.parent / 'info.json'
  84. if info_file.exists():
  85. _log_error(info_data, f'Invalid info.json location detected: {info_file}.')
  86. # Moving forward keyboard.json should be used as a build target
  87. if keyboard_json_count == 0:
  88. _log_warning(info_data, 'Build marker "keyboard.json" not found.')
  89. def _validate_layouts(keyboard, info_data): # noqa C901
  90. """Non schema checks
  91. """
  92. col_num = info_data.get('matrix_size', {}).get('cols', 0)
  93. row_num = info_data.get('matrix_size', {}).get('rows', 0)
  94. layouts = info_data.get('layouts', {})
  95. layout_aliases = info_data.get('layout_aliases', {})
  96. community_layouts = info_data.get('community_layouts', [])
  97. community_layouts_names = list(map(lambda layout: f'LAYOUT_{layout}', community_layouts))
  98. # Make sure we have at least one layout
  99. if len(layouts) == 0 or all(not layout.get('json_layout', False) for layout in layouts.values()):
  100. _log_error(info_data, 'No LAYOUTs defined! Need at least one layout defined in info.json.')
  101. # Make sure all layouts are DD
  102. for layout_name, layout_data in layouts.items():
  103. if layout_data.get('c_macro', False):
  104. _log_error(info_data, f'{layout_name}: Layout macro should not be defined within ".h" files.')
  105. # Make sure all matrix values are in bounds
  106. for layout_name, layout_data in layouts.items():
  107. for index, key_data in enumerate(layout_data['layout']):
  108. row, col = key_data['matrix']
  109. key_name = key_data.get('label', f'k{ROW_LETTERS[row]}{COL_LETTERS[col]}')
  110. if row >= row_num:
  111. _log_error(info_data, f'{layout_name}: Matrix row for key {index} ({key_name}) is {row} but must be less than {row_num}')
  112. if col >= col_num:
  113. _log_error(info_data, f'{layout_name}: Matrix column for key {index} ({key_name}) is {col} but must be less than {col_num}')
  114. # Reject duplicate matrix locations
  115. for layout_name, layout_data in layouts.items():
  116. seen = set()
  117. for index, key_data in enumerate(layout_data['layout']):
  118. key = f"{key_data['matrix']}"
  119. if key in seen:
  120. _log_error(info_data, f'{layout_name}: Matrix location for key {index} is not unique {key_data}')
  121. seen.add(key)
  122. # Warn if physical positions are offset (at least one key should be at x=0, and at least one key at y=0)
  123. for layout_name, layout_data in layouts.items():
  124. offset_x = min([_get_key_left_position(k) for k in layout_data['layout']])
  125. if offset_x > 0:
  126. _log_warning(info_data, f'Layout "{layout_name}" is offset on X axis by {offset_x}')
  127. offset_y = min([k['y'] for k in layout_data['layout']])
  128. if offset_y > 0:
  129. _log_warning(info_data, f'Layout "{layout_name}" is offset on Y axis by {offset_y}')
  130. # Providing only LAYOUT_all "because I define my layouts in a 3rd party tool"
  131. if len(layouts) == 1 and 'LAYOUT_all' in layouts:
  132. _log_warning(info_data, '"LAYOUT_all" should be "LAYOUT" unless additional layouts are provided.')
  133. # Extended layout name checks - ignoring community_layouts and "safe" values
  134. potential_layouts = set(layouts.keys()) - set(community_layouts_names)
  135. for layout in potential_layouts:
  136. if _keyboard_in_layout_name(keyboard, layout):
  137. _log_warning(info_data, f'Layout "{layout}" should not contain name of keyboard.')
  138. # Filter out any non-existing community layouts
  139. for layout in community_layouts:
  140. if not _valid_community_layout(layout):
  141. # Ignore layout from future checks
  142. info_data['community_layouts'].remove(layout)
  143. _log_error(info_data, 'Claims to support a community layout that does not exist: %s' % (layout))
  144. # Make sure we supply layout macros for the community layouts we claim to support
  145. for layout_name in community_layouts_names:
  146. if layout_name not in layouts and layout_name not in layout_aliases:
  147. _log_error(info_data, 'Claims to support community layout %s but no %s() macro found' % (layout, layout_name))
  148. def _validate_keycodes(keyboard, info_data):
  149. """Non schema checks
  150. """
  151. # keycodes with length > 7 must have short forms for visualisation purposes
  152. for decl in info_data.get('keycodes', []):
  153. if len(decl["key"]) > 7:
  154. if not decl.get("aliases", []):
  155. _log_error(info_data, f'Keycode {decl["key"]} has no short form alias')
  156. def _validate_encoders(keyboard, info_data):
  157. """Non schema checks
  158. """
  159. # encoder IDs in layouts must be in range and not duplicated
  160. found = _find_invalid_encoder_index(info_data)
  161. for layout_name, encoder_index, reason in found:
  162. _log_error(info_data, f'Layout "{layout_name}" contains {reason} encoder index {encoder_index}.')
  163. def _validate(keyboard, info_data):
  164. """Perform various validation on the provided info.json data
  165. """
  166. # First validate against the jsonschema
  167. try:
  168. validate(info_data, 'qmk.api.keyboard.v1')
  169. # Additional validation
  170. _validate_build_target(keyboard, info_data)
  171. _validate_layouts(keyboard, info_data)
  172. _validate_keycodes(keyboard, info_data)
  173. _validate_encoders(keyboard, info_data)
  174. except jsonschema.ValidationError as e:
  175. json_path = '.'.join([str(p) for p in e.absolute_path])
  176. cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
  177. maybe_exit(1)
  178. def info_json(keyboard, force_layout=None):
  179. """Generate the info.json data for a specific keyboard.
  180. """
  181. info_data = {
  182. 'keyboard_name': str(keyboard),
  183. 'keyboard_folder': str(keyboard),
  184. 'keymaps': {},
  185. 'layouts': {},
  186. 'parse_errors': [],
  187. 'parse_warnings': [],
  188. 'maintainer': 'qmk',
  189. }
  190. # Populate layout data
  191. layouts, aliases = _search_keyboard_h(keyboard)
  192. if aliases:
  193. info_data['layout_aliases'] = aliases
  194. for layout_name, layout_json in layouts.items():
  195. if not layout_name.startswith('LAYOUT_kc'):
  196. layout_json['c_macro'] = True
  197. layout_json['json_layout'] = False
  198. info_data['layouts'][layout_name] = layout_json
  199. # Merge in the data from info.json, config.h, and rules.mk
  200. info_data = merge_info_jsons(keyboard, info_data)
  201. info_data = _process_defaults(info_data)
  202. info_data = _extract_rules_mk(info_data, rules_mk(str(keyboard)))
  203. info_data = _extract_config_h(info_data, config_h(str(keyboard)))
  204. # Ensure that we have various calculated values
  205. info_data = _matrix_size(info_data)
  206. info_data = _joystick_axis_count(info_data)
  207. # Merge in data from <keyboard.c>
  208. info_data = _extract_led_config(info_data, str(keyboard))
  209. # Force a community layout if requested
  210. community_layouts = info_data.get("community_layouts", [])
  211. if force_layout in community_layouts:
  212. info_data["community_layouts"] = [force_layout]
  213. # Validate
  214. # Skip processing if necessary
  215. if not truthy(os.environ.get('SKIP_SCHEMA_VALIDATION'), False):
  216. _validate(keyboard, info_data)
  217. # Check that the reported matrix size is consistent with the actual matrix size
  218. _check_matrix(info_data)
  219. return info_data
  220. def _extract_features(info_data, rules):
  221. """Find all the features enabled in rules.mk.
  222. """
  223. # Process booleans rules
  224. for key, value in rules.items():
  225. if key.endswith('_ENABLE'):
  226. key = '_'.join(key.split('_')[:-1]).lower()
  227. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  228. if key in ['lto']:
  229. continue
  230. if 'config_h_features' not in info_data:
  231. info_data['config_h_features'] = {}
  232. if 'features' not in info_data:
  233. info_data['features'] = {}
  234. if key in info_data['features']:
  235. _log_warning(info_data, 'Feature %s is specified in both info.json (%s) and rules.mk (%s). The rules.mk value wins.' % (key, info_data['features'], value))
  236. info_data['features'][key] = value
  237. info_data['config_h_features'][key] = value
  238. return info_data
  239. def _pin_name(pin):
  240. """Returns the proper representation for a pin.
  241. """
  242. pin = pin.strip()
  243. if not pin:
  244. return None
  245. elif pin.isdigit():
  246. return int(pin)
  247. elif pin == 'NO_PIN':
  248. return None
  249. return pin
  250. def _extract_pins(pins):
  251. """Returns a list of pins from a comma separated string of pins.
  252. """
  253. return [_pin_name(pin) for pin in pins.split(',')]
  254. def _extract_2d_array(raw):
  255. """Return a 2d array of strings
  256. """
  257. out_array = []
  258. while raw[-1] != '}':
  259. raw = raw[:-1]
  260. for row in raw.split('},{'):
  261. if row.startswith('{'):
  262. row = row[1:]
  263. if row.endswith('}'):
  264. row = row[:-1]
  265. out_array.append([])
  266. for val in row.split(','):
  267. out_array[-1].append(val)
  268. return out_array
  269. def _extract_2d_int_array(raw):
  270. """Return a 2d array of ints
  271. """
  272. ret = _extract_2d_array(raw)
  273. return [list(map(int, x)) for x in ret]
  274. def _extract_direct_matrix(direct_pins):
  275. """extract direct_matrix
  276. """
  277. direct_pin_array = _extract_2d_array(direct_pins)
  278. for i in range(len(direct_pin_array)):
  279. for j in range(len(direct_pin_array[i])):
  280. if direct_pin_array[i][j] == 'NO_PIN':
  281. direct_pin_array[i][j] = None
  282. return direct_pin_array
  283. def _extract_audio(info_data, config_c):
  284. """Populate data about the audio configuration
  285. """
  286. audio_pins = []
  287. for pin in 'B5', 'B6', 'B7', 'C4', 'C5', 'C6':
  288. if config_c.get(f'{pin}_AUDIO'):
  289. audio_pins.append(pin)
  290. if audio_pins:
  291. info_data['audio'] = {'pins': audio_pins}
  292. def _extract_encoders_values(config_c, postfix=''):
  293. """Common encoder extraction logic
  294. """
  295. a_pad = config_c.get(f'ENCODER_A_PINS{postfix}', '').replace(' ', '')[1:-1]
  296. b_pad = config_c.get(f'ENCODER_B_PINS{postfix}', '').replace(' ', '')[1:-1]
  297. resolutions = config_c.get(f'ENCODER_RESOLUTIONS{postfix}', '').replace(' ', '')[1:-1]
  298. default_resolution = config_c.get('ENCODER_RESOLUTION', None)
  299. if a_pad and b_pad:
  300. a_pad = list(filter(None, a_pad.split(',')))
  301. b_pad = list(filter(None, b_pad.split(',')))
  302. resolutions = list(filter(None, resolutions.split(',')))
  303. if default_resolution:
  304. resolutions += [default_resolution] * (len(a_pad) - len(resolutions))
  305. encoders = []
  306. for index in range(len(a_pad)):
  307. encoder = {'pin_a': a_pad[index], 'pin_b': b_pad[index]}
  308. if index < len(resolutions):
  309. encoder['resolution'] = int(resolutions[index])
  310. encoders.append(encoder)
  311. return encoders
  312. def _extract_encoders(info_data, config_c):
  313. """Populate data about encoder pins
  314. """
  315. encoders = _extract_encoders_values(config_c)
  316. if encoders:
  317. if 'encoder' not in info_data:
  318. info_data['encoder'] = {}
  319. if 'rotary' in info_data['encoder']:
  320. _log_warning(info_data, 'Encoder config is specified in both config.h (%s) and info.json (%s). The config.h value wins.' % (encoders, info_data['encoder']['rotary']))
  321. info_data['encoder']['rotary'] = encoders
  322. # TODO: some logic still assumes ENCODER_ENABLED would partially create encoder dict
  323. if info_data.get('features', {}).get('encoder', False):
  324. if 'encoder' not in info_data:
  325. info_data['encoder'] = {}
  326. info_data['encoder']['enabled'] = True
  327. def _extract_split_encoders(info_data, config_c):
  328. """Populate data about split encoder pins
  329. """
  330. encoders = _extract_encoders_values(config_c, '_RIGHT')
  331. if encoders:
  332. if 'split' not in info_data:
  333. info_data['split'] = {}
  334. if 'encoder' not in info_data['split']:
  335. info_data['split']['encoder'] = {}
  336. if 'right' not in info_data['split']['encoder']:
  337. info_data['split']['encoder']['right'] = {}
  338. if 'rotary' in info_data['split']['encoder']['right']:
  339. _log_warning(info_data, 'Encoder config is specified in both config.h and info.json (encoder.rotary) (Value: %s), the config.h value wins.' % info_data['split']['encoder']['right']['rotary'])
  340. info_data['split']['encoder']['right']['rotary'] = encoders
  341. def _extract_secure_unlock(info_data, config_c):
  342. """Populate data about the secure unlock sequence
  343. """
  344. unlock = config_c.get('SECURE_UNLOCK_SEQUENCE', '').replace(' ', '')[1:-1]
  345. if unlock:
  346. unlock_array = _extract_2d_int_array(unlock)
  347. if 'secure' not in info_data:
  348. info_data['secure'] = {}
  349. if 'unlock_sequence' in info_data['secure']:
  350. _log_warning(info_data, 'Secure unlock sequence is specified in both config.h (SECURE_UNLOCK_SEQUENCE) and info.json (secure.unlock_sequence) (Value: %s), the config.h value wins.' % info_data['secure']['unlock_sequence'])
  351. info_data['secure']['unlock_sequence'] = unlock_array
  352. def _extract_split_handedness(info_data, config_c):
  353. # Migrate
  354. split = info_data.get('split', {})
  355. if 'matrix_grid' in split:
  356. split['handedness'] = split.get('handedness', {})
  357. split['handedness']['matrix_grid'] = split.pop('matrix_grid')
  358. def _extract_split_serial(info_data, config_c):
  359. # Migrate
  360. split = info_data.get('split', {})
  361. if 'soft_serial_pin' in split:
  362. split['serial'] = split.get('serial', {})
  363. split['serial']['pin'] = split.pop('soft_serial_pin')
  364. def _extract_split_transport(info_data, config_c):
  365. # Figure out the transport method
  366. if config_c.get('USE_I2C') is True:
  367. if 'split' not in info_data:
  368. info_data['split'] = {}
  369. if 'transport' not in info_data['split']:
  370. info_data['split']['transport'] = {}
  371. if 'protocol' in info_data['split']['transport']:
  372. _log_warning(info_data, 'Split transport is specified in both config.h (USE_I2C) and info.json (split.transport.protocol) (Value: %s), the config.h value wins.' % info_data['split']['transport'])
  373. info_data['split']['transport']['protocol'] = 'i2c'
  374. # Ignore transport defaults if "SPLIT_KEYBOARD" is unset
  375. elif 'enabled' in info_data.get('split', {}):
  376. if 'split' not in info_data:
  377. info_data['split'] = {}
  378. if 'transport' not in info_data['split']:
  379. info_data['split']['transport'] = {}
  380. if 'protocol' not in info_data['split']['transport']:
  381. info_data['split']['transport']['protocol'] = 'serial'
  382. # Migrate
  383. transport = info_data.get('split', {}).get('transport', {})
  384. if 'sync_matrix_state' in transport:
  385. transport['sync'] = transport.get('sync', {})
  386. transport['sync']['matrix_state'] = transport.pop('sync_matrix_state')
  387. if 'sync_modifiers' in transport:
  388. transport['sync'] = transport.get('sync', {})
  389. transport['sync']['modifiers'] = transport.pop('sync_modifiers')
  390. def _extract_split_right_pins(info_data, config_c):
  391. # Figure out the right half matrix pins
  392. row_pins = config_c.get('MATRIX_ROW_PINS_RIGHT', '').replace('{', '').replace('}', '').strip()
  393. col_pins = config_c.get('MATRIX_COL_PINS_RIGHT', '').replace('{', '').replace('}', '').strip()
  394. direct_pins = config_c.get('DIRECT_PINS_RIGHT', '').replace(' ', '')[1:-1]
  395. if row_pins or col_pins or direct_pins:
  396. if info_data.get('split', {}).get('matrix_pins', {}).get('right', None):
  397. _log_warning(info_data, 'Right hand matrix data is specified in both info.json and config.h, the config.h values win.')
  398. if 'split' not in info_data:
  399. info_data['split'] = {}
  400. if 'matrix_pins' not in info_data['split']:
  401. info_data['split']['matrix_pins'] = {}
  402. if 'right' not in info_data['split']['matrix_pins']:
  403. info_data['split']['matrix_pins']['right'] = {}
  404. if col_pins:
  405. info_data['split']['matrix_pins']['right']['cols'] = _extract_pins(col_pins)
  406. if row_pins:
  407. info_data['split']['matrix_pins']['right']['rows'] = _extract_pins(row_pins)
  408. if direct_pins:
  409. info_data['split']['matrix_pins']['right']['direct'] = _extract_direct_matrix(direct_pins)
  410. def _extract_matrix_info(info_data, config_c):
  411. """Populate the matrix information.
  412. """
  413. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  414. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  415. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  416. info_snippet = {}
  417. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  418. if 'matrix_size' in info_data:
  419. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  420. info_data['matrix_size'] = {
  421. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  422. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  423. }
  424. if row_pins and col_pins:
  425. if 'matrix_pins' in info_data and 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  426. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  427. info_snippet['cols'] = _extract_pins(col_pins)
  428. info_snippet['rows'] = _extract_pins(row_pins)
  429. if direct_pins:
  430. if 'matrix_pins' in info_data and 'direct' in info_data['matrix_pins']:
  431. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  432. info_snippet['direct'] = _extract_direct_matrix(direct_pins)
  433. if config_c.get('CUSTOM_MATRIX', 'no') != 'no':
  434. if 'matrix_pins' in info_data and 'custom' in info_data['matrix_pins']:
  435. _log_warning(info_data, 'Custom Matrix is specified in both info.json and config.h, the config.h values win.')
  436. info_snippet['custom'] = True
  437. if config_c['CUSTOM_MATRIX'] == 'lite':
  438. info_snippet['custom_lite'] = True
  439. if info_snippet:
  440. info_data['matrix_pins'] = info_snippet
  441. return info_data
  442. def _config_to_json(key_type, config_value):
  443. """Convert config value using spec
  444. """
  445. if key_type.startswith('array'):
  446. if key_type.count('.') > 1:
  447. raise Exception(f"Conversion of {key_type} not possible")
  448. if '.' in key_type:
  449. key_type, array_type = key_type.split('.', 1)
  450. else:
  451. array_type = None
  452. config_value = config_value.replace('{', '').replace('}', '').strip()
  453. if array_type == 'int':
  454. return list(map(int, config_value.split(',')))
  455. else:
  456. return list(map(str.strip, config_value.split(',')))
  457. elif key_type in ['bool', 'flag']:
  458. if isinstance(config_value, bool):
  459. return config_value
  460. return config_value in true_values
  461. elif key_type == 'hex':
  462. return '0x' + config_value[2:].upper()
  463. elif key_type == 'list':
  464. return config_value.split()
  465. elif key_type == 'int':
  466. return int(config_value)
  467. elif key_type == 'str':
  468. return config_value.strip('"').replace('\\"', '"').replace('\\\\', '\\')
  469. elif key_type == 'bcd_version':
  470. major = int(config_value[2:4])
  471. minor = int(config_value[4])
  472. revision = int(config_value[5])
  473. return f'{major}.{minor}.{revision}'
  474. return config_value
  475. def _extract_config_h(info_data, config_c):
  476. """Pull some keyboard information from existing config.h files
  477. """
  478. # Pull in data from the json map
  479. dotty_info = dotty(info_data)
  480. info_config_map = json_load(Path('data/mappings/info_config.hjson'))
  481. for config_key, info_dict in info_config_map.items():
  482. info_key = info_dict['info_key']
  483. key_type = info_dict.get('value_type', 'raw')
  484. try:
  485. replace_with = info_dict.get('replace_with')
  486. if config_key in config_c and info_dict.get('invalid', False):
  487. if replace_with:
  488. _log_error(info_data, '%s in config.h is no longer a valid option and should be replaced with %s' % (config_key, replace_with))
  489. else:
  490. _log_error(info_data, '%s in config.h is no longer a valid option and should be removed' % config_key)
  491. elif config_key in config_c and info_dict.get('deprecated', False):
  492. if replace_with:
  493. _log_warning(info_data, '%s in config.h is deprecated in favor of %s and will be removed at a later date' % (config_key, replace_with))
  494. else:
  495. _log_warning(info_data, '%s in config.h is deprecated and will be removed at a later date' % config_key)
  496. if config_key in config_c and info_dict.get('to_json', True):
  497. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  498. _log_warning(info_data, '%s in config.h is overwriting %s in info.json' % (config_key, info_key))
  499. dotty_info[info_key] = _config_to_json(key_type, config_c[config_key])
  500. except Exception as e:
  501. _log_warning(info_data, f'{config_key}->{info_key}: {e}')
  502. info_data.update(dotty_info)
  503. # Pull data that easily can't be mapped in json
  504. _extract_matrix_info(info_data, config_c)
  505. _extract_audio(info_data, config_c)
  506. _extract_secure_unlock(info_data, config_c)
  507. _extract_split_handedness(info_data, config_c)
  508. _extract_split_serial(info_data, config_c)
  509. _extract_split_transport(info_data, config_c)
  510. _extract_split_right_pins(info_data, config_c)
  511. _extract_encoders(info_data, config_c)
  512. _extract_split_encoders(info_data, config_c)
  513. return info_data
  514. def _process_defaults(info_data):
  515. """Process any additional defaults based on currently discovered information
  516. """
  517. defaults_map = json_load(Path('data/mappings/defaults.hjson'))
  518. for default_type in defaults_map.keys():
  519. thing_map = defaults_map[default_type]
  520. if default_type in info_data:
  521. merged_count = 0
  522. thing_items = thing_map.get(info_data[default_type], {}).items()
  523. for key, value in thing_items:
  524. if key not in info_data:
  525. info_data[key] = value
  526. merged_count += 1
  527. if merged_count == 0 and len(thing_items) > 0:
  528. _log_warning(info_data, 'All defaults for \'%s\' were skipped, potential redundant config or misconfiguration detected' % (default_type))
  529. return info_data
  530. def _extract_rules_mk(info_data, rules):
  531. """Pull some keyboard information from existing rules.mk files
  532. """
  533. info_data['processor'] = rules.get('MCU', info_data.get('processor', 'atmega32u4'))
  534. if info_data['processor'] in CHIBIOS_PROCESSORS:
  535. arm_processor_rules(info_data, rules)
  536. elif info_data['processor'] in LUFA_PROCESSORS + VUSB_PROCESSORS:
  537. avr_processor_rules(info_data, rules)
  538. else:
  539. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], info_data['processor']))
  540. unknown_processor_rules(info_data, rules)
  541. # Pull in data from the json map
  542. dotty_info = dotty(info_data)
  543. info_rules_map = json_load(Path('data/mappings/info_rules.hjson'))
  544. for rules_key, info_dict in info_rules_map.items():
  545. info_key = info_dict['info_key']
  546. key_type = info_dict.get('value_type', 'raw')
  547. try:
  548. replace_with = info_dict.get('replace_with')
  549. if rules_key in rules and info_dict.get('invalid', False):
  550. if replace_with:
  551. _log_error(info_data, '%s in rules.mk is no longer a valid option and should be replaced with %s' % (rules_key, replace_with))
  552. else:
  553. _log_error(info_data, '%s in rules.mk is no longer a valid option and should be removed' % rules_key)
  554. elif rules_key in rules and info_dict.get('deprecated', False):
  555. if replace_with:
  556. _log_warning(info_data, '%s in rules.mk is deprecated in favor of %s and will be removed at a later date' % (rules_key, replace_with))
  557. else:
  558. _log_warning(info_data, '%s in rules.mk is deprecated and will be removed at a later date' % rules_key)
  559. if rules_key in rules and info_dict.get('to_json', True):
  560. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  561. _log_warning(info_data, '%s in rules.mk is overwriting %s in info.json' % (rules_key, info_key))
  562. dotty_info[info_key] = _config_to_json(key_type, rules[rules_key])
  563. except Exception as e:
  564. _log_warning(info_data, f'{rules_key}->{info_key}: {e}')
  565. info_data.update(dotty_info)
  566. # Merge in config values that can't be easily mapped
  567. _extract_features(info_data, rules)
  568. return info_data
  569. def find_keyboard_c(keyboard):
  570. """Find all <keyboard>.c files
  571. """
  572. keyboard = Path(keyboard)
  573. current_path = Path('keyboards/')
  574. files = []
  575. for directory in keyboard.parts:
  576. current_path = current_path / directory
  577. keyboard_c_path = current_path / f'{directory}.c'
  578. if keyboard_c_path.exists():
  579. files.append(keyboard_c_path)
  580. return files
  581. def _extract_led_config(info_data, keyboard):
  582. """Scan all <keyboard>.c files for led config
  583. """
  584. for feature in ['rgb_matrix', 'led_matrix']:
  585. if info_data.get('features', {}).get(feature, False) or feature in info_data:
  586. # Only attempt search if dd led config is missing
  587. if 'layout' not in info_data.get(feature, {}):
  588. cols = info_data.get('matrix_size', {}).get('cols')
  589. rows = info_data.get('matrix_size', {}).get('rows')
  590. if cols and rows:
  591. # Process
  592. for file in find_keyboard_c(keyboard):
  593. try:
  594. ret = find_led_config(file, cols, rows)
  595. if ret:
  596. info_data[feature] = info_data.get(feature, {})
  597. info_data[feature]['layout'] = ret
  598. except Exception as e:
  599. _log_warning(info_data, f'led_config: {file.name}: {e}')
  600. else:
  601. _log_warning(info_data, 'led_config: matrix size required to parse g_led_config')
  602. if info_data[feature].get('layout', None) and not info_data[feature].get('led_count', None):
  603. info_data[feature]['led_count'] = len(info_data[feature]['layout'])
  604. return info_data
  605. def _matrix_size(info_data):
  606. """Add info_data['matrix_size'] if it doesn't exist.
  607. """
  608. if 'matrix_size' not in info_data and 'matrix_pins' in info_data:
  609. info_data['matrix_size'] = {}
  610. if 'direct' in info_data['matrix_pins']:
  611. info_data['matrix_size']['cols'] = len(info_data['matrix_pins']['direct'][0])
  612. info_data['matrix_size']['rows'] = len(info_data['matrix_pins']['direct'])
  613. elif 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  614. info_data['matrix_size']['cols'] = len(info_data['matrix_pins']['cols'])
  615. info_data['matrix_size']['rows'] = len(info_data['matrix_pins']['rows'])
  616. # Assumption of split common
  617. if 'split' in info_data:
  618. if info_data['split'].get('enabled', False):
  619. info_data['matrix_size']['rows'] *= 2
  620. return info_data
  621. def _joystick_axis_count(info_data):
  622. """Add info_data['joystick.axis_count'] if required
  623. """
  624. if 'axes' in info_data.get('joystick', {}):
  625. axes_keys = info_data['joystick']['axes'].keys()
  626. info_data['joystick']['axis_count'] = max(JOYSTICK_AXES.index(a) for a in axes_keys) + 1 if axes_keys else 0
  627. return info_data
  628. def _check_matrix(info_data):
  629. """Check the matrix to ensure that row/column count is consistent.
  630. """
  631. if 'matrix_pins' in info_data and 'matrix_size' in info_data:
  632. actual_col_count = info_data['matrix_size'].get('cols', 0)
  633. actual_row_count = info_data['matrix_size'].get('rows', 0)
  634. col_count = row_count = 0
  635. if 'direct' in info_data['matrix_pins']:
  636. col_count = len(info_data['matrix_pins']['direct'][0])
  637. row_count = len(info_data['matrix_pins']['direct'])
  638. elif 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  639. col_count = len(info_data['matrix_pins']['cols'])
  640. row_count = len(info_data['matrix_pins']['rows'])
  641. elif 'cols' not in info_data['matrix_pins'] and 'rows' not in info_data['matrix_pins']:
  642. # This case caters for custom matrix implementations where normal rows/cols are specified
  643. return
  644. if col_count != actual_col_count and col_count != (actual_col_count / 2):
  645. # FIXME: once we can we should detect if split is enabled to do the actual_col_count/2 check.
  646. _log_error(info_data, f'MATRIX_COLS is inconsistent with the size of MATRIX_COL_PINS: {col_count} != {actual_col_count}')
  647. if row_count != actual_row_count and row_count != (actual_row_count / 2):
  648. # FIXME: once we can we should detect if split is enabled to do the actual_row_count/2 check.
  649. _log_error(info_data, f'MATRIX_ROWS is inconsistent with the size of MATRIX_ROW_PINS: {row_count} != {actual_row_count}')
  650. def _search_keyboard_h(keyboard):
  651. keyboard = Path(keyboard)
  652. current_path = Path('keyboards/')
  653. aliases = {}
  654. layouts = {}
  655. for directory in keyboard.parts:
  656. current_path = current_path / directory
  657. keyboard_h = '%s.h' % (directory,)
  658. keyboard_h_path = current_path / keyboard_h
  659. if keyboard_h_path.exists():
  660. new_layouts, new_aliases = find_layouts(keyboard_h_path)
  661. layouts.update(new_layouts)
  662. for alias, alias_text in new_aliases.items():
  663. if alias_text in layouts:
  664. aliases[alias] = alias_text
  665. return layouts, aliases
  666. def _log_error(info_data, message):
  667. """Send an error message to both JSON and the log.
  668. """
  669. info_data['parse_errors'].append(message)
  670. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  671. def _log_warning(info_data, message):
  672. """Send a warning message to both JSON and the log.
  673. """
  674. info_data['parse_warnings'].append(message)
  675. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  676. def arm_processor_rules(info_data, rules):
  677. """Setup the default info for an ARM board.
  678. """
  679. info_data['processor_type'] = 'arm'
  680. info_data['protocol'] = 'ChibiOS'
  681. info_data['platform_key'] = 'chibios'
  682. if 'STM32' in info_data['processor']:
  683. info_data['platform'] = 'STM32'
  684. elif 'MCU_SERIES' in rules:
  685. info_data['platform'] = rules['MCU_SERIES']
  686. return info_data
  687. def avr_processor_rules(info_data, rules):
  688. """Setup the default info for an AVR board.
  689. """
  690. info_data['processor_type'] = 'avr'
  691. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  692. info_data['platform_key'] = 'avr'
  693. info_data['protocol'] = 'V-USB' if info_data['processor'] in VUSB_PROCESSORS else 'LUFA'
  694. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  695. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  696. return info_data
  697. def unknown_processor_rules(info_data, rules):
  698. """Setup the default keyboard info for unknown boards.
  699. """
  700. info_data['bootloader'] = 'unknown'
  701. info_data['platform'] = 'unknown'
  702. info_data['processor'] = 'unknown'
  703. info_data['processor_type'] = 'unknown'
  704. info_data['protocol'] = 'unknown'
  705. return info_data
  706. def merge_info_jsons(keyboard, info_data):
  707. """Return a merged copy of all the info.json files for a keyboard.
  708. """
  709. config_files = find_info_json(keyboard)
  710. for info_file in config_files:
  711. # Load and validate the JSON data
  712. new_info_data = json_load(info_file)
  713. if not isinstance(new_info_data, dict):
  714. _log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  715. continue
  716. if not truthy(os.environ.get('SKIP_SCHEMA_VALIDATION'), False):
  717. try:
  718. validate(new_info_data, 'qmk.keyboard.v1')
  719. except jsonschema.ValidationError as e:
  720. json_path = '.'.join([str(p) for p in e.absolute_path])
  721. cli.log.error('Not including data from file: %s', info_file)
  722. cli.log.error('\t%s: %s', json_path, e.message)
  723. continue
  724. # Merge layout data in
  725. if 'layout_aliases' in new_info_data:
  726. info_data['layout_aliases'] = {**info_data.get('layout_aliases', {}), **new_info_data['layout_aliases']}
  727. del new_info_data['layout_aliases']
  728. for layout_name, layout in new_info_data.get('layouts', {}).items():
  729. if layout_name in info_data.get('layout_aliases', {}):
  730. _log_warning(info_data, f"info.json uses alias name {layout_name} instead of {info_data['layout_aliases'][layout_name]}")
  731. layout_name = info_data['layout_aliases'][layout_name]
  732. if layout_name in info_data['layouts']:
  733. if len(info_data['layouts'][layout_name]['layout']) != len(layout['layout']):
  734. msg = 'Number of keys for %s does not match! info.json specifies %d keys, C macro specifies %d'
  735. _log_error(info_data, msg % (layout_name, len(layout['layout']), len(info_data['layouts'][layout_name]['layout'])))
  736. else:
  737. info_data['layouts'][layout_name]['json_layout'] = True
  738. for new_key, existing_key in zip(layout['layout'], info_data['layouts'][layout_name]['layout']):
  739. existing_key.update(new_key)
  740. else:
  741. if not all('matrix' in key_data.keys() for key_data in layout['layout']):
  742. _log_error(info_data, f'Layout "{layout_name}" has no "matrix" definition in either "info.json" or "<keyboard>.h"!')
  743. else:
  744. layout['c_macro'] = False
  745. layout['json_layout'] = True
  746. info_data['layouts'][layout_name] = layout
  747. # Update info_data with the new data
  748. if 'layouts' in new_info_data:
  749. del new_info_data['layouts']
  750. deep_update(info_data, new_info_data)
  751. return info_data
  752. def find_info_json(keyboard):
  753. """Finds all the info.json files associated with a keyboard.
  754. """
  755. # Find the most specific first
  756. base_path = Path('keyboards')
  757. keyboard_path = base_path / keyboard
  758. keyboard_parent = keyboard_path.parent
  759. info_jsons = [keyboard_path / 'info.json', keyboard_path / 'keyboard.json']
  760. # Add in parent folders for least specific
  761. for _ in range(5):
  762. if keyboard_parent == base_path:
  763. break
  764. info_jsons.append(keyboard_parent / 'info.json')
  765. info_jsons.append(keyboard_parent / 'keyboard.json')
  766. keyboard_parent = keyboard_parent.parent
  767. # Return a list of the info.json files that actually exist
  768. return [info_json for info_json in info_jsons if info_json.exists()]
  769. def keymap_json_config(keyboard, keymap, force_layout=None):
  770. """Extract keymap level config
  771. """
  772. # TODO: resolve keymap.py and info.py circular dependencies
  773. from qmk.keymap import locate_keymap
  774. keymap_folder = locate_keymap(keyboard, keymap, force_layout=force_layout).parent
  775. km_info_json = parse_configurator_json(keymap_folder / 'keymap.json')
  776. return km_info_json.get('config', {})
  777. def keymap_json(keyboard, keymap, force_layout=None):
  778. """Generate the info.json data for a specific keymap.
  779. """
  780. # TODO: resolve keymap.py and info.py circular dependencies
  781. from qmk.keymap import locate_keymap
  782. keymap_folder = locate_keymap(keyboard, keymap, force_layout=force_layout).parent
  783. # Files to scan
  784. keymap_config = keymap_folder / 'config.h'
  785. keymap_rules = keymap_folder / 'rules.mk'
  786. keymap_file = keymap_folder / 'keymap.json'
  787. # Build the info.json file
  788. kb_info_json = info_json(keyboard, force_layout=force_layout)
  789. # Merge in the data from keymap.json
  790. km_info_json = keymap_json_config(keyboard, keymap, force_layout=force_layout) if keymap_file.exists() else {}
  791. deep_update(kb_info_json, km_info_json)
  792. # Merge in the data from config.h, and rules.mk
  793. _extract_rules_mk(kb_info_json, parse_rules_mk_file(keymap_rules))
  794. _extract_config_h(kb_info_json, parse_config_h_file(keymap_config))
  795. return kb_info_json
  796. def get_modules(keyboard, keymap_filename):
  797. """Get the modules for a keyboard/keymap.
  798. """
  799. modules = []
  800. kb_info_json = info_json(keyboard)
  801. modules.extend(kb_info_json.get('modules', []))
  802. if keymap_filename:
  803. keymap_json = parse_configurator_json(keymap_filename)
  804. if keymap_json:
  805. modules.extend(keymap_json.get('modules', []))
  806. return list(dict.fromkeys(modules)) # remove dupes