You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helper.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import re
  5. import json
  6. import xml.etree.ElementTree
  7. # Version check
  8. f"Python 3.6+ is required"
  9. class UserException(Exception):
  10. pass
  11. def find(f, array):
  12. for a in array:
  13. if f(a):
  14. return f
  15. def input_default(prompt, default=""):
  16. str = input(f"{prompt} [{default}]: ")
  17. if str == "":
  18. return default
  19. return str
  20. def is_valid_slug(slug):
  21. return re.match(r'^[a-zA-Z0-9_\-]+$', slug) != None
  22. def slug_to_identifier(slug):
  23. if len(slug) == 0 or slug[0].isdigit():
  24. slug = "_" + slug
  25. slug = slug[0].upper() + slug[1:]
  26. slug = slug.replace('-', '_')
  27. return slug
  28. def create_plugin(slug, plugin_dir=None):
  29. # Check slug
  30. if not is_valid_slug(slug):
  31. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  32. if not plugin_dir:
  33. plugin_dir = os.path.join(slug, '')
  34. # Check if plugin directory exists
  35. if os.path.exists(plugin_dir):
  36. raise UserException(f"Directory {plugin_dir} already exists")
  37. # Create plugin directory
  38. os.mkdir(plugin_dir)
  39. # Create manifest
  40. try:
  41. create_manifest(slug, plugin_dir)
  42. except Exception as e:
  43. os.rmdir(plugin_dir)
  44. raise e
  45. # Create subdirectories
  46. os.mkdir(os.path.join(plugin_dir, "src"))
  47. os.mkdir(os.path.join(plugin_dir, "res"))
  48. # Create Makefile
  49. makefile = """# If RACK_DIR is not defined when calling the Makefile, default to two directories above
  50. RACK_DIR ?= ../..
  51. # FLAGS will be passed to both the C and C++ compiler
  52. FLAGS +=
  53. CFLAGS +=
  54. CXXFLAGS +=
  55. # Careful about linking to shared libraries, since you can't assume much about the user's environment and library search path.
  56. # Static libraries are fine, but they should be added to this plugin's build system.
  57. LDFLAGS +=
  58. # Add .cpp files to the build
  59. SOURCES += $(wildcard src/*.cpp)
  60. # Add files to the ZIP package when running `make dist`
  61. # The compiled plugin and "plugin.json" are automatically added.
  62. DISTRIBUTABLES += res
  63. DISTRIBUTABLES += $(wildcard LICENSE*)
  64. # Include the Rack plugin Makefile framework
  65. include $(RACK_DIR)/plugin.mk
  66. """
  67. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  68. f.write(makefile)
  69. # Create plugin.hpp
  70. plugin_hpp = """#include "rack.hpp"
  71. using namespace rack;
  72. // Declare the Plugin, defined in plugin.cpp
  73. extern Plugin *pluginInstance;
  74. // Declare each Model, defined in each module source file
  75. // extern Model *modelMyModule;
  76. """
  77. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  78. f.write(plugin_hpp)
  79. # Create plugin.cpp
  80. plugin_cpp = """#include "plugin.hpp"
  81. Plugin *pluginInstance;
  82. void init(Plugin *p) {
  83. pluginInstance = p;
  84. // Add modules here
  85. // p->addModel(modelMyModule);
  86. // Any other plugin initialization may go here.
  87. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  88. }
  89. """
  90. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  91. f.write(plugin_cpp)
  92. git_ignore = """/build
  93. /dist
  94. /plugin.so
  95. /plugin.dylib
  96. /plugin.dll
  97. .DS_Store
  98. """
  99. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  100. f.write(git_ignore)
  101. print(f"Created template plugin in {plugin_dir}")
  102. os.system(f"cd {plugin_dir} && git init")
  103. print(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  104. def create_manifest(slug, plugin_dir="."):
  105. # Default manifest
  106. manifest = {
  107. 'slug': slug,
  108. }
  109. # Try to load existing manifest file
  110. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  111. try:
  112. with open(manifest_filename, "r") as f:
  113. manifest = json.load(f)
  114. except:
  115. pass
  116. # Query manifest information
  117. manifest['name'] = input_default("Plugin name", manifest.get('name', slug))
  118. manifest['version'] = input_default("Version", manifest.get('version', "1.0.0"))
  119. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", manifest.get('license', "proprietary"))
  120. manifest['author'] = input_default("Author", manifest.get('author', ""))
  121. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  122. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  123. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  124. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  125. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  126. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  127. if 'modules' not in manifest:
  128. manifest['modules'] = []
  129. # Dump JSON
  130. with open(manifest_filename, "w") as f:
  131. json.dump(manifest, f, indent=" ")
  132. print(f"Manifest written to {manifest_filename}")
  133. def create_module(slug, panel_filename=None, source_filename=None):
  134. # Check slug
  135. if not is_valid_slug(slug):
  136. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  137. # Read manifest
  138. manifest_filename = 'plugin.json'
  139. with open(manifest_filename, "r") as f:
  140. manifest = json.load(f)
  141. # Check if module manifest exists
  142. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  143. if module_manifest:
  144. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  145. else:
  146. # Add module to manifest
  147. module_manifest = {}
  148. module_manifest['slug'] = slug
  149. module_manifest['name'] = input_default("Module name", slug)
  150. module_manifest['description'] = input_default("One-line description (optional)")
  151. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/plugin.cpp#L511-L571 for list)")
  152. tags = tags.split(",")
  153. tags = [tag.strip() for tag in tags]
  154. if len(tags) == 1 and tags[0] == "":
  155. tags = []
  156. module_manifest['tags'] = tags
  157. manifest['modules'].append(module_manifest)
  158. # Write manifest
  159. with open(manifest_filename, "w") as f:
  160. json.dump(manifest, f, indent=" ")
  161. print(f"Added {slug} to {manifest_filename}")
  162. # Check filenames
  163. if panel_filename and source_filename:
  164. if not os.path.exists(panel_filename):
  165. raise UserException(f"Panel not found at {panel_filename}.")
  166. print(f"Panel found at {panel_filename}. Generating source file.")
  167. if os.path.exists(source_filename):
  168. if input_default(f"{source_filename} already exists. Overwrite?", "n").lower() != "y":
  169. return
  170. # Read SVG XML
  171. tree = xml.etree.ElementTree.parse(panel_filename)
  172. components = panel_to_components(tree)
  173. print(f"Components extracted from {panel_filename}")
  174. # Write source
  175. source = components_to_source(components, slug)
  176. with open(source_filename, "w") as f:
  177. f.write(source)
  178. print(f"Source file generated at {source_filename}")
  179. # Append model to plugin.hpp
  180. identifier = slug_to_identifier(slug)
  181. # Tell user to add model to plugin.hpp and plugin.cpp
  182. print(f"""
  183. To enable the module, add
  184. extern Model *model{identifier};
  185. to plugin.hpp, and add
  186. p->addModel(model{identifier});
  187. to the init() function in plugin.cpp.""")
  188. def panel_to_components(tree):
  189. ns = {
  190. "svg": "http://www.w3.org/2000/svg",
  191. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  192. }
  193. # Get components layer
  194. root = tree.getroot()
  195. groups = root.findall(".//svg:g[@inkscape:label='components']", ns)
  196. if len(groups) < 1:
  197. raise UserException("Could not find \"components\" layer on panel")
  198. # Get circles and rects
  199. components_group = groups[0]
  200. circles = components_group.findall(".//svg:circle", ns)
  201. rects = components_group.findall(".//svg:rect", ns)
  202. components = {}
  203. components['params'] = []
  204. components['inputs'] = []
  205. components['outputs'] = []
  206. components['lights'] = []
  207. components['widgets'] = []
  208. for el in circles + rects:
  209. c = {}
  210. # Get name
  211. name = el.get('inkscape:label')
  212. if name is None:
  213. name = el.get('id')
  214. name = slug_to_identifier(name).upper()
  215. c['name'] = name
  216. # Get color
  217. style = el.get('style')
  218. color_match = re.search(r'fill:\S*#(.{6});', style)
  219. color = color_match.group(1)
  220. c['color'] = color
  221. # Get position
  222. if el.tag == "{http://www.w3.org/2000/svg}rect":
  223. x = float(el.get('x'))
  224. y = float(el.get('y'))
  225. width = float(el.get('width'))
  226. height = float(el.get('height'))
  227. c['x'] = round(x, 3)
  228. c['y'] = round(y, 3)
  229. c['width'] = round(width, 3)
  230. c['height'] = round(height, 3)
  231. c['cx'] = round(x + width / 2, 3)
  232. c['cy'] = round(y + height / 2, 3)
  233. elif el.tag == "{http://www.w3.org/2000/svg}circle":
  234. cx = float(el.get('cx'))
  235. cy = float(el.get('cy'))
  236. c['cx'] = round(cx, 3)
  237. c['cy'] = round(cy, 3)
  238. if color == 'ff0000':
  239. components['params'].append(c)
  240. if color == '00ff00':
  241. components['inputs'].append(c)
  242. if color == '0000ff':
  243. components['outputs'].append(c)
  244. if color == 'ff00ff':
  245. components['lights'].append(c)
  246. if color == 'ffff00':
  247. components['widgets'].append(c)
  248. # Sort components
  249. top_left_sort = lambda w: (w['cy'], w['cx'])
  250. components['params'] = sorted(components['params'], key=top_left_sort)
  251. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  252. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  253. components['lights'] = sorted(components['lights'], key=top_left_sort)
  254. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  255. print(f"Found {len(components['params'])} params, {len(components['inputs'])} inputs, {len(components['outputs'])} outputs, {len(components['lights'])} lights, and {len(components['widgets'])} custom widgets.")
  256. return components
  257. def components_to_source(components, slug):
  258. identifier = slug_to_identifier(slug)
  259. source = ""
  260. source += f"""#include "plugin.hpp"
  261. struct {identifier} : Module {{"""
  262. # Params
  263. source += """
  264. enum ParamIds {"""
  265. for c in components['params']:
  266. source += f"""
  267. {c['name']}_PARAM,"""
  268. source += """
  269. NUM_PARAMS
  270. };"""
  271. # Inputs
  272. source += """
  273. enum InputIds {"""
  274. for c in components['inputs']:
  275. source += f"""
  276. {c['name']}_INPUT,"""
  277. source += """
  278. NUM_INPUTS
  279. };"""
  280. # Outputs
  281. source += """
  282. enum OutputIds {"""
  283. for c in components['outputs']:
  284. source += f"""
  285. {c['name']}_OUTPUT,"""
  286. source += """
  287. NUM_OUTPUTS
  288. };"""
  289. # Lights
  290. source += """
  291. enum LightIds {"""
  292. for c in components['lights']:
  293. source += f"""
  294. {c['name']}_LIGHT,"""
  295. source += """
  296. NUM_LIGHTS
  297. };"""
  298. source += f"""
  299. {identifier}() {{
  300. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  301. for c in components['params']:
  302. source += f"""
  303. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  304. source += """
  305. }
  306. void process(const ProcessArgs &args) override {
  307. }
  308. };"""
  309. source += f"""
  310. struct {identifier}Widget : ModuleWidget {{
  311. {identifier}Widget({identifier} *module) {{
  312. setModule(module);
  313. setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/{slug}.svg")));
  314. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  315. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  316. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  317. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  318. # Params
  319. if len(components['params']) > 0:
  320. source += "\n"
  321. for c in components['params']:
  322. if 'x' in c:
  323. source += f"""
  324. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  325. else:
  326. source += f"""
  327. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  328. # Inputs
  329. if len(components['inputs']) > 0:
  330. source += "\n"
  331. for c in components['inputs']:
  332. if 'x' in c:
  333. source += f"""
  334. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  335. else:
  336. source += f"""
  337. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  338. # Outputs
  339. if len(components['outputs']) > 0:
  340. source += "\n"
  341. for c in components['outputs']:
  342. if 'x' in c:
  343. source += f"""
  344. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  345. else:
  346. source += f"""
  347. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  348. # Lights
  349. if len(components['lights']) > 0:
  350. source += "\n"
  351. for c in components['lights']:
  352. if 'x' in c:
  353. source += f"""
  354. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  355. else:
  356. source += f"""
  357. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  358. # Widgets
  359. if len(components['widgets']) > 0:
  360. source += "\n"
  361. for c in components['widgets']:
  362. if 'x' in c:
  363. source += f"""
  364. // mm2px(Vec({c['width']}, {c['height']}))
  365. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  366. else:
  367. source += f"""
  368. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  369. source += f"""
  370. }}
  371. }};
  372. Model *model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  373. return source
  374. def usage(script):
  375. text = f"""VCV Rack Plugin Helper Utility
  376. Usage: {script} <command> ...
  377. Commands:
  378. createplugin <slug> [plugin dir]
  379. A directory will be created and initialized with a minimal plugin template.
  380. If no plugin directory is given, the slug is used.
  381. createmanifest <slug> [plugin dir]
  382. Creates a `plugin.json` manifest file in an existing plugin directory.
  383. If no plugin directory is given, the current directory is used.
  384. createmodule <module slug> [panel file] [source file]
  385. Adds a new module to the plugin manifest in the current directory.
  386. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  387. Example:
  388. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  389. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  390. """
  391. print(text)
  392. def parse_args(args):
  393. script = args.pop(0)
  394. if len(args) == 0:
  395. usage(script)
  396. return
  397. cmd = args.pop(0)
  398. if cmd == 'createplugin':
  399. create_plugin(*args)
  400. elif cmd == 'createmodule':
  401. create_module(*args)
  402. elif cmd == 'createmanifest':
  403. create_manifest(*args)
  404. else:
  405. print(f"Command not found: {cmd}")
  406. if __name__ == "__main__":
  407. try:
  408. parse_args(sys.argv)
  409. except KeyboardInterrupt:
  410. pass
  411. except UserException as e:
  412. print(e)
  413. sys.exit(1)