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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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'] + 0.01 * 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. PARAMS_LEN
  281. };"""
  282. # Inputs
  283. source += """
  284. enum InputIds {"""
  285. for c in components['inputs']:
  286. source += f"""
  287. {c['name']}_INPUT,"""
  288. source += """
  289. INPUTS_LEN
  290. };"""
  291. # Outputs
  292. source += """
  293. enum OutputIds {"""
  294. for c in components['outputs']:
  295. source += f"""
  296. {c['name']}_OUTPUT,"""
  297. source += """
  298. OUTPUTS_LEN
  299. };"""
  300. # Lights
  301. source += """
  302. enum LightIds {"""
  303. for c in components['lights']:
  304. source += f"""
  305. {c['name']}_LIGHT,"""
  306. source += """
  307. LIGHTS_LEN
  308. };"""
  309. source += f"""
  310. {identifier}() {{
  311. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  312. for c in components['params']:
  313. source += f"""
  314. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  315. for c in components['inputs']:
  316. source += f"""
  317. configInput({c['name']}_INPUT, "");"""
  318. for c in components['outputs']:
  319. source += f"""
  320. configOutput({c['name']}_OUTPUT, "");"""
  321. source += """
  322. }
  323. void process(const ProcessArgs& args) override {
  324. }
  325. };"""
  326. source += f"""
  327. struct {identifier}Widget : ModuleWidget {{
  328. {identifier}Widget({identifier}* module) {{
  329. setModule(module);
  330. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  331. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  332. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  333. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  334. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  335. # Params
  336. if len(components['params']) > 0:
  337. source += "\n"
  338. for c in components['params']:
  339. if 'x' in c:
  340. source += f"""
  341. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  342. else:
  343. source += f"""
  344. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  345. # Inputs
  346. if len(components['inputs']) > 0:
  347. source += "\n"
  348. for c in components['inputs']:
  349. if 'x' in c:
  350. source += f"""
  351. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  352. else:
  353. source += f"""
  354. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  355. # Outputs
  356. if len(components['outputs']) > 0:
  357. source += "\n"
  358. for c in components['outputs']:
  359. if 'x' in c:
  360. source += f"""
  361. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  362. else:
  363. source += f"""
  364. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  365. # Lights
  366. if len(components['lights']) > 0:
  367. source += "\n"
  368. for c in components['lights']:
  369. if 'x' in c:
  370. source += f"""
  371. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  372. else:
  373. source += f"""
  374. addChild(createLightCentered<MediumLight<RedLight>>(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 Development Helper
  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)