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.

610 lines
17KB

  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 eprint(*args, **kwargs):
  12. print(*args, file=sys.stderr, **kwargs)
  13. def find(f, array):
  14. for a in array:
  15. if f(a):
  16. return f
  17. def input_default(prompt, default=""):
  18. str = input(f"{prompt} [{default}]: ")
  19. if str == "":
  20. return default
  21. return str
  22. def is_valid_slug(slug):
  23. return re.match(r'^[a-zA-Z0-9_\-]+$', slug) != None
  24. def str_to_identifier(s):
  25. if not s:
  26. return "_"
  27. # Identifiers can't start with a number
  28. if s[0].isdigit():
  29. s = "_" + s
  30. # Capitalize first letter
  31. s = s[0].upper() + s[1:]
  32. # Replace special characters with underscore
  33. s = re.sub(r'\W', '_', s)
  34. return s
  35. def create_plugin(slug, plugin_dir=None):
  36. # Check slug
  37. if not is_valid_slug(slug):
  38. raise UserException("Slug must only contain ASCII letters, numbers, '-', and '_'.")
  39. if not plugin_dir:
  40. plugin_dir = os.path.join(slug, '')
  41. # Check if plugin directory exists
  42. if os.path.exists(plugin_dir):
  43. raise UserException(f"Directory {plugin_dir} already exists")
  44. # Create plugin directory
  45. os.mkdir(plugin_dir)
  46. # Create manifest
  47. try:
  48. create_manifest(slug, plugin_dir)
  49. except Exception as e:
  50. os.rmdir(plugin_dir)
  51. raise e
  52. # Create subdirectories
  53. os.mkdir(os.path.join(plugin_dir, "src"))
  54. os.mkdir(os.path.join(plugin_dir, "res"))
  55. # Create Makefile
  56. makefile = """# If RACK_DIR is not defined when calling the Makefile, default to two directories above
  57. RACK_DIR ?= ../..
  58. # FLAGS will be passed to both the C and C++ compiler
  59. FLAGS +=
  60. CFLAGS +=
  61. CXXFLAGS +=
  62. # Careful about linking to shared libraries, since you can't assume much about the user's environment and library search path.
  63. # Static libraries are fine, but they should be added to this plugin's build system.
  64. LDFLAGS +=
  65. # Add .cpp files to the build
  66. SOURCES += $(wildcard src/*.cpp)
  67. # Add files to the ZIP package when running `make dist`
  68. # The compiled plugin and "plugin.json" are automatically added.
  69. DISTRIBUTABLES += res
  70. DISTRIBUTABLES += $(wildcard LICENSE*)
  71. DISTRIBUTABLES += $(wildcard presets)
  72. # Include the Rack plugin Makefile framework
  73. include $(RACK_DIR)/plugin.mk
  74. """
  75. with open(os.path.join(plugin_dir, "Makefile"), "w") as f:
  76. f.write(makefile)
  77. # Create plugin.hpp
  78. plugin_hpp = """#pragma once
  79. #include <rack.hpp>
  80. using namespace rack;
  81. // Declare the Plugin, defined in plugin.cpp
  82. extern Plugin* pluginInstance;
  83. // Declare each Model, defined in each module source file
  84. // extern Model* modelMyModule;
  85. """
  86. with open(os.path.join(plugin_dir, "src/plugin.hpp"), "w") as f:
  87. f.write(plugin_hpp)
  88. # Create plugin.cpp
  89. plugin_cpp = """#include "plugin.hpp"
  90. Plugin* pluginInstance;
  91. void init(Plugin* p) {
  92. pluginInstance = p;
  93. // Add modules here
  94. // p->addModel(modelMyModule);
  95. // Any other plugin initialization may go here.
  96. // As an alternative, consider lazy-loading assets and lookup tables when your module is created to reduce startup times of Rack.
  97. }
  98. """
  99. with open(os.path.join(plugin_dir, "src/plugin.cpp"), "w") as f:
  100. f.write(plugin_cpp)
  101. git_ignore = """/build
  102. /dist
  103. /*.so
  104. /*.dylib
  105. /*.dll
  106. .DS_Store
  107. """
  108. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  109. f.write(git_ignore)
  110. eprint(f"Created template plugin in {plugin_dir}")
  111. os.system(f"cd {plugin_dir} && git init")
  112. eprint(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  113. def create_manifest(slug, plugin_dir="."):
  114. # Default manifest
  115. manifest = {
  116. 'slug': slug,
  117. }
  118. # Try to load existing manifest file
  119. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  120. try:
  121. with open(manifest_filename, "r") as f:
  122. manifest = json.load(f)
  123. except:
  124. pass
  125. # Query manifest information
  126. manifest['name'] = input_default("Plugin name", manifest.get('name', slug))
  127. manifest['version'] = input_default("Version", manifest.get('version', "2.0.0"))
  128. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", manifest.get('license', "proprietary"))
  129. manifest['brand'] = input_default("Brand (prefix for all module names)", manifest.get('brand', manifest['name']))
  130. manifest['author'] = input_default("Author", manifest.get('author', ""))
  131. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  132. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  133. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  134. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  135. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  136. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  137. manifest['changelogUrl'] = manifest.get('changelogUrl', "")
  138. if 'modules' not in manifest:
  139. manifest['modules'] = []
  140. # Dump JSON
  141. with open(manifest_filename, "w") as f:
  142. json.dump(manifest, f, indent=" ")
  143. eprint("")
  144. eprint(f"Manifest written to {manifest_filename}")
  145. def create_module(slug, panel_filename=None, source_filename=None):
  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. 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 module_manifest:
  156. eprint(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  157. else:
  158. # Add module to manifest
  159. module_manifest = {}
  160. module_manifest['slug'] = slug
  161. module_manifest['name'] = input_default("Module name", slug)
  162. module_manifest['description'] = input_default("One-line description (optional)")
  163. tags = input_default("Tags (comma-separated, case-insensitive, see https://vcvrack.com/manual/Manifest#modules-tags for list)")
  164. tags = tags.split(",")
  165. tags = [tag.strip() for tag in tags]
  166. if len(tags) == 1 and tags[0] == "":
  167. tags = []
  168. module_manifest['tags'] = tags
  169. manifest['modules'].append(module_manifest)
  170. # Write manifest
  171. with open(manifest_filename, "w") as f:
  172. json.dump(manifest, f, indent=" ")
  173. eprint(f"Added {slug} to {manifest_filename}")
  174. # Check filenames
  175. if panel_filename:
  176. if not os.path.exists(panel_filename):
  177. raise UserException(f"Panel not found at {panel_filename}.")
  178. if source_filename and os.path.exists(source_filename):
  179. if input_default(f"{source_filename} already exists. Overwrite? (y/n)", "n").lower() != "y":
  180. return
  181. # Read SVG XML
  182. try:
  183. tree = xml.etree.ElementTree.parse(panel_filename)
  184. except:
  185. raise UserException("Invalid SVG")
  186. components = panel_to_components(tree)
  187. # Tell user to add model to plugin.hpp and plugin.cpp
  188. identifier = str_to_identifier(slug)
  189. eprint(f"""
  190. To enable the module, add
  191. extern Model* model{identifier};
  192. to plugin.hpp, and add
  193. p->addModel(model{identifier});
  194. to the init() function in plugin.cpp.""")
  195. # Write source
  196. source = components_to_source(components, slug)
  197. if source_filename:
  198. with open(source_filename, "w") as f:
  199. f.write(source)
  200. eprint(f"Source file generated at {source_filename}")
  201. else:
  202. print(source)
  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. root = tree.getroot()
  209. # Get page size
  210. re_unit = re.compile(r'(-?\d*\.?\d*)\s*([a-zA-Z]*)')
  211. root_width_match = re_unit.match(root.get('width'))
  212. root_height_match = re_unit.match(root.get('height'))
  213. root_width = float(root_width_match[1])
  214. root_height = float(root_height_match[1])
  215. # Since we emit mm2px() below, convert pixels to mm
  216. if root_width_match[2] == 'mm' and root_height_match[2] == 'mm':
  217. root_scale = 1
  218. else:
  219. svg_dpi = 75
  220. mm_per_in = 25.4
  221. root_scale = mm_per_in / svg_dpi
  222. root_width *= root_scale
  223. root_height *= root_scale
  224. # Get view box
  225. view = root.get('viewBox', f"0 0 {root_width} {root_height}")
  226. view_ary = view.split(' ')
  227. view_x = float(view_ary[0])
  228. view_y = float(view_ary[1])
  229. view_width = float(view_ary[2])
  230. view_height = float(view_ary[3])
  231. # Get components layer
  232. group = root.find(".//svg:g[@inkscape:label='components']", ns)
  233. # Illustrator uses `data-name` (in Unique object ID mode) or `id` (in Layer Names object ID mode) for the group name.
  234. # Don't test with `not group` since Elements with no subelements are falsy.
  235. if group is None:
  236. group = root.find(".//svg:g[@data-name='components']", ns)
  237. if group is None:
  238. group = root.find(".//svg:g[@id='components']", ns)
  239. if group is None:
  240. raise UserException("Could not find \"components\" layer on panel")
  241. components = {}
  242. components['params'] = []
  243. components['inputs'] = []
  244. components['outputs'] = []
  245. components['lights'] = []
  246. components['widgets'] = []
  247. for el in group:
  248. c = {}
  249. # Get name
  250. name = el.get('{' + ns['inkscape'] + '}label')
  251. # Illustrator names
  252. if not name:
  253. name = el.get('data-name')
  254. if not name:
  255. name = el.get('id')
  256. if not name:
  257. name = ""
  258. # Split name and component class name
  259. names = name.split('#', 1)
  260. name = names[0]
  261. if len(names) >= 2:
  262. c['cls'] = names[1]
  263. name = str_to_identifier(name).upper()
  264. c['name'] = name
  265. # Get position
  266. if el.tag == '{' + ns['svg'] + '}rect':
  267. x = (float(el.get('x')) - view_x) / view_width * root_width
  268. y = (float(el.get('y')) - view_y) / view_height * root_height
  269. width = (float(el.get('width')) - view_x) / view_width * root_width
  270. height = (float(el.get('height')) - view_y) / view_height * root_height
  271. c['x'] = round(x, 3)
  272. c['y'] = round(y, 3)
  273. c['width'] = round(width, 3)
  274. c['height'] = round(height, 3)
  275. c['cx'] = round(x + width / 2, 3)
  276. c['cy'] = round(y + height / 2, 3)
  277. elif el.tag == '{' + ns['svg'] + '}circle' or el.tag == '{' + ns['svg'] + '}ellipse':
  278. cx = (float(el.get('cx')) - view_x) / view_width * root_width
  279. cy = (float(el.get('cy')) - view_y) / view_height * root_height
  280. c['cx'] = round(cx, 3)
  281. c['cy'] = round(cy, 3)
  282. else:
  283. eprint(f"Element in components layer is not rect, circle, or ellipse: {el}")
  284. continue
  285. # Get color
  286. color = None
  287. # Get color from fill attribute
  288. fill = el.get('fill')
  289. if fill:
  290. color = fill
  291. # Get color from CSS fill style
  292. if not color:
  293. style = el.get('style')
  294. if style:
  295. color_match = re.search(r'fill:\S*(#[0-9a-fA-F]{6})', style)
  296. color = color_match.group(1)
  297. if not color:
  298. eprint(f"Cannot get color of component: {el}")
  299. continue
  300. color = color.lower()
  301. if color == '#ff0000' or color == '#f00' or color == 'red':
  302. components['params'].append(c)
  303. if color == '#00ff00' or color == '#0f0' or color == 'lime':
  304. components['inputs'].append(c)
  305. if color == '#0000ff' or color == '#00f' or color == 'blue':
  306. components['outputs'].append(c)
  307. if color == '#ff00ff' or color == '#f0f' or color == 'magenta':
  308. components['lights'].append(c)
  309. if color == '#ffff00' or color == '#ff0' or color == 'yellow':
  310. components['widgets'].append(c)
  311. # Sort components
  312. top_left_sort = lambda w: w['cy'] + 0.01 * w['cx']
  313. components['params'] = sorted(components['params'], key=top_left_sort)
  314. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  315. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  316. components['lights'] = sorted(components['lights'], key=top_left_sort)
  317. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  318. eprint(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.")
  319. return components
  320. def components_to_source(components, slug):
  321. identifier = str_to_identifier(slug)
  322. source = ""
  323. source += f"""#include "plugin.hpp"
  324. struct {identifier} : Module {{"""
  325. # Params
  326. source += """
  327. enum ParamId {"""
  328. for c in components['params']:
  329. source += f"""
  330. {c['name']}_PARAM,"""
  331. source += """
  332. PARAMS_LEN
  333. };"""
  334. # Inputs
  335. source += """
  336. enum InputId {"""
  337. for c in components['inputs']:
  338. source += f"""
  339. {c['name']}_INPUT,"""
  340. source += """
  341. INPUTS_LEN
  342. };"""
  343. # Outputs
  344. source += """
  345. enum OutputId {"""
  346. for c in components['outputs']:
  347. source += f"""
  348. {c['name']}_OUTPUT,"""
  349. source += """
  350. OUTPUTS_LEN
  351. };"""
  352. # Lights
  353. source += """
  354. enum LightId {"""
  355. for c in components['lights']:
  356. source += f"""
  357. {c['name']}_LIGHT,"""
  358. source += """
  359. LIGHTS_LEN
  360. };"""
  361. source += f"""
  362. {identifier}() {{
  363. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  364. for c in components['params']:
  365. source += f"""
  366. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  367. for c in components['inputs']:
  368. source += f"""
  369. configInput({c['name']}_INPUT, "");"""
  370. for c in components['outputs']:
  371. source += f"""
  372. configOutput({c['name']}_OUTPUT, "");"""
  373. source += """
  374. }
  375. void process(const ProcessArgs& args) override {
  376. }
  377. };"""
  378. source += f"""
  379. struct {identifier}Widget : ModuleWidget {{
  380. {identifier}Widget({identifier}* module) {{
  381. setModule(module);
  382. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  383. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  384. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  385. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  386. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  387. # Params
  388. if len(components['params']) > 0:
  389. source += "\n"
  390. for c in components['params']:
  391. if 'x' in c:
  392. source += f"""
  393. addParam(createParam<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  394. else:
  395. source += f"""
  396. addParam(createParamCentered<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  397. # Inputs
  398. if len(components['inputs']) > 0:
  399. source += "\n"
  400. for c in components['inputs']:
  401. if 'x' in c:
  402. source += f"""
  403. addInput(createInput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  404. else:
  405. source += f"""
  406. addInput(createInputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  407. # Outputs
  408. if len(components['outputs']) > 0:
  409. source += "\n"
  410. for c in components['outputs']:
  411. if 'x' in c:
  412. source += f"""
  413. addOutput(createOutput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  414. else:
  415. source += f"""
  416. addOutput(createOutputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  417. # Lights
  418. if len(components['lights']) > 0:
  419. source += "\n"
  420. for c in components['lights']:
  421. if 'x' in c:
  422. source += f"""
  423. addChild(createLight<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  424. else:
  425. source += f"""
  426. addChild(createLightCentered<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  427. # Widgets
  428. if len(components['widgets']) > 0:
  429. source += "\n"
  430. for c in components['widgets']:
  431. if 'x' in c:
  432. source += f"""
  433. // mm2px(Vec({c['width']}, {c['height']}))
  434. addChild(createWidget<{c.get('cls', 'Widget')}>(mm2px(Vec({c['x']}, {c['y']}))));"""
  435. else:
  436. source += f"""
  437. addChild(createWidgetCentered<{c.get('cls', 'Widget')}>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  438. source += f"""
  439. }}
  440. }};
  441. Model* model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  442. return source
  443. def usage(script):
  444. text = f"""VCV Rack Plugin Development Helper
  445. Usage: {script} <command> ...
  446. Commands:
  447. createplugin <slug> [plugin dir]
  448. A directory will be created and initialized with a minimal plugin template.
  449. If no plugin directory is given, the slug is used.
  450. createmanifest <slug> [plugin dir]
  451. Creates a `plugin.json` manifest file in an existing plugin directory.
  452. If no plugin directory is given, the current directory is used.
  453. createmodule <module slug> [panel file] [source file]
  454. Adds a new module to the plugin manifest in the current directory.
  455. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  456. Example:
  457. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  458. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  459. """
  460. eprint(text)
  461. def parse_args(args):
  462. script = args.pop(0)
  463. if len(args) == 0:
  464. usage(script)
  465. return
  466. cmd = args.pop(0)
  467. if cmd == 'createplugin':
  468. create_plugin(*args)
  469. elif cmd == 'createmodule':
  470. create_module(*args)
  471. elif cmd == 'createmanifest':
  472. create_manifest(*args)
  473. else:
  474. eprint(f"Command not found: {cmd}")
  475. if __name__ == "__main__":
  476. try:
  477. parse_args(sys.argv)
  478. except KeyboardInterrupt:
  479. pass
  480. except UserException as e:
  481. eprint(e)
  482. sys.exit(1)