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.

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