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.

527 lines
14KB

  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import re
  5. import json
  6. import xml.etree.ElementTree
  7. if sys.version_info < (3, 6):
  8. print("Python 3.6 or higher required")
  9. exit(1)
  10. class UserException(Exception):
  11. pass
  12. def find(f, array):
  13. for a in array:
  14. if f(a):
  15. return f
  16. def input_default(prompt, default=""):
  17. str = input(f"{prompt} [{default}]: ")
  18. if str == "":
  19. return default
  20. return str
  21. def is_valid_slug(slug):
  22. return re.match(r'^[a-zA-Z0-9_\-]+$', slug) != None
  23. def slug_to_identifier(slug):
  24. if len(slug) == 0 or slug[0].isdigit():
  25. slug = "_" + slug
  26. slug = slug[0].upper() + slug[1:]
  27. slug = slug.replace('-', '_')
  28. return slug
  29. def usage(script):
  30. text = f"""Usage: {script} <command> ...
  31. Run commands without arguments for command help.
  32. Commands:
  33. createplugin <slug>
  34. createmodule <module slug>
  35. createmanifest
  36. """
  37. print(text)
  38. def usage_create_plugin(script):
  39. text = f"""Usage: {script} createplugin <slug>
  40. A directory <slug> will be created in the current working directory and seeded with initial files.
  41. """
  42. print(text)
  43. def create_plugin(slug):
  44. # Check slug
  45. if not is_valid_slug(slug):
  46. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  47. # Check if plugin directory exists
  48. plugin_dir = os.path.join(slug, '')
  49. if os.path.exists(plugin_dir):
  50. raise UserException(f"Directory {plugin_dir} already exists")
  51. # Create plugin directory
  52. os.mkdir(plugin_dir)
  53. # Create manifest
  54. try:
  55. create_manifest(plugin_dir, slug)
  56. except Exception as e:
  57. os.rmdir(plugin_dir)
  58. raise e
  59. # Create subdirectories
  60. os.mkdir(os.path.join(plugin_dir, "src"))
  61. os.mkdir(os.path.join(plugin_dir, "res"))
  62. # Create Makefile
  63. makefile = """# If RACK_DIR is not defined when calling the Makefile, default to two directories above
  64. RACK_DIR ?= ../..
  65. # FLAGS will be passed to both the C and C++ compiler
  66. FLAGS +=
  67. CFLAGS +=
  68. CXXFLAGS +=
  69. # Careful about linking to shared libraries, since you can't assume much about the user's environment and library search path.
  70. # Static libraries are fine, but they should be added to this plugin's build system.
  71. LDFLAGS +=
  72. # Add .cpp files to the build
  73. SOURCES += $(wildcard src/*.cpp)
  74. # Add files to the ZIP package when running `make dist`
  75. # The compiled plugin and "plugin.json" are automatically added.
  76. DISTRIBUTABLES += res
  77. DISTRIBUTABLES += $(wildcard LICENSE*)
  78. # Include the Rack plugin Makefile framework
  79. include $(RACK_DIR)/plugin.mk
  80. """
  81. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  82. f.write(makefile)
  83. # Create plugin.hpp
  84. plugin_hpp = """#include "rack.hpp"
  85. using namespace rack;
  86. // Declare the Plugin, defined in plugin.cpp
  87. extern Plugin *pluginInstance;
  88. // Declare each Model, defined in each module source file
  89. """
  90. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  91. f.write(plugin_hpp)
  92. # Create plugin.cpp
  93. plugin_cpp = """#include "plugin.hpp"
  94. Plugin *pluginInstance;
  95. void init(Plugin *p) {
  96. pluginInstance = p;
  97. // Any other plugin initialization may go here.
  98. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  99. }
  100. """
  101. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  102. f.write(plugin_cpp)
  103. git_ignore = """/build
  104. /dist
  105. /plugin.so
  106. /plugin.dylib
  107. /plugin.dll
  108. .DS_Store
  109. """
  110. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  111. f.write(git_ignore)
  112. print(f"Created template plugin in {plugin_dir}")
  113. os.system(f"cd {plugin_dir} && git init")
  114. print(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  115. def create_manifest(plugin_dir, slug=None):
  116. manifest = {}
  117. # Query manifest information
  118. if not slug:
  119. slug = input_default("Plugin slug (unique identifier)")
  120. manifest['slug'] = slug
  121. manifest['name'] = input_default("Plugin name", slug)
  122. manifest['version'] = input_default("Version", "1.0.0")
  123. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", "proprietary")
  124. manifest['author'] = input_default("Author")
  125. manifest['authorEmail'] = input_default("Author email (optional)")
  126. manifest['authorUrl'] = input_default("Author website URL (optional)")
  127. manifest['pluginUrl'] = input_default("Plugin website URL (optional)")
  128. manifest['manualUrl'] = input_default("Manual website URL (optional)")
  129. manifest['sourceUrl'] = input_default("Source code URL (optional)")
  130. manifest['donateUrl'] = input_default("Donate URL (optional)")
  131. manifest['modules'] = []
  132. # Dump JSON
  133. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  134. with open(manifest_filename, "w") as f:
  135. json.dump(manifest, f, indent="\t")
  136. print(f"Manifest created at {manifest_filename}")
  137. def usage_create_module(script):
  138. text = f"""Usage: {script} createmodule <module slug>
  139. Must be called in a plugin directory.
  140. A panel file must exist in res/<module slug>.svg.
  141. A source file will be created at src/<module slug>.cpp.
  142. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  143. """
  144. print(text)
  145. def create_module(slug):
  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. manifest = None
  152. with open(manifest_filename, "r") as f:
  153. manifest = json.load(f)
  154. # Check if module manifest exists
  155. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  156. if not module_manifest:
  157. # Add module to manifest
  158. module_manifest = {}
  159. module_manifest['slug'] = slug
  160. module_manifest['name'] = input_default("Module name", slug)
  161. module_manifest['description'] = input_default("One-line description (optional)")
  162. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/plugin.cpp#L543 for list)")
  163. tags = tags.split(",")
  164. tags = [tag.strip() for tag in tags]
  165. if len(tags) == 1 and tags[0] == "":
  166. tags = []
  167. module_manifest['tags'] = tags
  168. manifest['modules'].append(module_manifest)
  169. # Write manifest
  170. with open(manifest_filename, "w") as f:
  171. json.dump(manifest, f, indent="\t")
  172. print(f"Added {slug} to plugin.json")
  173. else:
  174. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  175. # Check filenames
  176. panel_filename = f"res/{slug}.svg"
  177. source_filename = f"src/{slug}.cpp"
  178. if not os.path.exists(panel_filename):
  179. 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.")
  180. return
  181. print(f"Panel found at {panel_filename}. Generating source file.")
  182. if os.path.exists(source_filename):
  183. if input_default(f"{source_filename} already exists. Overwrite?", "n").lower() != "y":
  184. return
  185. # Read SVG XML
  186. tree = xml.etree.ElementTree.parse(panel_filename)
  187. components = panel_to_components(tree)
  188. print(f"Components extracted from {panel_filename}")
  189. # Write source
  190. source = components_to_source(components, slug)
  191. with open(source_filename, "w") as f:
  192. f.write(source)
  193. print(f"Source file generated at {source_filename}")
  194. # Append model to plugin.hpp
  195. identifier = slug_to_identifier(slug)
  196. # Tell user to add model to plugin.hpp and plugin.cpp
  197. print(f"")
  198. print(f"To enable the module, add")
  199. print(f"extern Model *model{identifier};")
  200. print(f"to plugin.hpp, and add")
  201. print(f"p->addModel(model{identifier});")
  202. print(f"to the init() function in plugin.cpp.")
  203. def panel_to_components(tree):
  204. ns = {
  205. "svg": "http://www.w3.org/2000/svg",
  206. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  207. }
  208. # Get components layer
  209. root = tree.getroot()
  210. groups = root.findall(".//svg:g[@inkscape:label='components']", ns)
  211. if len(groups) < 1:
  212. raise UserException("Could not find \"components\" layer on panel")
  213. # Get circles and rects
  214. components_group = groups[0]
  215. circles = components_group.findall(".//svg:circle", ns)
  216. rects = components_group.findall(".//svg:rect", ns)
  217. components = {}
  218. components['params'] = []
  219. components['inputs'] = []
  220. components['outputs'] = []
  221. components['lights'] = []
  222. components['widgets'] = []
  223. for el in circles + rects:
  224. c = {}
  225. # Get name
  226. name = el.get('inkscape:label')
  227. if name is None:
  228. name = el.get('id')
  229. name = slug_to_identifier(name).upper()
  230. c['name'] = name
  231. # Get color
  232. style = el.get('style')
  233. color_match = re.search(r'fill:\S*#(.{6});', style)
  234. color = color_match.group(1)
  235. c['color'] = color
  236. # Get position
  237. if el.tag == "{http://www.w3.org/2000/svg}rect":
  238. x = float(el.get('x'))
  239. y = float(el.get('y'))
  240. width = float(el.get('width'))
  241. height = float(el.get('height'))
  242. c['x'] = round(x, 3)
  243. c['y'] = round(y, 3)
  244. c['width'] = round(width, 3)
  245. c['height'] = round(height, 3)
  246. c['cx'] = round(x + width / 2, 3)
  247. c['cy'] = round(y + height / 2, 3)
  248. elif el.tag == "{http://www.w3.org/2000/svg}circle":
  249. cx = float(el.get('cx'))
  250. cy = float(el.get('cy'))
  251. c['cx'] = round(cx, 3)
  252. c['cy'] = round(cy, 3)
  253. if color == 'ff0000':
  254. components['params'].append(c)
  255. if color == '00ff00':
  256. components['inputs'].append(c)
  257. if color == '0000ff':
  258. components['outputs'].append(c)
  259. if color == 'ff00ff':
  260. components['lights'].append(c)
  261. if color == 'ffff00':
  262. components['widgets'].append(c)
  263. # Sort components
  264. top_left_sort = lambda w: (w['cy'], w['cx'])
  265. components['params'] = sorted(components['params'], key=top_left_sort)
  266. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  267. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  268. components['lights'] = sorted(components['lights'], key=top_left_sort)
  269. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  270. 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.")
  271. return components
  272. def components_to_source(components, slug):
  273. identifier = slug_to_identifier(slug)
  274. source = ""
  275. source += f"""#include "plugin.hpp"
  276. struct {identifier} : Module {{"""
  277. # Params
  278. source += """
  279. enum ParamIds {"""
  280. for c in components['params']:
  281. source += f"""
  282. {c['name']}_PARAM,"""
  283. source += """
  284. NUM_PARAMS
  285. };"""
  286. # Inputs
  287. source += """
  288. enum InputIds {"""
  289. for c in components['inputs']:
  290. source += f"""
  291. {c['name']}_INPUT,"""
  292. source += """
  293. NUM_INPUTS
  294. };"""
  295. # Outputs
  296. source += """
  297. enum OutputIds {"""
  298. for c in components['outputs']:
  299. source += f"""
  300. {c['name']}_OUTPUT,"""
  301. source += """
  302. NUM_OUTPUTS
  303. };"""
  304. # Lights
  305. source += """
  306. enum LightIds {"""
  307. for c in components['lights']:
  308. source += f"""
  309. {c['name']}_LIGHT,"""
  310. source += """
  311. NUM_LIGHTS
  312. };"""
  313. source += f"""
  314. {identifier}() {{
  315. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  316. for c in components['params']:
  317. source += f"""
  318. params[{c['name']}_PARAM].config(0.f, 1.f, 0.f, "");"""
  319. source += """
  320. }
  321. void process(const ProcessArgs &args) override {
  322. }
  323. };"""
  324. source += f"""
  325. struct {identifier}Widget : ModuleWidget {{
  326. {identifier}Widget({identifier} *module) {{
  327. setModule(module);
  328. setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/{slug}.svg")));
  329. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  330. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  331. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  332. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  333. # Params
  334. if len(components['params']) > 0:
  335. source += "\n"
  336. for c in components['params']:
  337. if 'x' in c:
  338. source += f"""
  339. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  340. else:
  341. source += f"""
  342. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  343. # Inputs
  344. if len(components['inputs']) > 0:
  345. source += "\n"
  346. for c in components['inputs']:
  347. if 'x' in c:
  348. source += f"""
  349. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  350. else:
  351. source += f"""
  352. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  353. # Outputs
  354. if len(components['outputs']) > 0:
  355. source += "\n"
  356. for c in components['outputs']:
  357. if 'x' in c:
  358. source += f"""
  359. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  360. else:
  361. source += f"""
  362. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  363. # Lights
  364. if len(components['lights']) > 0:
  365. source += "\n"
  366. for c in components['lights']:
  367. if 'x' in c:
  368. source += f"""
  369. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  370. else:
  371. source += f"""
  372. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  373. # Widgets
  374. if len(components['widgets']) > 0:
  375. source += "\n"
  376. for c in components['widgets']:
  377. if 'x' in c:
  378. source += f"""
  379. // mm2px(Vec({c['width']}, {c['height']}))
  380. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  381. else:
  382. source += f"""
  383. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  384. source += f"""
  385. }}
  386. }};
  387. Model *model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  388. return source
  389. def parse_args(args):
  390. if len(args) >= 2:
  391. if args[1] == 'createplugin':
  392. if len(args) >= 3:
  393. create_plugin(args[2])
  394. return
  395. usage_create_plugin(args[0])
  396. return
  397. if args[1] == 'createmodule':
  398. if len(args) >= 3:
  399. create_module(args[2])
  400. return
  401. usage_create_module(args[0])
  402. return
  403. if args[1] == 'createmanifest':
  404. create_manifest('.')
  405. return
  406. usage(args[0])
  407. if __name__ == "__main__":
  408. try:
  409. parse_args(sys.argv)
  410. except KeyboardInterrupt:
  411. pass
  412. except UserException as e:
  413. print(e)
  414. sys.exit(1)