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.

532 lines
14KB

  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['brand'] = input_default("Brand (prefix for all module names)", manifest.get('brand', manifest['name']))
  121. manifest['author'] = input_default("Author", manifest.get('author', ""))
  122. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  123. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  124. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  125. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  126. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  127. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  128. if 'modules' not in manifest:
  129. manifest['modules'] = []
  130. # Dump JSON
  131. with open(manifest_filename, "w") as f:
  132. json.dump(manifest, f, indent=" ")
  133. print(f"Manifest written to {manifest_filename}")
  134. def create_module(slug, panel_filename=None, source_filename=None):
  135. # Check slug
  136. if not is_valid_slug(slug):
  137. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  138. # Read manifest
  139. manifest_filename = 'plugin.json'
  140. with open(manifest_filename, "r") as f:
  141. manifest = json.load(f)
  142. # Check if module manifest exists
  143. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  144. if module_manifest:
  145. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  146. else:
  147. # Add module to manifest
  148. module_manifest = {}
  149. module_manifest['slug'] = slug
  150. module_manifest['name'] = input_default("Module name", slug)
  151. module_manifest['description'] = input_default("One-line description (optional)")
  152. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/plugin.cpp#L511-L571 for list)")
  153. tags = tags.split(",")
  154. tags = [tag.strip() for tag in tags]
  155. if len(tags) == 1 and tags[0] == "":
  156. tags = []
  157. module_manifest['tags'] = tags
  158. manifest['modules'].append(module_manifest)
  159. # Write manifest
  160. with open(manifest_filename, "w") as f:
  161. json.dump(manifest, f, indent=" ")
  162. print(f"Added {slug} to {manifest_filename}")
  163. # Check filenames
  164. if panel_filename and source_filename:
  165. if not os.path.exists(panel_filename):
  166. raise UserException(f"Panel not found at {panel_filename}.")
  167. print(f"Panel found at {panel_filename}. Generating source file.")
  168. if os.path.exists(source_filename):
  169. if input_default(f"{source_filename} already exists. Overwrite?", "n").lower() != "y":
  170. return
  171. # Read SVG XML
  172. tree = xml.etree.ElementTree.parse(panel_filename)
  173. components = panel_to_components(tree)
  174. print(f"Components extracted from {panel_filename}")
  175. # Write source
  176. source = components_to_source(components, slug)
  177. with open(source_filename, "w") as f:
  178. f.write(source)
  179. print(f"Source file generated at {source_filename}")
  180. # Append model to plugin.hpp
  181. identifier = slug_to_identifier(slug)
  182. # Tell user to add model to plugin.hpp and plugin.cpp
  183. print(f"""
  184. To enable the module, add
  185. extern Model *model{identifier};
  186. to plugin.hpp, and add
  187. p->addModel(model{identifier});
  188. to the init() function in plugin.cpp.""")
  189. def panel_to_components(tree):
  190. ns = {
  191. "svg": "http://www.w3.org/2000/svg",
  192. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  193. }
  194. # Get components layer
  195. root = tree.getroot()
  196. groups = root.findall(".//svg:g[@inkscape:label='components']", ns)
  197. if len(groups) < 1:
  198. raise UserException("Could not find \"components\" layer on panel")
  199. # Get circles and rects
  200. components_group = groups[0]
  201. circles = components_group.findall(".//svg:circle", ns)
  202. rects = components_group.findall(".//svg:rect", ns)
  203. components = {}
  204. components['params'] = []
  205. components['inputs'] = []
  206. components['outputs'] = []
  207. components['lights'] = []
  208. components['widgets'] = []
  209. for el in circles + rects:
  210. c = {}
  211. # Get name
  212. name = el.get('{http://www.inkscape.org/namespaces/inkscape}label')
  213. if name is None:
  214. name = el.get('id')
  215. name = slug_to_identifier(name).upper()
  216. c['name'] = name
  217. # Get color
  218. style = el.get('style')
  219. color_match = re.search(r'fill:\S*#(.{6});', style)
  220. color = color_match.group(1)
  221. c['color'] = color
  222. # Get position
  223. if el.tag == "{http://www.w3.org/2000/svg}rect":
  224. x = float(el.get('x'))
  225. y = float(el.get('y'))
  226. width = float(el.get('width'))
  227. height = float(el.get('height'))
  228. c['x'] = round(x, 3)
  229. c['y'] = round(y, 3)
  230. c['width'] = round(width, 3)
  231. c['height'] = round(height, 3)
  232. c['cx'] = round(x + width / 2, 3)
  233. c['cy'] = round(y + height / 2, 3)
  234. elif el.tag == "{http://www.w3.org/2000/svg}circle":
  235. cx = float(el.get('cx'))
  236. cy = float(el.get('cy'))
  237. c['cx'] = round(cx, 3)
  238. c['cy'] = round(cy, 3)
  239. if color == 'ff0000':
  240. components['params'].append(c)
  241. if color == '00ff00':
  242. components['inputs'].append(c)
  243. if color == '0000ff':
  244. components['outputs'].append(c)
  245. if color == 'ff00ff':
  246. components['lights'].append(c)
  247. if color == 'ffff00':
  248. components['widgets'].append(c)
  249. # Sort components
  250. top_left_sort = lambda w: (w['cy'], w['cx'])
  251. components['params'] = sorted(components['params'], key=top_left_sort)
  252. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  253. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  254. components['lights'] = sorted(components['lights'], key=top_left_sort)
  255. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  256. 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.")
  257. return components
  258. def components_to_source(components, slug):
  259. identifier = slug_to_identifier(slug)
  260. source = ""
  261. source += f"""#include "plugin.hpp"
  262. struct {identifier} : Module {{"""
  263. # Params
  264. source += """
  265. enum ParamIds {"""
  266. for c in components['params']:
  267. source += f"""
  268. {c['name']}_PARAM,"""
  269. source += """
  270. NUM_PARAMS
  271. };"""
  272. # Inputs
  273. source += """
  274. enum InputIds {"""
  275. for c in components['inputs']:
  276. source += f"""
  277. {c['name']}_INPUT,"""
  278. source += """
  279. NUM_INPUTS
  280. };"""
  281. # Outputs
  282. source += """
  283. enum OutputIds {"""
  284. for c in components['outputs']:
  285. source += f"""
  286. {c['name']}_OUTPUT,"""
  287. source += """
  288. NUM_OUTPUTS
  289. };"""
  290. # Lights
  291. source += """
  292. enum LightIds {"""
  293. for c in components['lights']:
  294. source += f"""
  295. {c['name']}_LIGHT,"""
  296. source += """
  297. NUM_LIGHTS
  298. };"""
  299. source += f"""
  300. {identifier}() {{
  301. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  302. for c in components['params']:
  303. source += f"""
  304. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  305. source += """
  306. }
  307. void process(const ProcessArgs &args) override {
  308. }
  309. };"""
  310. source += f"""
  311. struct {identifier}Widget : ModuleWidget {{
  312. {identifier}Widget({identifier} *module) {{
  313. setModule(module);
  314. setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/{slug}.svg")));
  315. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  316. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  317. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  318. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  319. # Params
  320. if len(components['params']) > 0:
  321. source += "\n"
  322. for c in components['params']:
  323. if 'x' in c:
  324. source += f"""
  325. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  326. else:
  327. source += f"""
  328. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  329. # Inputs
  330. if len(components['inputs']) > 0:
  331. source += "\n"
  332. for c in components['inputs']:
  333. if 'x' in c:
  334. source += f"""
  335. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  336. else:
  337. source += f"""
  338. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  339. # Outputs
  340. if len(components['outputs']) > 0:
  341. source += "\n"
  342. for c in components['outputs']:
  343. if 'x' in c:
  344. source += f"""
  345. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  346. else:
  347. source += f"""
  348. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  349. # Lights
  350. if len(components['lights']) > 0:
  351. source += "\n"
  352. for c in components['lights']:
  353. if 'x' in c:
  354. source += f"""
  355. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  356. else:
  357. source += f"""
  358. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  359. # Widgets
  360. if len(components['widgets']) > 0:
  361. source += "\n"
  362. for c in components['widgets']:
  363. if 'x' in c:
  364. source += f"""
  365. // mm2px(Vec({c['width']}, {c['height']}))
  366. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  367. else:
  368. source += f"""
  369. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  370. source += f"""
  371. }}
  372. }};
  373. Model *model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  374. return source
  375. def usage(script):
  376. text = f"""VCV Rack Plugin Helper Utility
  377. Usage: {script} <command> ...
  378. Commands:
  379. createplugin <slug> [plugin dir]
  380. A directory will be created and initialized with a minimal plugin template.
  381. If no plugin directory is given, the slug is used.
  382. createmanifest <slug> [plugin dir]
  383. Creates a `plugin.json` manifest file in an existing plugin directory.
  384. If no plugin directory is given, the current directory is used.
  385. createmodule <module slug> [panel file] [source file]
  386. Adds a new module to the plugin manifest in the current directory.
  387. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  388. Example:
  389. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  390. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  391. """
  392. print(text)
  393. def parse_args(args):
  394. script = args.pop(0)
  395. if len(args) == 0:
  396. usage(script)
  397. return
  398. cmd = args.pop(0)
  399. if cmd == 'createplugin':
  400. create_plugin(*args)
  401. elif cmd == 'createmodule':
  402. create_module(*args)
  403. elif cmd == 'createmanifest':
  404. create_manifest(*args)
  405. else:
  406. print(f"Command not found: {cmd}")
  407. if __name__ == "__main__":
  408. try:
  409. parse_args(sys.argv)
  410. except KeyboardInterrupt:
  411. pass
  412. except UserException as e:
  413. print(e)
  414. sys.exit(1)