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.

536 lines
15KB

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