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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 usage(script):
  29. text = f"""Usage: {script} <command> ...
  30. Run commands without arguments for command help.
  31. Commands:
  32. createplugin <slug>
  33. createmodule <module slug>
  34. createmanifest
  35. """
  36. print(text)
  37. def usage_create_plugin(script):
  38. text = f"""Usage: {script} createplugin <slug>
  39. A directory <slug> will be created in the current working directory and seeded with initial files.
  40. """
  41. print(text)
  42. def create_plugin(slug):
  43. # Check slug
  44. if not is_valid_slug(slug):
  45. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  46. # Check if plugin directory exists
  47. plugin_dir = os.path.join(slug, '')
  48. if os.path.exists(plugin_dir):
  49. raise UserException(f"Directory {plugin_dir} already exists")
  50. # Create plugin directory
  51. os.mkdir(plugin_dir)
  52. # Create manifest
  53. try:
  54. create_manifest(plugin_dir, slug)
  55. except Exception as e:
  56. os.rmdir(plugin_dir)
  57. raise e
  58. # Create subdirectories
  59. os.mkdir(os.path.join(plugin_dir, "src"))
  60. os.mkdir(os.path.join(plugin_dir, "res"))
  61. # Create Makefile
  62. makefile = """# If RACK_DIR is not defined when calling the Makefile, default to two directories above
  63. RACK_DIR ?= ../..
  64. # FLAGS will be passed to both the C and C++ compiler
  65. FLAGS +=
  66. CFLAGS +=
  67. CXXFLAGS +=
  68. # Careful about linking to shared libraries, since you can't assume much about the user's environment and library search path.
  69. # Static libraries are fine, but they should be added to this plugin's build system.
  70. LDFLAGS +=
  71. # Add .cpp files to the build
  72. SOURCES += $(wildcard src/*.cpp)
  73. # Add files to the ZIP package when running `make dist`
  74. # The compiled plugin and "plugin.json" are automatically added.
  75. DISTRIBUTABLES += res
  76. DISTRIBUTABLES += $(wildcard LICENSE*)
  77. # Include the Rack plugin Makefile framework
  78. include $(RACK_DIR)/plugin.mk
  79. """
  80. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  81. f.write(makefile)
  82. # Create plugin.hpp
  83. plugin_hpp = """#include "rack.hpp"
  84. using namespace rack;
  85. // Declare the Plugin, defined in plugin.cpp
  86. extern Plugin *pluginInstance;
  87. // Declare each Model, defined in each module source file
  88. """
  89. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  90. f.write(plugin_hpp)
  91. # Create plugin.cpp
  92. plugin_cpp = """#include "plugin.hpp"
  93. Plugin *pluginInstance;
  94. void init(Plugin *p) {
  95. pluginInstance = p;
  96. // Add modules here, e.g.
  97. // p->addModel(modelMyModule);
  98. // Any other plugin initialization may go here.
  99. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  100. }
  101. """
  102. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  103. f.write(plugin_cpp)
  104. git_ignore = """/build
  105. /dist
  106. /plugin.so
  107. /plugin.dylib
  108. /plugin.dll
  109. .DS_Store
  110. """
  111. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  112. f.write(git_ignore)
  113. print(f"Created template plugin in {plugin_dir}")
  114. os.system(f"cd {plugin_dir} && git init")
  115. print(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  116. def create_manifest(plugin_dir, slug=None):
  117. manifest = {}
  118. # Query manifest information
  119. if not slug:
  120. slug = input_default("Plugin slug (unique identifier)")
  121. manifest['slug'] = slug
  122. manifest['name'] = input_default("Plugin name", slug)
  123. manifest['version'] = input_default("Version", "1.0.0")
  124. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", "proprietary")
  125. manifest['author'] = input_default("Author")
  126. manifest['authorEmail'] = input_default("Author email (optional)")
  127. manifest['authorUrl'] = input_default("Author website URL (optional)")
  128. manifest['pluginUrl'] = input_default("Plugin website URL (optional)")
  129. manifest['manualUrl'] = input_default("Manual website URL (optional)")
  130. manifest['sourceUrl'] = input_default("Source code URL (optional)")
  131. manifest['donateUrl'] = input_default("Donate URL (optional)")
  132. manifest['modules'] = []
  133. # Dump JSON
  134. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  135. with open(manifest_filename, "w") as f:
  136. json.dump(manifest, f, indent="\t")
  137. print(f"Manifest created at {manifest_filename}")
  138. def usage_create_module(script):
  139. text = f"""Usage: {script} createmodule <module slug>
  140. Must be called in a plugin directory.
  141. A panel file must exist in res/<module slug>.svg.
  142. A source file will be created at src/<module slug>.cpp.
  143. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  144. """
  145. print(text)
  146. def create_module(slug):
  147. # Check slug
  148. if not is_valid_slug(slug):
  149. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  150. # Read manifest
  151. manifest_filename = 'plugin.json'
  152. manifest = None
  153. with open(manifest_filename, "r") as f:
  154. manifest = json.load(f)
  155. # Check if module manifest exists
  156. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  157. if not module_manifest:
  158. # Add module to manifest
  159. module_manifest = {}
  160. module_manifest['slug'] = slug
  161. module_manifest['name'] = input_default("Module name", slug)
  162. module_manifest['description'] = input_default("One-line description (optional)")
  163. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/plugin.cpp#L543 for list)")
  164. tags = tags.split(",")
  165. tags = [tag.strip() for tag in tags]
  166. if len(tags) == 1 and tags[0] == "":
  167. tags = []
  168. module_manifest['tags'] = tags
  169. manifest['modules'].append(module_manifest)
  170. # Write manifest
  171. with open(manifest_filename, "w") as f:
  172. json.dump(manifest, f, indent="\t")
  173. print(f"Added {slug} to plugin.json")
  174. else:
  175. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  176. # Check filenames
  177. panel_filename = f"res/{slug}.svg"
  178. source_filename = f"src/{slug}.cpp"
  179. if not os.path.exists(panel_filename):
  180. print(f"Panel not found at {panel_filename}. If you wish to automatically generate a source file, run this command with no arguments for instructions for creating a panel file.")
  181. return
  182. print(f"Panel found at {panel_filename}. Generating source file.")
  183. if os.path.exists(source_filename):
  184. if input_default(f"{source_filename} already exists. Overwrite?", "n").lower() != "y":
  185. return
  186. # Read SVG XML
  187. tree = xml.etree.ElementTree.parse(panel_filename)
  188. components = panel_to_components(tree)
  189. print(f"Components extracted from {panel_filename}")
  190. # Write source
  191. source = components_to_source(components, slug)
  192. with open(source_filename, "w") as f:
  193. f.write(source)
  194. print(f"Source file generated at {source_filename}")
  195. # Append model to plugin.hpp
  196. identifier = slug_to_identifier(slug)
  197. # Tell user to add model to plugin.hpp and plugin.cpp
  198. print(f"")
  199. print(f"To enable the module, add")
  200. print(f"extern Model *model{identifier};")
  201. print(f"to plugin.hpp, and add")
  202. print(f"p->addModel(model{identifier});")
  203. print(f"to the init() function in plugin.cpp.")
  204. def panel_to_components(tree):
  205. ns = {
  206. "svg": "http://www.w3.org/2000/svg",
  207. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  208. }
  209. # Get components layer
  210. root = tree.getroot()
  211. groups = root.findall(".//svg:g[@inkscape:label='components']", ns)
  212. if len(groups) < 1:
  213. raise UserException("Could not find \"components\" layer on panel")
  214. # Get circles and rects
  215. components_group = groups[0]
  216. circles = components_group.findall(".//svg:circle", ns)
  217. rects = components_group.findall(".//svg:rect", ns)
  218. components = {}
  219. components['params'] = []
  220. components['inputs'] = []
  221. components['outputs'] = []
  222. components['lights'] = []
  223. components['widgets'] = []
  224. for el in circles + rects:
  225. c = {}
  226. # Get name
  227. name = el.get('inkscape:label')
  228. if name is None:
  229. name = el.get('id')
  230. name = slug_to_identifier(name).upper()
  231. c['name'] = name
  232. # Get color
  233. style = el.get('style')
  234. color_match = re.search(r'fill:\S*#(.{6});', style)
  235. color = color_match.group(1)
  236. c['color'] = color
  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'], 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.")
  272. return components
  273. def components_to_source(components, slug):
  274. identifier = slug_to_identifier(slug)
  275. source = ""
  276. source += f"""#include "plugin.hpp"
  277. struct {identifier} : Module {{"""
  278. # Params
  279. source += """
  280. enum ParamIds {"""
  281. for c in components['params']:
  282. source += f"""
  283. {c['name']}_PARAM,"""
  284. source += """
  285. NUM_PARAMS
  286. };"""
  287. # Inputs
  288. source += """
  289. enum InputIds {"""
  290. for c in components['inputs']:
  291. source += f"""
  292. {c['name']}_INPUT,"""
  293. source += """
  294. NUM_INPUTS
  295. };"""
  296. # Outputs
  297. source += """
  298. enum OutputIds {"""
  299. for c in components['outputs']:
  300. source += f"""
  301. {c['name']}_OUTPUT,"""
  302. source += """
  303. NUM_OUTPUTS
  304. };"""
  305. # Lights
  306. source += """
  307. enum LightIds {"""
  308. for c in components['lights']:
  309. source += f"""
  310. {c['name']}_LIGHT,"""
  311. source += """
  312. NUM_LIGHTS
  313. };"""
  314. source += f"""
  315. {identifier}() {{
  316. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  317. for c in components['params']:
  318. source += f"""
  319. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  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(APP->window->loadSvg(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 parse_args(args):
  391. if len(args) >= 2:
  392. if args[1] == 'createplugin':
  393. if len(args) >= 3:
  394. create_plugin(args[2])
  395. return
  396. usage_create_plugin(args[0])
  397. return
  398. if args[1] == 'createmodule':
  399. if len(args) >= 3:
  400. create_module(args[2])
  401. return
  402. usage_create_module(args[0])
  403. return
  404. if args[1] == 'createmanifest':
  405. create_manifest('.')
  406. return
  407. usage(args[0])
  408. if __name__ == "__main__":
  409. try:
  410. parse_args(sys.argv)
  411. except KeyboardInterrupt:
  412. pass
  413. except UserException as e:
  414. print(e)
  415. sys.exit(1)