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.

616 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 = """# Ignore all dotfiles except git dotfiles
  102. .*
  103. !.git*
  104. # Binaries and build targets
  105. *.a
  106. *.so
  107. *.dylib
  108. *.dll
  109. /build
  110. /dep
  111. /dist
  112. """
  113. with open(os.path.join(plugin_dir, ".gitignore"), "w") as f:
  114. f.write(git_ignore)
  115. eprint(f"Created template plugin in {plugin_dir}")
  116. os.system(f"cd {plugin_dir} && git init")
  117. eprint(f"You may use `make`, `make clean`, `make dist`, `make install`, etc in the {plugin_dir} directory.")
  118. def create_manifest(slug, plugin_dir="."):
  119. # Default manifest
  120. manifest = {
  121. 'slug': slug,
  122. }
  123. # Try to load existing manifest file
  124. manifest_filename = os.path.join(plugin_dir, 'plugin.json')
  125. try:
  126. with open(manifest_filename, "r") as f:
  127. manifest = json.load(f)
  128. except:
  129. pass
  130. # Query manifest information
  131. manifest['name'] = input_default("Plugin name", manifest.get('name', slug))
  132. manifest['version'] = input_default("Version", manifest.get('version', "2.0.0"))
  133. manifest['license'] = input_default("License (if open-source, use license identifier from https://spdx.org/licenses/)", manifest.get('license', "proprietary"))
  134. manifest['brand'] = input_default("Brand (prefix for all module names)", manifest.get('brand', manifest['name']))
  135. manifest['author'] = input_default("Author", manifest.get('author', ""))
  136. manifest['authorEmail'] = input_default("Author email (optional)", manifest.get('authorEmail', ""))
  137. manifest['authorUrl'] = input_default("Author website URL (optional)", manifest.get('authorUrl', ""))
  138. manifest['pluginUrl'] = input_default("Plugin website URL (optional)", manifest.get('pluginUrl', ""))
  139. manifest['manualUrl'] = input_default("Manual website URL (optional)", manifest.get('manualUrl', ""))
  140. manifest['sourceUrl'] = input_default("Source code URL (optional)", manifest.get('sourceUrl', ""))
  141. manifest['donateUrl'] = input_default("Donate URL (optional)", manifest.get('donateUrl', ""))
  142. manifest['changelogUrl'] = manifest.get('changelogUrl', "")
  143. if 'modules' not in manifest:
  144. manifest['modules'] = []
  145. # Dump JSON
  146. with open(manifest_filename, "w") as f:
  147. json.dump(manifest, f, indent=" ")
  148. eprint("")
  149. eprint(f"Manifest written to {manifest_filename}")
  150. def create_module(slug, panel_filename=None, source_filename=None):
  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. with open(manifest_filename, "r") as f:
  157. manifest = json.load(f)
  158. # Check if module manifest exists
  159. module_manifest = find(lambda m: m['slug'] == slug, manifest['modules'])
  160. if module_manifest:
  161. eprint(f"Module {slug} already exists in plugin.json. Edit this file to modify the module manifest.")
  162. else:
  163. # Add module to manifest
  164. module_manifest = {}
  165. module_manifest['slug'] = slug
  166. module_manifest['name'] = input_default("Module name", slug)
  167. module_manifest['description'] = input_default("One-line description (optional)")
  168. tags = input_default("Tags (comma-separated, case-insensitive, see https://vcvrack.com/manual/Manifest#modules-tags for list)")
  169. tags = tags.split(",")
  170. tags = [tag.strip() for tag in tags]
  171. if len(tags) == 1 and tags[0] == "":
  172. tags = []
  173. module_manifest['tags'] = tags
  174. manifest['modules'].append(module_manifest)
  175. # Write manifest
  176. with open(manifest_filename, "w") as f:
  177. json.dump(manifest, f, indent=" ")
  178. eprint(f"Added {slug} to {manifest_filename}")
  179. # Check filenames
  180. if panel_filename:
  181. if not os.path.exists(panel_filename):
  182. raise UserException(f"Panel not found at {panel_filename}.")
  183. if source_filename and os.path.exists(source_filename):
  184. if input_default(f"{source_filename} already exists. Overwrite? (y/n)", "n").lower() != "y":
  185. return
  186. # Read SVG XML
  187. try:
  188. tree = xml.etree.ElementTree.parse(panel_filename)
  189. except:
  190. raise UserException("Invalid SVG")
  191. components = panel_to_components(tree)
  192. # Tell user to add model to plugin.hpp and plugin.cpp
  193. identifier = str_to_identifier(slug)
  194. eprint(f"""
  195. To enable the module, add
  196. extern Model* model{identifier};
  197. to plugin.hpp, and add
  198. p->addModel(model{identifier});
  199. to the init() function in plugin.cpp.""")
  200. # Write source
  201. source = components_to_source(components, slug)
  202. if source_filename:
  203. with open(source_filename, "w") as f:
  204. f.write(source)
  205. eprint(f"Source file generated at {source_filename}")
  206. else:
  207. print(source)
  208. def panel_to_components(tree):
  209. ns = {
  210. "svg": "http://www.w3.org/2000/svg",
  211. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  212. }
  213. root = tree.getroot()
  214. # Get page size
  215. re_unit = re.compile(r'(-?\d*\.?\d*)\s*([a-zA-Z]*)')
  216. root_width_match = re_unit.match(root.get('width'))
  217. root_height_match = re_unit.match(root.get('height'))
  218. root_width = float(root_width_match[1])
  219. root_height = float(root_height_match[1])
  220. # Since we emit mm2px() below, convert pixels to mm
  221. if root_width_match[2] == 'mm' and root_height_match[2] == 'mm':
  222. root_scale = 1
  223. else:
  224. svg_dpi = 75
  225. mm_per_in = 25.4
  226. root_scale = mm_per_in / svg_dpi
  227. root_width *= root_scale
  228. root_height *= root_scale
  229. # Get view box
  230. view = root.get('viewBox', f"0 0 {root_width} {root_height}")
  231. view_ary = view.split(' ')
  232. view_x = float(view_ary[0])
  233. view_y = float(view_ary[1])
  234. view_width = float(view_ary[2])
  235. view_height = float(view_ary[3])
  236. # Get components layer
  237. group = root.find(".//svg:g[@inkscape:label='components']", ns)
  238. # Illustrator uses `data-name` (in Unique object ID mode) or `id` (in Layer Names object ID mode) for the group name.
  239. # Don't test with `not group` since Elements with no subelements are falsy.
  240. if group is None:
  241. group = root.find(".//svg:g[@data-name='components']", ns)
  242. if group is None:
  243. group = root.find(".//svg:g[@id='components']", ns)
  244. if group is None:
  245. raise UserException("Could not find \"components\" layer on panel")
  246. components = {}
  247. components['params'] = []
  248. components['inputs'] = []
  249. components['outputs'] = []
  250. components['lights'] = []
  251. components['widgets'] = []
  252. for el in group:
  253. c = {}
  254. # Get name
  255. name = el.get('{' + ns['inkscape'] + '}label')
  256. # Illustrator names
  257. if not name:
  258. name = el.get('data-name')
  259. if not name:
  260. name = el.get('id')
  261. if not name:
  262. name = ""
  263. # Split name and component class name
  264. names = name.split('#', 1)
  265. name = names[0]
  266. if len(names) >= 2:
  267. c['cls'] = names[1]
  268. name = str_to_identifier(name).upper()
  269. c['name'] = name
  270. # Get position
  271. if el.tag == '{' + ns['svg'] + '}rect':
  272. x = (float(el.get('x')) - view_x) / view_width * root_width
  273. y = (float(el.get('y')) - view_y) / view_height * root_height
  274. width = (float(el.get('width')) - view_x) / view_width * root_width
  275. height = (float(el.get('height')) - view_y) / view_height * root_height
  276. c['x'] = round(x, 3)
  277. c['y'] = round(y, 3)
  278. c['width'] = round(width, 3)
  279. c['height'] = round(height, 3)
  280. c['cx'] = round(x + width / 2, 3)
  281. c['cy'] = round(y + height / 2, 3)
  282. elif el.tag == '{' + ns['svg'] + '}circle' or el.tag == '{' + ns['svg'] + '}ellipse':
  283. cx = (float(el.get('cx')) - view_x) / view_width * root_width
  284. cy = (float(el.get('cy')) - view_y) / view_height * root_height
  285. c['cx'] = round(cx, 3)
  286. c['cy'] = round(cy, 3)
  287. else:
  288. eprint(f"Element in components layer is not rect, circle, or ellipse: {el}")
  289. continue
  290. # Get color
  291. color = None
  292. # Get color from fill attribute
  293. fill = el.get('fill')
  294. if fill:
  295. color = fill
  296. # Get color from CSS fill style
  297. if not color:
  298. style = el.get('style')
  299. if style:
  300. color_match = re.search(r'fill:\S*(#[0-9a-fA-F]{6})', style)
  301. color = color_match.group(1)
  302. if not color:
  303. eprint(f"Cannot get color of component: {el}")
  304. continue
  305. color = color.lower()
  306. if color == '#ff0000' or color == '#f00' or color == 'red':
  307. components['params'].append(c)
  308. if color == '#00ff00' or color == '#0f0' or color == 'lime':
  309. components['inputs'].append(c)
  310. if color == '#0000ff' or color == '#00f' or color == 'blue':
  311. components['outputs'].append(c)
  312. if color == '#ff00ff' or color == '#f0f' or color == 'magenta':
  313. components['lights'].append(c)
  314. if color == '#ffff00' or color == '#ff0' or color == 'yellow':
  315. components['widgets'].append(c)
  316. # Sort components
  317. top_left_sort = lambda w: w['cy'] + 0.01 * w['cx']
  318. components['params'] = sorted(components['params'], key=top_left_sort)
  319. components['inputs'] = sorted(components['inputs'], key=top_left_sort)
  320. components['outputs'] = sorted(components['outputs'], key=top_left_sort)
  321. components['lights'] = sorted(components['lights'], key=top_left_sort)
  322. components['widgets'] = sorted(components['widgets'], key=top_left_sort)
  323. 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.")
  324. return components
  325. def components_to_source(components, slug):
  326. identifier = str_to_identifier(slug)
  327. source = ""
  328. source += f"""#include "plugin.hpp"
  329. struct {identifier} : Module {{"""
  330. # Params
  331. source += """
  332. enum ParamId {"""
  333. for c in components['params']:
  334. source += f"""
  335. {c['name']}_PARAM,"""
  336. source += """
  337. PARAMS_LEN
  338. };"""
  339. # Inputs
  340. source += """
  341. enum InputId {"""
  342. for c in components['inputs']:
  343. source += f"""
  344. {c['name']}_INPUT,"""
  345. source += """
  346. INPUTS_LEN
  347. };"""
  348. # Outputs
  349. source += """
  350. enum OutputId {"""
  351. for c in components['outputs']:
  352. source += f"""
  353. {c['name']}_OUTPUT,"""
  354. source += """
  355. OUTPUTS_LEN
  356. };"""
  357. # Lights
  358. source += """
  359. enum LightId {"""
  360. for c in components['lights']:
  361. source += f"""
  362. {c['name']}_LIGHT,"""
  363. source += """
  364. LIGHTS_LEN
  365. };"""
  366. source += f"""
  367. {identifier}() {{
  368. config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN);"""
  369. for c in components['params']:
  370. source += f"""
  371. configParam({c['name']}_PARAM, 0.f, 1.f, 0.f, "");"""
  372. for c in components['inputs']:
  373. source += f"""
  374. configInput({c['name']}_INPUT, "");"""
  375. for c in components['outputs']:
  376. source += f"""
  377. configOutput({c['name']}_OUTPUT, "");"""
  378. source += """
  379. }
  380. void process(const ProcessArgs& args) override {
  381. }
  382. };"""
  383. source += f"""
  384. struct {identifier}Widget : ModuleWidget {{
  385. {identifier}Widget({identifier}* module) {{
  386. setModule(module);
  387. setPanel(createPanel(asset::plugin(pluginInstance, "res/{slug}.svg")));
  388. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
  389. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
  390. addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
  391. addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));"""
  392. # Params
  393. if len(components['params']) > 0:
  394. source += "\n"
  395. for c in components['params']:
  396. if 'x' in c:
  397. source += f"""
  398. addParam(createParam<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_PARAM));"""
  399. else:
  400. source += f"""
  401. addParam(createParamCentered<{c.get('cls', 'RoundBlackKnob')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_PARAM));"""
  402. # Inputs
  403. if len(components['inputs']) > 0:
  404. source += "\n"
  405. for c in components['inputs']:
  406. if 'x' in c:
  407. source += f"""
  408. addInput(createInput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_INPUT));"""
  409. else:
  410. source += f"""
  411. addInput(createInputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_INPUT));"""
  412. # Outputs
  413. if len(components['outputs']) > 0:
  414. source += "\n"
  415. for c in components['outputs']:
  416. if 'x' in c:
  417. source += f"""
  418. addOutput(createOutput<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_OUTPUT));"""
  419. else:
  420. source += f"""
  421. addOutput(createOutputCentered<{c.get('cls', 'PJ301MPort')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_OUTPUT));"""
  422. # Lights
  423. if len(components['lights']) > 0:
  424. source += "\n"
  425. for c in components['lights']:
  426. if 'x' in c:
  427. source += f"""
  428. addChild(createLight<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['x']}, {c['y']})), module, {identifier}::{c['name']}_LIGHT));"""
  429. else:
  430. source += f"""
  431. addChild(createLightCentered<{c.get('cls', 'MediumLight<RedLight>')}>(mm2px(Vec({c['cx']}, {c['cy']})), module, {identifier}::{c['name']}_LIGHT));"""
  432. # Widgets
  433. if len(components['widgets']) > 0:
  434. source += "\n"
  435. for c in components['widgets']:
  436. if 'x' in c:
  437. source += f"""
  438. // mm2px(Vec({c['width']}, {c['height']}))
  439. addChild(createWidget<{c.get('cls', 'Widget')}>(mm2px(Vec({c['x']}, {c['y']}))));"""
  440. else:
  441. source += f"""
  442. addChild(createWidgetCentered<{c.get('cls', 'Widget')}>(mm2px(Vec({c['cx']}, {c['cy']}))));"""
  443. source += f"""
  444. }}
  445. }};
  446. Model* model{identifier} = createModel<{identifier}, {identifier}Widget>("{slug}");"""
  447. return source
  448. def usage(script):
  449. text = f"""VCV Rack Plugin Development Helper
  450. Usage: {script} <command> ...
  451. Commands:
  452. createplugin <slug> [plugin dir]
  453. A directory will be created and initialized with a minimal plugin template.
  454. If no plugin directory is given, the slug is used.
  455. createmanifest <slug> [plugin dir]
  456. Creates a `plugin.json` manifest file in an existing plugin directory.
  457. If no plugin directory is given, the current directory is used.
  458. createmodule <module slug> [panel file] [source file]
  459. Adds a new module to the plugin manifest in the current directory.
  460. If a panel and source file are given, generates a template source file initialized with components from a panel file.
  461. Example:
  462. {script} createmodule MyModule res/MyModule.svg src/MyModule.cpp
  463. See https://vcvrack.com/manual/PanelTutorial.html for creating SVG panel files.
  464. """
  465. eprint(text)
  466. def parse_args(args):
  467. script = args.pop(0)
  468. if len(args) == 0:
  469. usage(script)
  470. return
  471. cmd = args.pop(0)
  472. if cmd == 'createplugin':
  473. create_plugin(*args)
  474. elif cmd == 'createmodule':
  475. create_module(*args)
  476. elif cmd == 'createmanifest':
  477. create_manifest(*args)
  478. else:
  479. eprint(f"Command not found: {cmd}")
  480. if __name__ == "__main__":
  481. try:
  482. parse_args(sys.argv)
  483. except KeyboardInterrupt:
  484. pass
  485. except UserException as e:
  486. eprint(e)
  487. sys.exit(1)