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.

helper.py 15KB

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