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.

586 lines
16KB

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