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.

498 lines
13KB

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