info.py 44 KB

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