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