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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. DISTRIBUTABLES += $(wildcard presets)
  70. # Include the Rack plugin Makefile framework
  71. include $(RACK_DIR)/plugin.mk
  72. """
  73. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  74. f.write(makefile)
  75. # Create plugin.hpp
  76. plugin_hpp = """#pragma once
  77. #include <rack.hpp>
  78. using namespace rack;
  79. // Declare the Plugin, defined in plugin.cpp
  80. extern Plugin* pluginInstance;
  81. // Declare each Model, defined in each module source file
  82. // extern Model* modelMyModule;
  83. """
  84. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  85. f.write(plugin_hpp)
  86. # Create plugin.cpp
  87. plugin_cpp = """#include "plugin.hpp"
  88. Plugin* pluginInstance;
  89. void init(Plugin* p) {
  90. pluginInstance = p;
  91. // Add modules here
  92. // p->addModel(modelMyModule);
  93. // Any other plugin initialization may go here.
  94. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  95. }
  96. """
  97. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  98. f.write(plugin_cpp)
  99. git_ignore = """/build
  100. /dist
  101. /plugin.so
  102. /plugin.dylib
  103. /plugin.dll
  104. .DS_Store
  105. """
  106. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  107. f.write(git_ignore)
  108. print(f"Created template plugin in {plugin_dir}")
  109. os.system(f"cd {plugin_dir} && git init")
  110. print(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  111. def create_manifest(slug, plugin_dir="."):
  112. # Default manifest
  113. manifest = {
  114. 'slug': slug,
  115. }
  116. # Try to load existing manifest file
  117. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  118. try:
  119. with open(manifest_filename, "r") as f:
  120. manifest = json.load(f)
  121. except:
  122. pass
  123. # Query manifest information
  124. manifest['name'] = input_default("Plugin name", manifest.get('name', slug))
  125. manifest['version'] = input_default("Version", manifest.get('version', "1.0.0"))
  126. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", manifest.get('license', "proprietary"))
  127. manifest['brand'] = input_default("Brand (prefix for all module names)", manifest.get('brand', manifest['name']))
  128. manifest['author'] = input_default("Author", manifest.get('author', ""))
  129. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  130. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  131. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  132. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  133. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  134. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  135. manifest['changelogUrl'] = manifest.get('changelogUrl', "")
  136. if 'modules' not in manifest:
  137. manifest['modules'] = []
  138. # Dump JSON
  139. with open(manifest_filename, "w") as f:
  140. json.dump(manifest, f, indent=" ")
  141. print("")
  142. print(f"Manifest written to {manifest_filename}")
  143. def create_module(slug, panel_filename=None, source_filename=None):
  144. # Check slug
  145. if not is_valid_slug(slug):
  146. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  147. # Read manifest
  148. manifest_filename = 'plugin.json'
  149. with open(manifest_filename, "r") as f:
  150. manifest = json.load(f)
  151. # Check if module manifest exists
  152. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  153. if module_manifest:
  154. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  155. else:
  156. # Add module to manifest
  157. module_manifest = {}
  158. module_manifest['slug'] = slug
  159. module_manifest['name'] = input_default("Module name", slug)
  160. module_manifest['description'] = input_default("One-line description (optional)")
  161. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/tag.cpp for list)")
  162. tags = tags.split(",")
  163. tags = [tag.strip() for tag in tags]
  164. if len(tags) == 1 and tags[0] == "":
  165. tags = []
  166. module_manifest['tags'] = tags
  167. manifest['modules'].append(module_manifest)
  168. # Write manifest
  169. with open(manifest_filename, "w") as f:
  170. json.dump(manifest, f, indent=" ")
  171. print(f"Added {slug} to {manifest_filename}")
  172. # Check filenames
  173. if panel_filename and source_filename:
  174. if not os.path.exists(panel_filename):
  175. raise UserException(f"Panel not found at {panel_filename}.")
  176. if os.path.exists(source_filename):
  177. if input_default(f"{source_filename} already exists. Overwrite? (y/n)", "n").lower() != "y":
  178. return
  179. # Read SVG XML
  180. tree = xml.etree.ElementTree.parse(panel_filename)
  181. components = panel_to_components(tree)
  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. root = tree.getroot()
  202. # Get SVG scale
  203. root_width = root.get('width')
  204. svg_dpi = 75
  205. scale = 1
  206. if re.match('\d+px', root_width):
  207. scale = 25.4 / svg_dpi
  208. # Get components layer
  209. group = root.find(".//svg:g[@inkscape:label='components']", ns)
  210. # Illustrator uses `id` for the group name.
  211. # Don't test with `not group` since Elements with no subelements are falsy.
  212. if group is None:
  213. group = root.find(".//svg:g[@id='components']", ns)
  214. if group is None:
  215. raise UserException("Could not find \"components\" layer on panel")
  216. components = {}
  217. components['params'] = []
  218. components['inputs'] = []
  219. components['outputs'] = []
  220. components['lights'] = []
  221. components['widgets'] = []
  222. for el in group:
  223. c = {}
  224. # Get name
  225. name = el.get('{' + ns['inkscape'] + '}label')
  226. if not name:
  227. name = el.get('id')
  228. if not name:
  229. name = ""
  230. name = str_to_identifier(name).upper()
  231. c['name'] = name
  232. # Get position
  233. if el.tag == '{' + ns['svg'] + '}rect':
  234. x = float(el.get('x')) * scale
  235. y = float(el.get('y')) * scale
  236. width = float(el.get('width')) * scale
  237. height = float(el.get('height')) * scale
  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 == '{' + ns['svg'] + '}circle' or el.tag == '{' + ns['svg'] + '}ellipse':
  245. cx = float(el.get('cx')) * scale
  246. cy = float(el.get('cy')) * scale
  247. c['cx'] = round(cx, 3)
  248. c['cy'] = round(cy, 3)
  249. else:
  250. print(f"Element in components layer is not rect, circle, or ellipse: {el}")
  251. continue
  252. # Get color
  253. fill = el.get('fill')
  254. style = el.get('style')
  255. if fill:
  256. color_match = re.search(r'#(.{6})', fill)
  257. color = color_match.group(1).lower()
  258. elif style:
  259. color_match = re.search(r'fill:\S*#(.{6});', style)
  260. color = color_match.group(1).lower()
  261. else:
  262. print(f"Cannot get color of component: {el}")
  263. continue
  264. if color == 'ff0000':
  265. components['params'].append(c)
  266. if color == '00ff00':
  267. components['inputs'].append(c)
  268. if color == '0000ff':
  269. components['outputs'].append(c)
  270. if color == 'ff00ff':
  271. components['lights'].append(c)
  272. if color == 'ffff00':
  273. components['widgets'].append(c)
  274. # Sort components
  275. top_left_sort = lambda w: w['cy'] + 0.01 * w['cx']
  276. components['params'] = sorted(components['params'], key=top_left_sort)
  277. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  278. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  279. components['lights'] = sorted(components['lights'], key=top_left_sort)
  280. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  281. 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.")
  282. return components
  283. def components_to_source(components, slug):
  284. identifier = str_to_identifier(slug)
  285. source = ""
  286. source += f"""#include "plugin.hpp"
  287. struct {identifier} : Module {{"""
  288. # Params
  289. source += """
  290. enum ParamId {"""
  291. for c in components['params']:
  292. source += f"""
  293. {c['name']}_PARAM,"""
  294. source += """
  295. PARAMS_LEN
  296. };"""
  297. # Inputs
  298. source += """
  299. enum InputId {"""
  300. for c in components['inputs']:
  301. source += f"""
  302. {c['name']}_INPUT,"""
  303. source += """
  304. INPUTS_LEN
  305. };"""
  306. # Outputs
  307. source += """
  308. enum OutputId {"""
  309. for c in components['outputs']:
  310. source += f"""
  311. {c['name']}_OUTPUT,"""
  312. source += """
  313. OUTPUTS_LEN
  314. };"""
  315. # Lights
  316. source += """
  317. enum LightId {"""
  318. for c in components['lights']:
  319. source += f"""
  320. {c['name']}_LIGHT,"""
  321. source += """
  322. LIGHTS_LEN
  323. };"""
  324. source += f"""
  325. {identifier}() {{
  326. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  327. for c in components['params']:
  328. source += f"""
  329. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  330. for c in components['inputs']:
  331. source += f"""
  332. configInput({c['name']}_INPUT, "");"""
  333. for c in components['outputs']:
  334. source += f"""
  335. configOutput({c['name']}_OUTPUT, "");"""
  336. source += """
  337. }
  338. void process(const ProcessArgs& args) override {
  339. }
  340. };"""
  341. source += f"""
  342. struct {identifier}Widget : ModuleWidget {{
  343. {identifier}Widget({identifier}* module) {{
  344. setModule(module);
  345. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  346. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  347. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  348. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  349. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  350. # Params
  351. if len(components['params']) > 0:
  352. source += "\n"
  353. for c in components['params']:
  354. if 'x' in c:
  355. source += f"""
  356. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  357. else:
  358. source += f"""
  359. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  360. # Inputs
  361. if len(components['inputs']) > 0:
  362. source += "\n"
  363. for c in components['inputs']:
  364. if 'x' in c:
  365. source += f"""
  366. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  367. else:
  368. source += f"""
  369. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  370. # Outputs
  371. if len(components['outputs']) > 0:
  372. source += "\n"
  373. for c in components['outputs']:
  374. if 'x' in c:
  375. source += f"""
  376. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  377. else:
  378. source += f"""
  379. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  380. # Lights
  381. if len(components['lights']) > 0:
  382. source += "\n"
  383. for c in components['lights']:
  384. if 'x' in c:
  385. source += f"""
  386. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  387. else:
  388. source += f"""
  389. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  390. # Widgets
  391. if len(components['widgets']) > 0:
  392. source += "\n"
  393. for c in components['widgets']:
  394. if 'x' in c:
  395. source += f"""
  396. // mm2px(Vec({c['width']}, {c['height']}))
  397. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  398. else:
  399. source += f"""
  400. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  401. source += f"""
  402. }}
  403. }};
  404. Model* model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  405. return source
  406. def usage(script):
  407. text = f"""VCV Rack Plugin Development Helper
  408. Usage: {script} <command> ...
  409. Commands:
  410. createplugin <slug> [plugin dir]
  411. A directory will be created and initialized with a minimal plugin template.
  412. If no plugin directory is given, the slug is used.
  413. createmanifest <slug> [plugin dir]
  414. Creates a `plugin.json` manifest file in an existing plugin directory.
  415. If no plugin directory is given, the current directory is used.
  416. createmodule <module slug> [panel file] [source file]
  417. Adds a new module to the plugin manifest in the current directory.
  418. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  419. Example:
  420. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  421. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  422. """
  423. print(text)
  424. def parse_args(args):
  425. script = args.pop(0)
  426. if len(args) == 0:
  427. usage(script)
  428. return
  429. cmd = args.pop(0)
  430. if cmd == 'createplugin':
  431. create_plugin(*args)
  432. elif cmd == 'createmodule':
  433. create_module(*args)
  434. elif cmd == 'createmanifest':
  435. create_manifest(*args)
  436. else:
  437. print(f"Command not found: {cmd}")
  438. if __name__ == "__main__":
  439. try:
  440. parse_args(sys.argv)
  441. except KeyboardInterrupt:
  442. pass
  443. except UserException as e:
  444. print(e)
  445. sys.exit(1)