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