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.

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