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.

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