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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 `data-name` (in Unique object ID mode) or `id` (in Layer Names object ID mode) 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[@data-name='components']", ns)
  214. if group is None:
  215. group = root.find(".//svg:g[@id='components']", ns)
  216. if group is None:
  217. raise UserException("Could not find \"components\" layer on panel")
  218. components = {}
  219. components['params'] = []
  220. components['inputs'] = []
  221. components['outputs'] = []
  222. components['lights'] = []
  223. components['widgets'] = []
  224. for el in group:
  225. c = {}
  226. # Get name
  227. name = el.get('{' + ns['inkscape'] + '}label')
  228. # Illustrator names
  229. if not name:
  230. name = el.get('data-name')
  231. if not name:
  232. name = el.get('id')
  233. if not name:
  234. name = ""
  235. # Split name and component class name
  236. names = name.split('#', 1)
  237. name = names[0]
  238. if len(names) >= 2:
  239. c['cls'] = names[1]
  240. name = str_to_identifier(name).upper()
  241. c['name'] = name
  242. # Get position
  243. if el.tag == '{' + ns['svg'] + '}rect':
  244. x = float(el.get('x')) * scale
  245. y = float(el.get('y')) * scale
  246. width = float(el.get('width')) * scale
  247. height = float(el.get('height')) * scale
  248. c['x'] = round(x, 3)
  249. c['y'] = round(y, 3)
  250. c['width'] = round(width, 3)
  251. c['height'] = round(height, 3)
  252. c['cx'] = round(x + width / 2, 3)
  253. c['cy'] = round(y + height / 2, 3)
  254. elif el.tag == '{' + ns['svg'] + '}circle' or el.tag == '{' + ns['svg'] + '}ellipse':
  255. cx = float(el.get('cx')) * scale
  256. cy = float(el.get('cy')) * scale
  257. c['cx'] = round(cx, 3)
  258. c['cy'] = round(cy, 3)
  259. else:
  260. print(f"Element in components layer is not rect, circle, or ellipse: {el}")
  261. continue
  262. # Get color
  263. color = None
  264. # Get color from fill attribute
  265. fill = el.get('fill')
  266. if fill:
  267. color = fill
  268. # Get color from CSS fill style
  269. if not color:
  270. style = el.get('style')
  271. if style:
  272. color_match = re.search(r'fill:\S*(#.{6});', style)
  273. color = color_match.group(1)
  274. if not color:
  275. print(f"Cannot get color of component: {el}")
  276. continue
  277. print(color)
  278. color = color.lower()
  279. if color == '#ff0000' or color == '#f00' or color == 'red':
  280. components['params'].append(c)
  281. if color == '#00ff00' or color == '#0f0' or color == 'lime':
  282. components['inputs'].append(c)
  283. if color == '#0000ff' or color == '#00f' or color == 'blue':
  284. components['outputs'].append(c)
  285. if color == '#ff00ff' or color == '#f0f' or color == 'magenta':
  286. components['lights'].append(c)
  287. if color == '#ffff00' or color == '#ff0' or color == 'yellow':
  288. components['widgets'].append(c)
  289. # Sort components
  290. top_left_sort = lambda w: w['cy'] + 0.01 * w['cx']
  291. components['params'] = sorted(components['params'], key=top_left_sort)
  292. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  293. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  294. components['lights'] = sorted(components['lights'], key=top_left_sort)
  295. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  296. 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.")
  297. return components
  298. def components_to_source(components, slug):
  299. identifier = str_to_identifier(slug)
  300. source = ""
  301. source += f"""#include "plugin.hpp"
  302. struct {identifier} : Module {{"""
  303. # Params
  304. source += """
  305. enum ParamId {"""
  306. for c in components['params']:
  307. source += f"""
  308. {c['name']}_PARAM,"""
  309. source += """
  310. PARAMS_LEN
  311. };"""
  312. # Inputs
  313. source += """
  314. enum InputId {"""
  315. for c in components['inputs']:
  316. source += f"""
  317. {c['name']}_INPUT,"""
  318. source += """
  319. INPUTS_LEN
  320. };"""
  321. # Outputs
  322. source += """
  323. enum OutputId {"""
  324. for c in components['outputs']:
  325. source += f"""
  326. {c['name']}_OUTPUT,"""
  327. source += """
  328. OUTPUTS_LEN
  329. };"""
  330. # Lights
  331. source += """
  332. enum LightId {"""
  333. for c in components['lights']:
  334. source += f"""
  335. {c['name']}_LIGHT,"""
  336. source += """
  337. LIGHTS_LEN
  338. };"""
  339. source += f"""
  340. {identifier}() {{
  341. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  342. for c in components['params']:
  343. source += f"""
  344. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  345. for c in components['inputs']:
  346. source += f"""
  347. configInput({c['name']}_INPUT, "");"""
  348. for c in components['outputs']:
  349. source += f"""
  350. configOutput({c['name']}_OUTPUT, "");"""
  351. source += """
  352. }
  353. void process(const ProcessArgs& args) override {
  354. }
  355. };"""
  356. source += f"""
  357. struct {identifier}Widget : ModuleWidget {{
  358. {identifier}Widget({identifier}* module) {{
  359. setModule(module);
  360. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  361. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  362. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  363. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  364. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  365. # Params
  366. if len(components['params']) > 0:
  367. source += "\n"
  368. for c in components['params']:
  369. if 'x' in c:
  370. source += f"""
  371. addParam(createParam<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  372. else:
  373. source += f"""
  374. addParam(createParamCentered<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  375. # Inputs
  376. if len(components['inputs']) > 0:
  377. source += "\n"
  378. for c in components['inputs']:
  379. if 'x' in c:
  380. source += f"""
  381. addInput(createInput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  382. else:
  383. source += f"""
  384. addInput(createInputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  385. # Outputs
  386. if len(components['outputs']) > 0:
  387. source += "\n"
  388. for c in components['outputs']:
  389. if 'x' in c:
  390. source += f"""
  391. addOutput(createOutput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  392. else:
  393. source += f"""
  394. addOutput(createOutputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  395. # Lights
  396. if len(components['lights']) > 0:
  397. source += "\n"
  398. for c in components['lights']:
  399. if 'x' in c:
  400. source += f"""
  401. addChild(createLight<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  402. else:
  403. source += f"""
  404. addChild(createLightCentered<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  405. # Widgets
  406. if len(components['widgets']) > 0:
  407. source += "\n"
  408. for c in components['widgets']:
  409. if 'x' in c:
  410. source += f"""
  411. // mm2px(Vec({c['width']}, {c['height']}))
  412. addChild(createWidget<{c.get('cls', 'Widget')}>(mm2px(Vec({c['x']}, {c['y']}))));"""
  413. else:
  414. source += f"""
  415. addChild(createWidgetCentered<{c.get('cls', 'Widget')}>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  416. source += f"""
  417. }}
  418. }};
  419. Model* model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  420. return source
  421. def usage(script):
  422. text = f"""VCV Rack Plugin Development Helper
  423. Usage: {script} <command> ...
  424. Commands:
  425. createplugin <slug> [plugin dir]
  426. A directory will be created and initialized with a minimal plugin template.
  427. If no plugin directory is given, the slug is used.
  428. createmanifest <slug> [plugin dir]
  429. Creates a `plugin.json` manifest file in an existing plugin directory.
  430. If no plugin directory is given, the current directory is used.
  431. createmodule <module slug> [panel file] [source file]
  432. Adds a new module to the plugin manifest in the current directory.
  433. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  434. Example:
  435. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  436. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  437. """
  438. print(text)
  439. def parse_args(args):
  440. script = args.pop(0)
  441. if len(args) == 0:
  442. usage(script)
  443. return
  444. cmd = args.pop(0)
  445. if cmd == 'createplugin':
  446. create_plugin(*args)
  447. elif cmd == 'createmodule':
  448. create_module(*args)
  449. elif cmd == 'createmanifest':
  450. create_manifest(*args)
  451. else:
  452. print(f"Command not found: {cmd}")
  453. if __name__ == "__main__":
  454. try:
  455. parse_args(sys.argv)
  456. except KeyboardInterrupt:
  457. pass
  458. except UserException as e:
  459. print(e)
  460. sys.exit(1)