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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 eprint(*args, **kwargs):
  12. print(*args, file=sys.stderr, **kwargs)
  13. def find(f, array):
  14. for a in array:
  15. if f(a):
  16. return f
  17. def input_default(prompt, default=""):
  18. str = input(f"{prompt} [{default}]: ")
  19. if str == "":
  20. return default
  21. return str
  22. def is_valid_slug(slug):
  23. return re.match(r'^[a-zA-Z0-9_\-]+$', slug) != None
  24. def str_to_identifier(s):
  25. if not s:
  26. return "_"
  27. # Identifiers can't start with a number
  28. if s[0].isdigit():
  29. s = "_" + s
  30. # Capitalize first letter
  31. s = s[0].upper() + s[1:]
  32. # Replace special characters with underscore
  33. s = re.sub(r'\W', '_', s)
  34. return s
  35. def create_plugin(slug, plugin_dir=None):
  36. # Check slug
  37. if not is_valid_slug(slug):
  38. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  39. if not plugin_dir:
  40. plugin_dir = os.path.join(slug, '')
  41. # Check if plugin directory exists
  42. if os.path.exists(plugin_dir):
  43. raise UserException(f"Directory {plugin_dir} already exists")
  44. # Create plugin directory
  45. os.mkdir(plugin_dir)
  46. # Create manifest
  47. try:
  48. create_manifest(slug, plugin_dir)
  49. except Exception as e:
  50. os.rmdir(plugin_dir)
  51. raise e
  52. # Create subdirectories
  53. os.mkdir(os.path.join(plugin_dir, "src"))
  54. os.mkdir(os.path.join(plugin_dir, "res"))
  55. # Create Makefile
  56. makefile = """# If RACK_DIR is not defined when calling the Makefile, default to two directories above
  57. RACK_DIR ?= ../..
  58. # FLAGS will be passed to both the C and C++ compiler
  59. FLAGS +=
  60. CFLAGS +=
  61. CXXFLAGS +=
  62. # Careful about linking to shared libraries, since you can't assume much about the user's environment and library search path.
  63. # Static libraries are fine, but they should be added to this plugin's build system.
  64. LDFLAGS +=
  65. # Add .cpp files to the build
  66. SOURCES += $(wildcard src/*.cpp)
  67. # Add files to the ZIP package when running `make dist`
  68. # The compiled plugin and "plugin.json" are automatically added.
  69. DISTRIBUTABLES += res
  70. DISTRIBUTABLES += $(wildcard LICENSE*)
  71. DISTRIBUTABLES += $(wildcard presets)
  72. # Include the Rack plugin Makefile framework
  73. include $(RACK_DIR)/plugin.mk
  74. """
  75. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  76. f.write(makefile)
  77. # Create plugin.hpp
  78. plugin_hpp = """#pragma once
  79. #include <rack.hpp>
  80. using namespace rack;
  81. // Declare the Plugin, defined in plugin.cpp
  82. extern Plugin* pluginInstance;
  83. // Declare each Model, defined in each module source file
  84. // extern Model* modelMyModule;
  85. """
  86. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  87. f.write(plugin_hpp)
  88. # Create plugin.cpp
  89. plugin_cpp = """#include "plugin.hpp"
  90. Plugin* pluginInstance;
  91. void init(Plugin* p) {
  92. pluginInstance = p;
  93. // Add modules here
  94. // p->addModel(modelMyModule);
  95. // Any other plugin initialization may go here.
  96. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  97. }
  98. """
  99. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  100. f.write(plugin_cpp)
  101. git_ignore = """/build
  102. /dist
  103. /plugin.so
  104. /plugin.dylib
  105. /plugin.dll
  106. .DS_Store
  107. """
  108. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  109. f.write(git_ignore)
  110. eprint(f"Created template plugin in {plugin_dir}")
  111. os.system(f"cd {plugin_dir} && git init")
  112. eprint(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  113. def create_manifest(slug, plugin_dir="."):
  114. # Default manifest
  115. manifest = {
  116. 'slug': slug,
  117. }
  118. # Try to load existing manifest file
  119. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  120. try:
  121. with open(manifest_filename, "r") as f:
  122. manifest = json.load(f)
  123. except:
  124. pass
  125. # Query manifest information
  126. manifest['name'] = input_default("Plugin name", manifest.get('name', slug))
  127. manifest['version'] = input_default("Version", manifest.get('version', "2.0.0"))
  128. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", manifest.get('license', "proprietary"))
  129. manifest['brand'] = input_default("Brand (prefix for all module names)", manifest.get('brand', manifest['name']))
  130. manifest['author'] = input_default("Author", manifest.get('author', ""))
  131. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  132. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  133. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  134. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  135. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  136. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  137. manifest['changelogUrl'] = manifest.get('changelogUrl', "")
  138. if 'modules' not in manifest:
  139. manifest['modules'] = []
  140. # Dump JSON
  141. with open(manifest_filename, "w") as f:
  142. json.dump(manifest, f, indent=" ")
  143. eprint("")
  144. eprint(f"Manifest written to {manifest_filename}")
  145. def create_module(slug, panel_filename=None, source_filename=None):
  146. # Check slug
  147. if not is_valid_slug(slug):
  148. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  149. # Read manifest
  150. manifest_filename = 'plugin.json'
  151. with open(manifest_filename, "r") as f:
  152. manifest = json.load(f)
  153. # Check if module manifest exists
  154. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  155. if module_manifest:
  156. eprint(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  157. else:
  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/tag.cpp 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=" ")
  173. eprint(f"Added {slug} to {manifest_filename}")
  174. # Check filenames
  175. if panel_filename:
  176. if not os.path.exists(panel_filename):
  177. raise UserException(f"Panel not found at {panel_filename}.")
  178. if source_filename and os.path.exists(source_filename):
  179. if input_default(f"{source_filename} already exists. Overwrite? (y/n)", "n").lower() != "y":
  180. return
  181. # Read SVG XML
  182. tree = xml.etree.ElementTree.parse(panel_filename)
  183. components = panel_to_components(tree)
  184. # Tell user to add model to plugin.hpp and plugin.cpp
  185. identifier = str_to_identifier(slug)
  186. eprint(f"""
  187. To enable the module, add
  188. extern Model* model{identifier};
  189. to plugin.hpp, and add
  190. p->addModel(model{identifier});
  191. to the init() function in plugin.cpp.""")
  192. # Write source
  193. source = components_to_source(components, slug)
  194. if source_filename:
  195. with open(source_filename, "w") as f:
  196. f.write(source)
  197. eprint(f"Source file generated at {source_filename}")
  198. else:
  199. print(source)
  200. def panel_to_components(tree):
  201. ns = {
  202. "svg": "http://www.w3.org/2000/svg",
  203. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  204. }
  205. root = tree.getroot()
  206. # Get SVG scale relative to mm
  207. root_width = root.get('width')
  208. if re.match('\d+mm', root_width):
  209. scale = 1
  210. else:
  211. svg_dpi = 75
  212. mm_per_in = 25.4
  213. scale = mm_per_in / svg_dpi
  214. # Get components layer
  215. group = root.find(".//svg:g[@inkscape:label='components']", ns)
  216. # Illustrator uses `data-name` (in Unique object ID mode) or `id` (in Layer Names object ID mode) for the group name.
  217. # Don't test with `not group` since Elements with no subelements are falsy.
  218. if group is None:
  219. group = root.find(".//svg:g[@data-name='components']", ns)
  220. if group is None:
  221. group = root.find(".//svg:g[@id='components']", ns)
  222. if group is None:
  223. raise UserException("Could not find \"components\" layer on panel")
  224. components = {}
  225. components['params'] = []
  226. components['inputs'] = []
  227. components['outputs'] = []
  228. components['lights'] = []
  229. components['widgets'] = []
  230. for el in group:
  231. c = {}
  232. # Get name
  233. name = el.get('{' + ns['inkscape'] + '}label')
  234. # Illustrator names
  235. if not name:
  236. name = el.get('data-name')
  237. if not name:
  238. name = el.get('id')
  239. if not name:
  240. name = ""
  241. # Split name and component class name
  242. names = name.split('#', 1)
  243. name = names[0]
  244. if len(names) >= 2:
  245. c['cls'] = names[1]
  246. name = str_to_identifier(name).upper()
  247. c['name'] = name
  248. # Get position
  249. if el.tag == '{' + ns['svg'] + '}rect':
  250. x = float(el.get('x')) * scale
  251. y = float(el.get('y')) * scale
  252. width = float(el.get('width')) * scale
  253. height = float(el.get('height')) * scale
  254. c['x'] = round(x, 3)
  255. c['y'] = round(y, 3)
  256. c['width'] = round(width, 3)
  257. c['height'] = round(height, 3)
  258. c['cx'] = round(x + width / 2, 3)
  259. c['cy'] = round(y + height / 2, 3)
  260. elif el.tag == '{' + ns['svg'] + '}circle' or el.tag == '{' + ns['svg'] + '}ellipse':
  261. cx = float(el.get('cx')) * scale
  262. cy = float(el.get('cy')) * scale
  263. c['cx'] = round(cx, 3)
  264. c['cy'] = round(cy, 3)
  265. else:
  266. eprint(f"Element in components layer is not rect, circle, or ellipse: {el}")
  267. continue
  268. # Get color
  269. color = None
  270. # Get color from fill attribute
  271. fill = el.get('fill')
  272. if fill:
  273. color = fill
  274. # Get color from CSS fill style
  275. if not color:
  276. style = el.get('style')
  277. if style:
  278. color_match = re.search(r'fill:\S*(#[0-9a-fA-F]{6})', style)
  279. color = color_match.group(1)
  280. if not color:
  281. eprint(f"Cannot get color of component: {el}")
  282. continue
  283. color = color.lower()
  284. if color == '#ff0000' or color == '#f00' or color == 'red':
  285. components['params'].append(c)
  286. if color == '#00ff00' or color == '#0f0' or color == 'lime':
  287. components['inputs'].append(c)
  288. if color == '#0000ff' or color == '#00f' or color == 'blue':
  289. components['outputs'].append(c)
  290. if color == '#ff00ff' or color == '#f0f' or color == 'magenta':
  291. components['lights'].append(c)
  292. if color == '#ffff00' or color == '#ff0' or color == 'yellow':
  293. components['widgets'].append(c)
  294. # Sort components
  295. top_left_sort = lambda w: w['cy'] + 0.01 * w['cx']
  296. components['params'] = sorted(components['params'], key=top_left_sort)
  297. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  298. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  299. components['lights'] = sorted(components['lights'], key=top_left_sort)
  300. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  301. eprint(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.")
  302. return components
  303. def components_to_source(components, slug):
  304. identifier = str_to_identifier(slug)
  305. source = ""
  306. source += f"""#include "plugin.hpp"
  307. struct {identifier} : Module {{"""
  308. # Params
  309. source += """
  310. enum ParamId {"""
  311. for c in components['params']:
  312. source += f"""
  313. {c['name']}_PARAM,"""
  314. source += """
  315. PARAMS_LEN
  316. };"""
  317. # Inputs
  318. source += """
  319. enum InputId {"""
  320. for c in components['inputs']:
  321. source += f"""
  322. {c['name']}_INPUT,"""
  323. source += """
  324. INPUTS_LEN
  325. };"""
  326. # Outputs
  327. source += """
  328. enum OutputId {"""
  329. for c in components['outputs']:
  330. source += f"""
  331. {c['name']}_OUTPUT,"""
  332. source += """
  333. OUTPUTS_LEN
  334. };"""
  335. # Lights
  336. source += """
  337. enum LightId {"""
  338. for c in components['lights']:
  339. source += f"""
  340. {c['name']}_LIGHT,"""
  341. source += """
  342. LIGHTS_LEN
  343. };"""
  344. source += f"""
  345. {identifier}() {{
  346. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  347. for c in components['params']:
  348. source += f"""
  349. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  350. for c in components['inputs']:
  351. source += f"""
  352. configInput({c['name']}_INPUT, "");"""
  353. for c in components['outputs']:
  354. source += f"""
  355. configOutput({c['name']}_OUTPUT, "");"""
  356. source += """
  357. }
  358. void process(const ProcessArgs& args) override {
  359. }
  360. };"""
  361. source += f"""
  362. struct {identifier}Widget : ModuleWidget {{
  363. {identifier}Widget({identifier}* module) {{
  364. setModule(module);
  365. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  366. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  367. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  368. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  369. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  370. # Params
  371. if len(components['params']) > 0:
  372. source += "\n"
  373. for c in components['params']:
  374. if 'x' in c:
  375. source += f"""
  376. addParam(createParam<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  377. else:
  378. source += f"""
  379. addParam(createParamCentered<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  380. # Inputs
  381. if len(components['inputs']) > 0:
  382. source += "\n"
  383. for c in components['inputs']:
  384. if 'x' in c:
  385. source += f"""
  386. addInput(createInput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  387. else:
  388. source += f"""
  389. addInput(createInputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  390. # Outputs
  391. if len(components['outputs']) > 0:
  392. source += "\n"
  393. for c in components['outputs']:
  394. if 'x' in c:
  395. source += f"""
  396. addOutput(createOutput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  397. else:
  398. source += f"""
  399. addOutput(createOutputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  400. # Lights
  401. if len(components['lights']) > 0:
  402. source += "\n"
  403. for c in components['lights']:
  404. if 'x' in c:
  405. source += f"""
  406. addChild(createLight<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  407. else:
  408. source += f"""
  409. addChild(createLightCentered<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  410. # Widgets
  411. if len(components['widgets']) > 0:
  412. source += "\n"
  413. for c in components['widgets']:
  414. if 'x' in c:
  415. source += f"""
  416. // mm2px(Vec({c['width']}, {c['height']}))
  417. addChild(createWidget<{c.get('cls', 'Widget')}>(mm2px(Vec({c['x']}, {c['y']}))));"""
  418. else:
  419. source += f"""
  420. addChild(createWidgetCentered<{c.get('cls', 'Widget')}>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  421. source += f"""
  422. }}
  423. }};
  424. Model* model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  425. return source
  426. def usage(script):
  427. text = f"""VCV Rack Plugin Development Helper
  428. Usage: {script} <command> ...
  429. Commands:
  430. createplugin <slug> [plugin dir]
  431. A directory will be created and initialized with a minimal plugin template.
  432. If no plugin directory is given, the slug is used.
  433. createmanifest <slug> [plugin dir]
  434. Creates a `plugin.json` manifest file in an existing plugin directory.
  435. If no plugin directory is given, the current directory is used.
  436. createmodule <module slug> [panel file] [source file]
  437. Adds a new module to the plugin manifest in the current directory.
  438. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  439. Example:
  440. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  441. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  442. """
  443. eprint(text)
  444. def parse_args(args):
  445. script = args.pop(0)
  446. if len(args) == 0:
  447. usage(script)
  448. return
  449. cmd = args.pop(0)
  450. if cmd == 'createplugin':
  451. create_plugin(*args)
  452. elif cmd == 'createmodule':
  453. create_module(*args)
  454. elif cmd == 'createmanifest':
  455. create_manifest(*args)
  456. else:
  457. eprint(f"Command not found: {cmd}")
  458. if __name__ == "__main__":
  459. try:
  460. parse_args(sys.argv)
  461. except KeyboardInterrupt:
  462. pass
  463. except UserException as e:
  464. eprint(e)
  465. sys.exit(1)