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.

535 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)", slug)
  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. Instructions for creating a panel:
  143. - Only Inkscape is supported by this script and Rack's SVG renderer.
  144. - Create a document with units in "mm", height of 128.5 mm, and width of a multiple of 5.08 mm (1 HP in Eurorack).
  145. - Design the panel.
  146. - Create a layer named "widgets".
  147. - For each component, create a shape on the widgets layer.
  148. - Use a circle to place a component by its center.
  149. The size of the circle does not matter, only the center point.
  150. A `create*Centered()` call is generated in C++.
  151. - Use a rectangle to to place a component by its top-left point.
  152. This should only be used when the shape's size is equal to the component's size in C++.
  153. A `create*()` call is generated in C++.
  154. - Set the color of each shape depending on the component's type.
  155. - Param: red #ff0000
  156. - Input: green #00ff00
  157. - Output: blue #0000ff
  158. - Light: magenta #ff00ff
  159. - Custom widgets: yellow #ffff00
  160. - Hide the widgets layer and save to res/<module slug>.svg.
  161. """
  162. print(text)
  163. def create_module(slug):
  164. # Check slug
  165. if not is_valid_slug(slug):
  166. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  167. # Read manifest
  168. manifest_filename = 'plugin.json'
  169. manifest = None
  170. with open(manifest_filename, "r") as f:
  171. manifest = json.load(f)
  172. # Check if module manifest exists
  173. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  174. if not module_manifest:
  175. # Add module to manifest
  176. module_manifest = {}
  177. module_manifest['slug'] = slug
  178. module_manifest['name'] = input_default("Module name", slug)
  179. module_manifest['description'] = input_default("One-line description (optional)")
  180. tags = input_default("Tags (comma-separated, case-insensitive, see https://github.com/VCVRack/Rack/blob/v1/src/plugin.cpp#L543 for list)")
  181. tags = tags.split(",")
  182. tags = [tag.strip() for tag in tags]
  183. if len(tags) == 1 and tags[0] == "":
  184. tags = []
  185. module_manifest['tags'] = tags
  186. manifest['modules'].append(module_manifest)
  187. # Write manifest
  188. with open(manifest_filename, "w") as f:
  189. json.dump(manifest, f, indent="\t")
  190. print(f"Added {slug} to plugin.json")
  191. else:
  192. print(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  193. # Check filenames
  194. panel_filename = f"res/{slug}.svg"
  195. source_filename = f"src/{slug}.cpp"
  196. if not os.path.exists(panel_filename):
  197. 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.")
  198. return
  199. print(f"Panel found at {panel_filename}. Generating source file.")
  200. if os.path.exists(source_filename):
  201. if input_default(f"{source_filename} already exists. Overwrite?", "n").lower() != "y":
  202. return
  203. # Read SVG XML
  204. tree = xml.etree.ElementTree.parse(panel_filename)
  205. components = panel_to_components(tree)
  206. print(f"Components extracted from {panel_filename}")
  207. # Write source
  208. source = components_to_source(components, slug)
  209. with open(source_filename, "w") as f:
  210. f.write(source)
  211. print(f"Source file generated at {source_filename}")
  212. # Append model to plugin.hpp
  213. identifier = slug_to_identifier(slug)
  214. # Tell user to add model to plugin.hpp and plugin.cpp
  215. print(f"")
  216. print(f"To enable the module, add")
  217. print(f"extern Model *model{identifier};")
  218. print(f"to plugin.hpp, and add")
  219. print(f"p->addModel(model{identifier});")
  220. print(f"to the init() function in plugin.cpp.")
  221. def panel_to_components(tree):
  222. ns = {
  223. "svg": "http://www.w3.org/2000/svg",
  224. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  225. }
  226. # Get widgets layer
  227. root = tree.getroot()
  228. groups = root.findall(".//svg:g[@inkscape:label='widgets']", ns)
  229. if len(groups) < 1:
  230. raise UserException("Could not find \"widgets\" layer on panel")
  231. # Get circles and rects
  232. widgets_group = groups[0]
  233. circles = widgets_group.findall(".//svg:circle", ns)
  234. rects = widgets_group.findall(".//svg:rect", ns)
  235. components = {}
  236. components['params'] = []
  237. components['inputs'] = []
  238. components['outputs'] = []
  239. components['lights'] = []
  240. components['widgets'] = []
  241. for el in circles + rects:
  242. c = {}
  243. # Get name
  244. name = el.get('inkscape:label')
  245. if name is None:
  246. name = el.get('id')
  247. name = slug_to_identifier(name).upper()
  248. c['name'] = name
  249. # Get color
  250. style = el.get('style')
  251. color_match = re.search(r'fill:\S*#(.{6});', style)
  252. color = color_match.group(1)
  253. c['color'] = color
  254. # Get position
  255. if el.tag == "{http://www.w3.org/2000/svg}rect":
  256. x = float(el.get('x'))
  257. y = float(el.get('y'))
  258. width = float(el.get('width'))
  259. height = float(el.get('height'))
  260. c['x'] = round(x, 3)
  261. c['y'] = round(y, 3)
  262. c['width'] = round(width, 3)
  263. c['height'] = round(height, 3)
  264. elif el.tag == "{http://www.w3.org/2000/svg}circle":
  265. cx = float(el.get('cx'))
  266. cy = float(el.get('cy'))
  267. c['cx'] = round(cx, 3)
  268. c['cy'] = round(cy, 3)
  269. if color == 'ff0000':
  270. components['params'].append(c)
  271. if color == '00ff00':
  272. components['inputs'].append(c)
  273. if color == '0000ff':
  274. components['outputs'].append(c)
  275. if color == 'ff00ff':
  276. components['lights'].append(c)
  277. if color == 'ffff00':
  278. components['widgets'].append(c)
  279. 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.")
  280. return components
  281. def components_to_source(components, slug):
  282. identifier = slug_to_identifier(slug)
  283. source = ""
  284. source += f"""#include "plugin.hpp"
  285. struct {identifier} : Module {{"""
  286. # Params
  287. source += """
  288. enum ParamIds {"""
  289. for c in components['params']:
  290. source += f"""
  291. {c['name']}_PARAM,"""
  292. source += """
  293. NUM_PARAMS
  294. };"""
  295. # Inputs
  296. source += """
  297. enum InputIds {"""
  298. for c in components['inputs']:
  299. source += f"""
  300. {c['name']}_INPUT,"""
  301. source += """
  302. NUM_INPUTS
  303. };"""
  304. # Outputs
  305. source += """
  306. enum OutputIds {"""
  307. for c in components['outputs']:
  308. source += f"""
  309. {c['name']}_OUTPUT,"""
  310. source += """
  311. NUM_OUTPUTS
  312. };"""
  313. # Lights
  314. source += """
  315. enum LightIds {"""
  316. for c in components['lights']:
  317. source += f"""
  318. {c['name']}_LIGHT,"""
  319. source += """
  320. NUM_LIGHTS
  321. };"""
  322. source += f"""
  323. {identifier}() {{
  324. config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);"""
  325. for c in components['params']:
  326. source += f"""
  327. params[{c['name']}_PARAM].config(0.f, 1.f, 0.f, "");"""
  328. source += """
  329. }
  330. void process(const ProcessArgs &args) override {
  331. }
  332. };"""
  333. source += f"""
  334. struct {identifier}Widget : ModuleWidget {{
  335. {identifier}Widget({identifier} *module) {{
  336. setModule(module);
  337. setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/{slug}.svg")));
  338. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  339. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  340. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  341. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  342. # Params
  343. if len(components['params']) > 0:
  344. source += "\n"
  345. for c in components['params']:
  346. if 'cx' in c:
  347. source += f"""
  348. addParam(createParamCentered<RoundBlackKnob>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  349. else:
  350. source += f"""
  351. addParam(createParam<RoundBlackKnob>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  352. # Inputs
  353. if len(components['inputs']) > 0:
  354. source += "\n"
  355. for c in components['inputs']:
  356. if 'cx' in c:
  357. source += f"""
  358. addInput(createInputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  359. else:
  360. source += f"""
  361. addInput(createInput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  362. # Outputs
  363. if len(components['outputs']) > 0:
  364. source += "\n"
  365. for c in components['outputs']:
  366. if 'cx' in c:
  367. source += f"""
  368. addOutput(createOutputCentered<PJ301MPort>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  369. else:
  370. source += f"""
  371. addOutput(createOutput<PJ301MPort>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  372. # Lights
  373. if len(components['lights']) > 0:
  374. source += "\n"
  375. for c in components['lights']:
  376. if 'cx' in c:
  377. source += f"""
  378. addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  379. else:
  380. source += f"""
  381. addChild(createLight<MediumLight<RedLight>>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  382. # Widgets
  383. if len(components['widgets']) > 0:
  384. source += "\n"
  385. for c in components['widgets']:
  386. if 'cx' in c:
  387. source += f"""
  388. addChild(createWidgetCentered<Widget>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  389. else:
  390. source += f"""
  391. // mm2px(Vec({c['width']}, {c['height']}))
  392. addChild(createWidget<Widget>(mm2px(Vec({c['x']}, {c['y']}))));"""
  393. source += f"""
  394. }}
  395. }};
  396. Model *model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  397. return source
  398. def parse_args(args):
  399. if len(args) >= 2:
  400. if args[1] == 'createplugin':
  401. if len(args) >= 3:
  402. create_plugin(args[2])
  403. return
  404. usage_create_plugin(args[0])
  405. return
  406. if args[1] == 'createmodule':
  407. if len(args) >= 3:
  408. create_module(args[2])
  409. return
  410. usage_create_module(args[0])
  411. return
  412. if args[1] == 'createmanifest':
  413. create_manifest('.')
  414. return
  415. usage(args[0])
  416. if __name__ == "__main__":
  417. try:
  418. parse_args(sys.argv)
  419. except KeyboardInterrupt:
  420. pass
  421. except UserException as e:
  422. print(e)
  423. sys.exit(1)