info.py 39 KB

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