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.

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