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.

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