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.

535 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 = """#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. # Illustrator uses `id` for the group name.
  198. if len(groups) < 1:
  199. groups = root.findall(".//svg:g[@id='components']", ns)
  200. if len(groups) < 1:
  201. raise UserException("Could not find \"components\" layer on panel")
  202. # Get circles and rects
  203. components_group = groups[0]
  204. circles = components_group.findall(".//svg:circle", ns)
  205. rects = components_group.findall(".//svg:rect", ns)
  206. components = {}
  207. components['params'] = []
  208. components['inputs'] = []
  209. components['outputs'] = []
  210. components['lights'] = []
  211. components['widgets'] = []
  212. for el in circles + rects:
  213. c = {}
  214. # Get name
  215. name = el.get('{http://www.inkscape.org/namespaces/inkscape}label')
  216. if name is None:
  217. name = el.get('id')
  218. name = slug_to_identifier(name).upper()
  219. c['name'] = name
  220. # Get color
  221. style = el.get('style')
  222. color_match = re.search(r'fill:\S*#(.{6});', style)
  223. color = color_match.group(1).lower()
  224. c['color'] = color
  225. # Get position
  226. if el.tag == "{http://www.w3.org/2000/svg}rect":
  227. x = float(el.get('x'))
  228. y = float(el.get('y'))
  229. width = float(el.get('width'))
  230. height = float(el.get('height'))
  231. c['x'] = round(x, 3)
  232. c['y'] = round(y, 3)
  233. c['width'] = round(width, 3)
  234. c['height'] = round(height, 3)
  235. c['cx'] = round(x + width / 2, 3)
  236. c['cy'] = round(y + height / 2, 3)
  237. elif el.tag == "{http://www.w3.org/2000/svg}circle":
  238. cx = float(el.get('cx'))
  239. cy = float(el.get('cy'))
  240. c['cx'] = round(cx, 3)
  241. c['cy'] = round(cy, 3)
  242. if color == 'ff0000':
  243. components['params'].append(c)
  244. if color == '00ff00':
  245. components['inputs'].append(c)
  246. if color == '0000ff':
  247. components['outputs'].append(c)
  248. if color == 'ff00ff':
  249. components['lights'].append(c)
  250. if color == 'ffff00':
  251. components['widgets'].append(c)
  252. # Sort components
  253. top_left_sort = lambda w: (w['cy'], w['cx'])
  254. components['params'] = sorted(components['params'], key=top_left_sort)
  255. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  256. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  257. components['lights'] = sorted(components['lights'], key=top_left_sort)
  258. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  259. 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.")
  260. return components
  261. def components_to_source(components, slug):
  262. identifier = slug_to_identifier(slug)
  263. source = ""
  264. source += f"""#include "plugin.hpp"
  265. struct {identifier} : Module {{"""
  266. # Params
  267. source += """
  268. enum ParamIds {"""
  269. for c in components['params']:
  270. source += f"""
  271. {c['name']}_PARAM,"""
  272. source += """
  273. NUM_PARAMS
  274. };"""
  275. # Inputs
  276. source += """
  277. enum InputIds {"""
  278. for c in components['inputs']:
  279. source += f"""
  280. {c['name']}_INPUT,"""
  281. source += """
  282. NUM_INPUTS
  283. };"""
  284. # Outputs
  285. source += """
  286. enum OutputIds {"""
  287. for c in components['outputs']:
  288. source += f"""
  289. {c['name']}_OUTPUT,"""
  290. source += """
  291. NUM_OUTPUTS
  292. };"""
  293. # Lights
  294. source += """
  295. enum LightIds {"""
  296. for c in components['lights']:
  297. source += f"""
  298. {c['name']}_LIGHT,"""
  299. source += """
  300. NUM_LIGHTS
  301. };"""
  302. source += f"""
  303. {identifier}() {{
  304. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  305. for c in components['params']:
  306. source += f"""
  307. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  308. source += """
  309. }
  310. void process(const ProcessArgs &args) override {
  311. }
  312. };"""
  313. source += f"""
  314. struct {identifier}Widget : ModuleWidget {{
  315. {identifier}Widget({identifier} *module) {{
  316. setModule(module);
  317. setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/{slug}.svg")));
  318. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  319. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  320. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  321. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  322. # Params
  323. if len(components['params']) > 0:
  324. source += "\n"
  325. for c in components['params']:
  326. if 'x' in c:
  327. source += f"""
  328. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  329. else:
  330. source += f"""
  331. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  332. # Inputs
  333. if len(components['inputs']) > 0:
  334. source += "\n"
  335. for c in components['inputs']:
  336. if 'x' in c:
  337. source += f"""
  338. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  339. else:
  340. source += f"""
  341. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  342. # Outputs
  343. if len(components['outputs']) > 0:
  344. source += "\n"
  345. for c in components['outputs']:
  346. if 'x' in c:
  347. source += f"""
  348. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  349. else:
  350. source += f"""
  351. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  352. # Lights
  353. if len(components['lights']) > 0:
  354. source += "\n"
  355. for c in components['lights']:
  356. if 'x' in c:
  357. source += f"""
  358. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  359. else:
  360. source += f"""
  361. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  362. # Widgets
  363. if len(components['widgets']) > 0:
  364. source += "\n"
  365. for c in components['widgets']:
  366. if 'x' in c:
  367. source += f"""
  368. // mm2px(Vec({c['width']}, {c['height']}))
  369. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  370. else:
  371. source += f"""
  372. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  373. source += f"""
  374. }}
  375. }};
  376. Model *model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  377. return source
  378. def usage(script):
  379. text = f"""VCV Rack Plugin Helper Utility
  380. Usage: {script} <command> ...
  381. Commands:
  382. createplugin <slug> [plugin dir]
  383. A directory will be created and initialized with a minimal plugin template.
  384. If no plugin directory is given, the slug is used.
  385. createmanifest <slug> [plugin dir]
  386. Creates a `plugin.json` manifest file in an existing plugin directory.
  387. If no plugin directory is given, the current directory is used.
  388. createmodule <module slug> [panel file] [source file]
  389. Adds a new module to the plugin manifest in the current directory.
  390. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  391. Example:
  392. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  393. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  394. """
  395. print(text)
  396. def parse_args(args):
  397. script = args.pop(0)
  398. if len(args) == 0:
  399. usage(script)
  400. return
  401. cmd = args.pop(0)
  402. if cmd == 'createplugin':
  403. create_plugin(*args)
  404. elif cmd == 'createmodule':
  405. create_module(*args)
  406. elif cmd == 'createmanifest':
  407. create_manifest(*args)
  408. else:
  409. print(f"Command not found: {cmd}")
  410. if __name__ == "__main__":
  411. try:
  412. parse_args(sys.argv)
  413. except KeyboardInterrupt:
  414. pass
  415. except UserException as e:
  416. print(e)
  417. sys.exit(1)