community_modules.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import contextlib
  2. from argcomplete.completers import FilesCompleter
  3. from pathlib import Path
  4. from milc import cli
  5. import qmk.path
  6. from qmk.info import get_modules
  7. from qmk.keyboard import keyboard_completer, keyboard_folder
  8. from qmk.commands import dump_lines
  9. from qmk.constants import GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, GPL2_HEADER_SH_LIKE, GENERATED_HEADER_SH_LIKE
  10. from qmk.community_modules import module_api_list, load_module_jsons, find_module_path
  11. @contextlib.contextmanager
  12. def _render_api_guard(lines, api):
  13. if api.guard:
  14. lines.append(f'#if {api.guard}')
  15. yield
  16. if api.guard:
  17. lines.append(f'#endif // {api.guard}')
  18. def _render_api_header(api):
  19. lines = []
  20. if api.header:
  21. lines.append('')
  22. with _render_api_guard(lines, api):
  23. lines.append(f'#include <{api.header}>')
  24. return lines
  25. def _render_keycodes(module_jsons):
  26. lines = []
  27. lines.append('')
  28. lines.append('enum {')
  29. first = True
  30. for module_json in module_jsons:
  31. module_name = Path(module_json['module']).name
  32. keycodes = module_json.get('keycodes', [])
  33. if len(keycodes) > 0:
  34. lines.append(f' // From module: {module_name}')
  35. for keycode in keycodes:
  36. key = keycode.get('key', None)
  37. if first:
  38. lines.append(f' {key} = QK_COMMUNITY_MODULE,')
  39. first = False
  40. else:
  41. lines.append(f' {key},')
  42. for alias in keycode.get('aliases', []):
  43. lines.append(f' {alias} = {key},')
  44. lines.append('')
  45. lines.append(' LAST_COMMUNITY_MODULE_KEY')
  46. lines.append('};')
  47. lines.append('STATIC_ASSERT((int)LAST_COMMUNITY_MODULE_KEY <= (int)(QK_COMMUNITY_MODULE_MAX+1), "Too many community module keycodes");')
  48. return lines
  49. def _render_api_declarations(api, module, user_kb=True):
  50. lines = []
  51. lines.append('')
  52. with _render_api_guard(lines, api):
  53. if user_kb:
  54. lines.append(f'{api.ret_type} {api.name}_{module}_user({api.args});')
  55. lines.append(f'{api.ret_type} {api.name}_{module}_kb({api.args});')
  56. lines.append(f'{api.ret_type} {api.name}_{module}({api.args});')
  57. return lines
  58. def _render_api_implementations(api, module):
  59. module_name = Path(module).name
  60. lines = []
  61. lines.append('')
  62. with _render_api_guard(lines, api):
  63. # _user
  64. lines.append(f'__attribute__((weak)) {api.ret_type} {api.name}_{module_name}_user({api.args}) {{')
  65. if api.ret_type == 'bool':
  66. lines.append(' return true;')
  67. elif api.ret_type in ['layer_state_t', 'report_mouse_t']:
  68. lines.append(f' return {api.call_params};')
  69. else:
  70. pass
  71. lines.append('}')
  72. lines.append('')
  73. # _kb
  74. lines.append(f'__attribute__((weak)) {api.ret_type} {api.name}_{module_name}_kb({api.args}) {{')
  75. if api.ret_type == 'bool':
  76. lines.append(f' if(!{api.name}_{module_name}_user({api.call_params})) {{ return false; }}')
  77. lines.append(' return true;')
  78. elif api.ret_type in ['layer_state_t', 'report_mouse_t']:
  79. lines.append(f' return {api.name}_{module_name}_user({api.call_params});')
  80. else:
  81. lines.append(f' {api.name}_{module_name}_user({api.call_params});')
  82. lines.append('}')
  83. lines.append('')
  84. # module (non-suffixed)
  85. lines.append(f'__attribute__((weak)) {api.ret_type} {api.name}_{module_name}({api.args}) {{')
  86. if api.ret_type == 'bool':
  87. lines.append(f' if(!{api.name}_{module_name}_kb({api.call_params})) {{ return false; }}')
  88. lines.append(' return true;')
  89. elif api.ret_type in ['layer_state_t', 'report_mouse_t']:
  90. lines.append(f' return {api.name}_{module_name}_kb({api.call_params});')
  91. else:
  92. lines.append(f' {api.name}_{module_name}_kb({api.call_params});')
  93. lines.append('}')
  94. return lines
  95. def _render_core_implementation(api, modules):
  96. lines = []
  97. lines.append('')
  98. with _render_api_guard(lines, api):
  99. lines.append(f'{api.ret_type} {api.name}_modules({api.args}) {{')
  100. if api.ret_type == 'bool':
  101. lines.append(' return true')
  102. for module in modules:
  103. module_name = Path(module).name
  104. if api.ret_type == 'bool':
  105. lines.append(f' && {api.name}_{module_name}({api.call_params})')
  106. elif api.ret_type in ['layer_state_t', 'report_mouse_t']:
  107. lines.append(f' {api.call_params} = {api.name}_{module_name}({api.call_params});')
  108. else:
  109. lines.append(f' {api.name}_{module_name}({api.call_params});')
  110. if api.ret_type == 'bool':
  111. lines.append(' ;')
  112. elif api.ret_type in ['layer_state_t', 'report_mouse_t']:
  113. lines.append(f' return {api.call_params};')
  114. lines.append('}')
  115. return lines
  116. def _generate_features_rules(features_dict):
  117. lines = []
  118. for feature, enabled in features_dict.items():
  119. feature = feature.upper()
  120. enabled = 'yes' if enabled else 'no'
  121. lines.append(f'{feature}_ENABLE={enabled}')
  122. return lines
  123. def _generate_modules_rules(keyboard, filename):
  124. lines = []
  125. modules = get_modules(keyboard, filename)
  126. if len(modules) > 0:
  127. lines.append('')
  128. lines.append('OPT_DEFS += -DCOMMUNITY_MODULES_ENABLE=TRUE')
  129. for module in modules:
  130. module_path = qmk.path.unix_style_path(find_module_path(module))
  131. if not module_path:
  132. raise FileNotFoundError(f"Module '{module}' not found.")
  133. lines.append('')
  134. lines.append(f'COMMUNITY_MODULES += {module_path.name}') # use module_path here instead of module as it may be a subdirectory
  135. lines.append(f'OPT_DEFS += -DCOMMUNITY_MODULE_{module_path.name.upper()}_ENABLE=TRUE')
  136. lines.append(f'COMMUNITY_MODULE_PATHS += {module_path}')
  137. lines.append(f'VPATH += {module_path}')
  138. lines.append(f'SRC += $(wildcard {module_path}/{module_path.name}.c)')
  139. lines.append(f'MODULE_NAME_{module_path.name.upper()} := {module_path.name}')
  140. lines.append(f'MODULE_PATH_{module_path.name.upper()} := {module_path}')
  141. lines.append(f'-include {module_path}/rules.mk')
  142. module_jsons = load_module_jsons(modules)
  143. for module_json in module_jsons:
  144. if 'features' in module_json:
  145. lines.append('')
  146. lines.append(f'# Module: {module_json["module_name"]}')
  147. lines.extend(_generate_features_rules(module_json['features']))
  148. return lines
  149. def _module_slugs(modules):
  150. return [Path(m).name.lower() for m in modules]
  151. def _render_eeconfig_declarations(modules):
  152. lines = []
  153. lines.append('')
  154. lines.append('// nvm eeconfig')
  155. for module_slug in _module_slugs(modules):
  156. lines.extend([
  157. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  158. f'bool eeconfig_is_{module_slug}_datablock_valid(void);',
  159. f'uint32_t eeconfig_read_{module_slug}_datablock(void *data, uint32_t offset, uint32_t length) __attribute__((nonnull));',
  160. f'uint32_t eeconfig_update_{module_slug}_datablock(const void *data, uint32_t offset, uint32_t length) __attribute__((nonnull));',
  161. f'void eeconfig_init_{module_slug}_datablock(void);',
  162. f'# define eeconfig_read_{module_slug}_datablock_field(__object, __field) eeconfig_read_{module_slug}_datablock(&(__object.__field), offsetof(typeof(__object), __field), sizeof(__object.__field))',
  163. f'# define eeconfig_update_{module_slug}_datablock_field(__object, __field) eeconfig_update_{module_slug}_datablock(&(__object.__field), offsetof(typeof(__object), __field), sizeof(__object.__field))',
  164. '',
  165. f'bool nvm_eeconfig_is_{module_slug}_datablock_valid(void);',
  166. f'uint32_t nvm_eeconfig_read_{module_slug}_datablock(void *data, uint32_t offset, uint32_t length);',
  167. f'uint32_t nvm_eeconfig_update_{module_slug}_datablock(const void *data, uint32_t offset, uint32_t length);',
  168. f'void nvm_eeconfig_init_{module_slug}_datablock(void);',
  169. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  170. '',
  171. ])
  172. lines.append('typedef struct PACKED {')
  173. for module_slug in _module_slugs(modules):
  174. lines.extend([
  175. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  176. f' uint32_t {module_slug}_version;',
  177. f' uint8_t {module_slug}[EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE];',
  178. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  179. ])
  180. lines.append('} eeprom_modules_t;')
  181. lines.append('')
  182. for module_slug in _module_slugs(modules):
  183. lines.append(f'#define EECONFIG_MODULE_{module_slug.upper()}_VERSION (uint32_t *)(EECONFIG_MODULES_DATABLOCK + (offsetof(eeprom_modules_t, {module_slug}_version)))')
  184. lines.append(f'#define EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK (uint8_t *)(EECONFIG_MODULES_DATABLOCK + (offsetof(eeprom_modules_t, {module_slug})))')
  185. lines.append('')
  186. lines.append('bool eeconfig_is_modules_datablock_valid(void);')
  187. lines.append('void eeconfig_init_modules_datablock(void);')
  188. lines.append('void eeconfig_prepare_modules_datablocks(void);')
  189. lines.append('')
  190. return lines
  191. def _render_eeconfig_implementation(modules):
  192. lines = []
  193. lines.append('')
  194. lines.append('// nvm eeconfig')
  195. lines.append('#if defined(NVM_DRIVER_EEPROM)')
  196. lines.append('# include "nvm_eeprom_eeconfig_internal.h"')
  197. lines.append('# include "eeprom.h"')
  198. lines.append('#endif // defined(NVM_DRIVER_EEPROM)')
  199. lines.append('')
  200. for module_slug in _module_slugs(modules):
  201. lines.extend([
  202. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  203. f'bool eeconfig_is_{module_slug}_datablock_valid(void) {{ return nvm_eeconfig_is_{module_slug}_datablock_valid(); }}',
  204. f'uint32_t eeconfig_read_{module_slug}_datablock(void *data, uint32_t offset, uint32_t length) {{ return nvm_eeconfig_read_{module_slug}_datablock(data, offset, length); }}',
  205. f'uint32_t eeconfig_update_{module_slug}_datablock(const void *data, uint32_t offset, uint32_t length) {{ return nvm_eeconfig_update_{module_slug}_datablock(data, offset, length); }}',
  206. f'__attribute__((weak)) void eeconfig_init_{module_slug}_datablock(void) {{ nvm_eeconfig_init_{module_slug}_datablock(); }}',
  207. '',
  208. '# if defined(NVM_DRIVER_EEPROM)',
  209. f'bool nvm_eeconfig_is_{module_slug}_datablock_valid(void) {{',
  210. f' return eeprom_read_dword(EECONFIG_MODULE_{module_slug.upper()}_VERSION) == (EECONFIG_MODULE_{module_slug.upper()}_DATA_VERSION);',
  211. '}',
  212. f'uint32_t nvm_eeconfig_read_{module_slug}_datablock(void *data, uint32_t offset, uint32_t length) {{',
  213. f' if (eeconfig_is_{module_slug}_datablock_valid()) {{',
  214. f' void *ee_start = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK + offset);',
  215. f' void *ee_end = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK + MIN((EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE), offset + length));',
  216. ' eeprom_read_block(data, ee_start, ee_end - ee_start);',
  217. ' return ee_end - ee_start;',
  218. ' } else {',
  219. ' memset(data, 0, length);',
  220. ' return length;',
  221. ' }',
  222. '}',
  223. f'uint32_t nvm_eeconfig_update_{module_slug}_datablock(const void *data, uint32_t offset, uint32_t length) {{',
  224. f' eeprom_update_dword(EECONFIG_MODULE_{module_slug.upper()}_VERSION, (EECONFIG_MODULE_{module_slug.upper()}_DATA_VERSION));',
  225. f' void *ee_start = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK + offset);',
  226. f' void *ee_end = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK + MIN((EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE), offset + length));',
  227. ' eeprom_update_block(data, ee_start, ee_end - ee_start);',
  228. ' return ee_end - ee_start;',
  229. '}',
  230. f'void nvm_eeconfig_init_{module_slug}_datablock(void) {{',
  231. f' eeprom_update_dword(EECONFIG_MODULE_{module_slug.upper()}_VERSION, (EECONFIG_MODULE_{module_slug.upper()}_DATA_VERSION));',
  232. f' void *start = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK);',
  233. f' void *end = (void *)(uintptr_t)(EECONFIG_MODULE_{module_slug.upper()}_DATABLOCK + (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE));',
  234. ' long remaining = end - start;',
  235. ' uint8_t dummy[16] = {0};',
  236. f' for (int i = 0; i < EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE; i += sizeof(dummy)) {{',
  237. ' int this_loop = remaining < sizeof(dummy) ? remaining : sizeof(dummy);',
  238. ' eeprom_update_block(dummy, start, this_loop);',
  239. ' start += this_loop;',
  240. ' remaining -= this_loop;',
  241. ' }',
  242. '}',
  243. '# endif // defined(NVM_DRIVER_EEPROM)',
  244. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  245. '',
  246. ])
  247. lines.append('bool eeconfig_is_modules_datablock_valid(void) {')
  248. lines.append(' return true')
  249. for module_slug in _module_slugs(modules):
  250. lines.extend([
  251. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  252. f' && eeconfig_is_{module_slug}_datablock_valid()',
  253. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  254. ])
  255. lines.append(' ;')
  256. lines.append('}')
  257. lines.append('')
  258. lines.append('void eeconfig_init_modules_datablock(void) {')
  259. for module_slug in _module_slugs(modules):
  260. lines.extend([
  261. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  262. f' eeconfig_init_{module_slug}_datablock();',
  263. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  264. ])
  265. lines.append('}')
  266. lines.append('')
  267. lines.append('void eeconfig_prepare_modules_datablocks(void) {')
  268. for module_slug in _module_slugs(modules):
  269. lines.extend([
  270. f'#if (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  271. f' if (!eeconfig_is_{module_slug}_datablock_valid()) {{ eeconfig_init_{module_slug}_datablock(); }}',
  272. f'#endif // (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE) > 0',
  273. ])
  274. lines.append('}')
  275. lines.append('')
  276. return lines
  277. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  278. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  279. @cli.argument('-e', '--escape', arg_only=True, action='store_true', help="Escape spaces in quiet mode")
  280. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate rules.mk for.')
  281. @cli.argument('filename', nargs='?', arg_only=True, type=qmk.path.FileType('r'), completer=FilesCompleter('.json'), help='A configurator export JSON to be compiled and flashed or a pre-compiled binary firmware file (bin/hex) to be flashed.')
  282. @cli.subcommand('Creates a community_modules_rules_mk from a keymap.json file.')
  283. def generate_community_modules_rules_mk(cli):
  284. rules_mk_lines = [GPL2_HEADER_SH_LIKE, GENERATED_HEADER_SH_LIKE]
  285. rules_mk_lines.extend(_generate_modules_rules(cli.args.keyboard, cli.args.filename))
  286. # Show the results
  287. dump_lines(cli.args.output, rules_mk_lines)
  288. if cli.args.output:
  289. if cli.args.quiet:
  290. if cli.args.escape:
  291. print(cli.args.output.as_posix().replace(' ', '\\ '))
  292. else:
  293. print(cli.args.output)
  294. else:
  295. cli.log.info('Wrote rules.mk to %s.', cli.args.output)
  296. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  297. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  298. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate community_post_config.h for.')
  299. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  300. @cli.subcommand('Creates a community_post_config.h from a keymap.json file.')
  301. def generate_community_post_config_h(cli):
  302. """Creates a community_post_config.h from a keymap.json file
  303. """
  304. if cli.args.output and cli.args.output.name == '-':
  305. cli.args.output = None
  306. lines = [
  307. GPL2_HEADER_C_LIKE,
  308. GENERATED_HEADER_C_LIKE,
  309. '#pragma once',
  310. '',
  311. ]
  312. modules = get_modules(cli.args.keyboard, cli.args.filename)
  313. if len(modules) > 0:
  314. lines.append('// Split transactions')
  315. for module_slug in _module_slugs(modules):
  316. lines.extend([
  317. f'#ifdef SPLIT_TRANSACTION_IDS_MODULE_{module_slug.upper()}',
  318. '# define SPLIT_TRANSACTION_RPC',
  319. '#endif',
  320. ])
  321. lines.append('')
  322. lines.append('// nvm eeconfig')
  323. for module_slug in _module_slugs(modules):
  324. lines.extend([
  325. f'#ifndef EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE',
  326. f'# define EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE 0',
  327. '#endif',
  328. f'#ifndef EECONFIG_MODULE_{module_slug.upper()}_DATA_VERSION',
  329. f'# define EECONFIG_MODULE_{module_slug.upper()}_DATA_VERSION (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE)',
  330. '#endif',
  331. '',
  332. ])
  333. module_size = " + ".join([f'(4 + (EECONFIG_MODULE_{module_slug.upper()}_DATA_SIZE))' for module_slug in _module_slugs(modules)])
  334. lines.append(f'#define EECONFIG_MODULE_DATA_SIZE ({module_size})')
  335. lines.append('')
  336. dump_lines(cli.args.output, lines, cli.args.quiet, remove_repeated_newlines=True)
  337. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  338. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  339. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate community_modules.h for.')
  340. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  341. @cli.subcommand('Creates a community_modules.h from a keymap.json file.')
  342. def generate_community_modules_h(cli):
  343. """Creates a community_modules.h from a keymap.json file
  344. """
  345. if cli.args.output and cli.args.output.name == '-':
  346. cli.args.output = None
  347. api_list, api_version, ver_major, ver_minor, ver_patch = module_api_list()
  348. lines = [
  349. GPL2_HEADER_C_LIKE,
  350. GENERATED_HEADER_C_LIKE,
  351. '#pragma once',
  352. '#include <stdint.h>',
  353. '#include <stdbool.h>',
  354. '#include <string.h>',
  355. '#include <keycodes.h>',
  356. '',
  357. '#include "compiler_support.h"',
  358. '',
  359. '#define COMMUNITY_MODULES_API_VERSION_BUILDER(ver_major,ver_minor,ver_patch) (((((uint32_t)(ver_major))&0xFF) << 24) | ((((uint32_t)(ver_minor))&0xFF) << 16) | (((uint32_t)(ver_patch))&0xFF))',
  360. f'#define COMMUNITY_MODULES_API_VERSION COMMUNITY_MODULES_API_VERSION_BUILDER({ver_major},{ver_minor},{ver_patch})',
  361. f'#define ASSERT_COMMUNITY_MODULES_MIN_API_VERSION(ver_major,ver_minor,ver_patch) STATIC_ASSERT(COMMUNITY_MODULES_API_VERSION_BUILDER(ver_major,ver_minor,ver_patch) <= COMMUNITY_MODULES_API_VERSION, "Community module requires a newer version of QMK modules API -- needs: " #ver_major "." #ver_minor "." #ver_patch ", current: {api_version}.")',
  362. '',
  363. 'typedef struct keyrecord_t keyrecord_t; // forward declaration so we don\'t need to include quantum.h',
  364. '',
  365. ]
  366. modules = get_modules(cli.args.keyboard, cli.args.filename)
  367. module_jsons = load_module_jsons(modules)
  368. if len(modules) > 0:
  369. lines.extend(_render_keycodes(module_jsons))
  370. for api in api_list:
  371. lines.extend(_render_api_header(api))
  372. for module in modules:
  373. lines.append('')
  374. lines.append(f'// From module: {module}')
  375. for api in api_list:
  376. lines.extend(_render_api_declarations(api, Path(module).name))
  377. lines.append('')
  378. lines.extend(_render_eeconfig_declarations(modules))
  379. lines.append('// Core wrapper')
  380. for api in api_list:
  381. lines.extend(_render_api_declarations(api, 'modules', user_kb=False))
  382. dump_lines(cli.args.output, lines, cli.args.quiet, remove_repeated_newlines=True)
  383. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  384. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  385. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate community_modules.c for.')
  386. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  387. @cli.subcommand('Creates a community_modules.c from a keymap.json file.')
  388. def generate_community_modules_c(cli):
  389. """Creates a community_modules.c from a keymap.json file
  390. """
  391. if cli.args.output and cli.args.output.name == '-':
  392. cli.args.output = None
  393. api_list, _, _, _, _ = module_api_list()
  394. lines = [
  395. GPL2_HEADER_C_LIKE,
  396. GENERATED_HEADER_C_LIKE,
  397. '',
  398. '#include "community_modules.h"',
  399. ]
  400. modules = get_modules(cli.args.keyboard, cli.args.filename)
  401. if len(modules) > 0:
  402. for module in modules:
  403. for api in api_list:
  404. lines.extend(_render_api_implementations(api, Path(module).name))
  405. for api in api_list:
  406. lines.extend(_render_core_implementation(api, modules))
  407. lines.extend(_render_eeconfig_implementation(modules))
  408. dump_lines(cli.args.output, lines, cli.args.quiet, remove_repeated_newlines=True)
  409. def _generate_include_per_module(cli, include_file_name):
  410. """Generates C code to include "<module_path>/include_file_name" for each module."""
  411. if cli.args.output and cli.args.output.name == '-':
  412. cli.args.output = None
  413. lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE]
  414. for module in get_modules(cli.args.keyboard, cli.args.filename):
  415. full_path = f'{find_module_path(module)}/{include_file_name}'
  416. lines.append('')
  417. lines.append(f'#if __has_include("{full_path}")')
  418. lines.append(f'#include "{full_path}"')
  419. lines.append(f'#endif // __has_include("{full_path}")')
  420. dump_lines(cli.args.output, lines, cli.args.quiet, remove_repeated_newlines=True)
  421. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  422. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  423. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate community_modules_introspection.h for.')
  424. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  425. @cli.subcommand('Creates a community_modules_introspection.h from a keymap.json file.')
  426. def generate_community_modules_introspection_h(cli):
  427. """Creates a community_modules_introspection.h from a keymap.json file
  428. """
  429. _generate_include_per_module(cli, 'introspection.h')
  430. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  431. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  432. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate community_modules.c for.')
  433. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  434. @cli.subcommand('Creates a community_modules_introspection.c from a keymap.json file.')
  435. def generate_community_modules_introspection_c(cli):
  436. """Creates a community_modules_introspection.c from a keymap.json file
  437. """
  438. _generate_include_per_module(cli, 'introspection.c')
  439. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  440. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  441. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate led_matrix_community_modules.inc for.')
  442. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  443. @cli.subcommand('Creates an led_matrix_community_modules.inc from a keymap.json file.')
  444. def generate_led_matrix_community_modules_inc(cli):
  445. """Creates an led_matrix_community_modules.inc from a keymap.json file
  446. """
  447. _generate_include_per_module(cli, 'led_matrix_module.inc')
  448. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  449. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  450. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate rgb_matrix_community_modules.inc for.')
  451. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  452. @cli.subcommand('Creates an rgb_matrix_community_modules.inc from a keymap.json file.')
  453. def generate_rgb_matrix_community_modules_inc(cli):
  454. """Creates an rgb_matrix_community_modules.inc from a keymap.json file
  455. """
  456. _generate_include_per_module(cli, 'rgb_matrix_module.inc')
  457. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  458. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  459. @cli.argument('-kb', '--keyboard', required=True, arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate split_transaction_id_community_modules.inc for.')
  460. @cli.argument('filename', nargs='?', type=qmk.path.FileType('r'), arg_only=True, completer=FilesCompleter('.json'), help='Configurator JSON file')
  461. @cli.subcommand('Creates an split_transaction_id_community_modules.inc from a keymap.json file.')
  462. def generate_split_transaction_id_community_modules_inc(cli):
  463. """Creates an split_transaction_id_community_modules.inc from a keymap.json file
  464. """
  465. if cli.args.output and cli.args.output.name == '-':
  466. cli.args.output = None
  467. lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE]
  468. for module in get_modules(cli.args.keyboard, cli.args.filename):
  469. lines.extend([
  470. f'#ifdef SPLIT_TRANSACTION_IDS_MODULE_{Path(module).name.upper()}',
  471. f' SPLIT_TRANSACTION_IDS_MODULE_{Path(module).name.upper()},',
  472. '#endif',
  473. ])
  474. dump_lines(cli.args.output, lines, cli.args.quiet, remove_repeated_newlines=True)