Home Reference Source

cables_dev/cables_ui/src/ui/components/patchview.js

  1. import { Logger, ele, Events } from "cables-shared-client";
  2. import { Link, Op, Patch, Port, utils } from "cables";
  3. import { BoundingBox, Geometry, Shader } from "cables-corelibs";
  4. import { cloneObject, getShortOpName } from "cables/src/core/utils.js";
  5. import PatchSaveServer from "../api/patchserverapi.js";
  6. import defaultOps from "../defaultops.js";
  7. import ModalDialog from "../dialogs/modaldialog.js";
  8. import { notify, notifyError, notifyWarn } from "../elements/notification.js";
  9. import gluiconfig from "../glpatch/gluiconfig.js";
  10. import { GuiText } from "../text.js";
  11. import { getHandleBarHtml } from "../utils/handlebars.js";
  12. import undo from "../utils/undo.js";
  13. import opCleaner from "./cleanops.js";
  14. import PatchLayout from "./patchlayout.js";
  15. import { convertPorts, getConverters } from "./converterops.js";
  16. import SuggestionDialog from "./suggestiondialog.js";
  17. import SuggestPortDialog from "./suggestionportdialog.js";
  18. import Snap from "../glpatch/snap.js";
  19. import subPatchOpUtil from "../subpatchop_util.js";
  20. import uiconfig from "../uiconfig.js";
  21. import namespace from "../namespaceutils.js";
  22. import opNames from "../opnameutils.js";
  23. import Gui, { gui } from "../gui.js";
  24. import { platform } from "../platform.js";
  25. import { UserSettings, userSettings } from "./usersettings.js";
  26. import GlPatch from "../glpatch/glpatch.js";
  27. import { UiOp } from "../core_extend_op.js";
  28. import GlPort from "../glpatch/glport.js";
  29. /**
  30. * @typedef AddOpOptions
  31. * @property {string} [subPatch]
  32. * @property {string} [createdLocally]
  33. * @property {Port} [linkNewOpToPort]
  34. * @property {Object} [linkNewLink]
  35. * @property {UiOp} [linkNewOpToOp]
  36. * @property {boolean} [linkOnlyFirstPort]
  37. * @property {AddOpCallback} [onOpAdd]
  38. * @property {import("cables/src/core/core_patch.js").OpUiAttribs} [uiAttribs]
  39. */
  40. /**
  41. * @callback AddOpCallback
  42. * @param {UiOp} result
  43. */
  44. /**
  45. * @typedef GotoOpOptions
  46. * @property {boolean} [focusAnim=true]
  47. * @property {boolean} [showParams=false]
  48. * @property {boolean} [center=true]
  49. * @property {boolean} [zoom=false]
  50. * @property {boolean} [unselectAll]
  51. */
  52. /** Manages the patch view and provides helper functions for editing the patch. */
  53. export default class PatchView extends Events
  54. {
  55. /**
  56. * @param {Patch<UiOp>} corepatch
  57. */
  58. constructor(corepatch)
  59. {
  60. super();
  61. /** @type {Patch<UiOp>} */
  62. this._p = corepatch;
  63. this._log = new Logger("patchview");
  64. this._element = null;
  65. this._pvRenderers = {};
  66. /** @type {GlPatch} */
  67. this._patchRenderer = null;
  68. // this._cachedSubpatchNames = {};
  69. this.isPasting = false;
  70. /** @type {Object} */
  71. this.currentOpPaste = null;
  72. /** @type {String} */
  73. this.newPatchOpPaste = null;
  74. this._showingNavHelperEmpty = false;
  75. this._lastTempOP = null;
  76. this.boundingRect = null;
  77. this.store = new PatchSaveServer(); // this should probably be somewhere else need only one storage, even when opening multiple patchviews ?
  78. this._initListeners();
  79. this._eleSubpatchNav = ele.byId("subpatch_nav");
  80. corepatch.on("onLink", this._portValidate.bind(this));
  81. corepatch.on(Link.EVENT_UNLINK, this._portValidate.bind(this));
  82. corepatch.on("onLink", this.refreshCurrentOpParamsByPort.bind(this));
  83. corepatch.on(Link.EVENT_UNLINK, this.refreshCurrentOpParamsByPort.bind(this));
  84. // corepatch.on("onOpAdd", this._onAddOpHistory.bind(this));
  85. corepatch.on(Patch.EVENT_OP_DELETED, this._onDeleteOpUndo.bind(this));
  86. corepatch.on(Patch.EVENT_OP_ADDED, (op) => { if (!undo.paused()) gui.savedState.setUnSaved("onOpAdd", op.getSubPatch()); });
  87. corepatch.on(Patch.EVENT_OP_DELETED, (op) => { if (!undo.paused()) gui.savedState.setUnSaved("onOpDelete", op.getSubPatch()); });
  88. corepatch.on("onLink", (p1, p2) => { if (!undo.paused()) gui.savedState.setUnSaved("onLink", p1.op.getSubPatch() || p2.op.getSubPatch()); });
  89. corepatch.on(Link.EVENT_UNLINK, (p1, p2) => { if (!undo.paused()) gui.savedState.setUnSaved("onUnLink", p1.op.getSubPatch() || p2.op.getSubPatch()); });
  90. }
  91. get element() { return this._element || PatchView.getElement(); }
  92. static getElement()
  93. {
  94. return document.querySelector("#patchviews .visible");
  95. }
  96. get patchRenderer()
  97. {
  98. return this._patchRenderer;
  99. }
  100. get rendererName()
  101. {
  102. return this._patchRenderer.name;
  103. }
  104. // _onAddOpHistory(op, fromDeserialize)
  105. // {
  106. // if (this._showingNavHelperEmpty)
  107. // {
  108. // this._showingNavHelperEmpty = false;
  109. // ele.hide(ele.byId("patchnavhelperEmpty"));
  110. // }
  111. // if (!fromDeserialize)
  112. // {
  113. // if (!op.uiAttribs) op.uiAttribs = {};
  114. // if (!op.uiAttribs.history) op.uiAttribs.history = {};
  115. // op.uiAttribs.history.createdAt = Date.now();
  116. // op.uiAttribs.history.createdBy = {
  117. // "name": gui.user.usernameLowercase
  118. // };
  119. // op.uiAttribs.history.lastInteractionAt = Date.now();
  120. // op.uiAttribs.history.lastInteractionBy = {
  121. // "name": gui.user.usernameLowercase
  122. // };
  123. // }
  124. // }
  125. /**
  126. * @param {String} subPatchId
  127. */
  128. focusSubpatchOp(subPatchId)
  129. {
  130. const outerOp = gui.corePatch().getSubPatchOuterOp(subPatchId);
  131. gui.patchView.setCurrentSubPatch(outerOp.uiAttribs.subPatch, () =>
  132. {
  133. gui.patchView.centerSelectOp(outerOp.id);
  134. });
  135. }
  136. /**
  137. * @param {String} subPatchId
  138. */
  139. clickSubPatchNav(subPatchId)
  140. {
  141. gui.patchView.setCurrentSubPatch(subPatchId, () =>
  142. {
  143. gui.patchParamPanel.show(true);
  144. this.focus();
  145. });
  146. }
  147. /**
  148. * @param {Op} op
  149. */
  150. _onDeleteOpUndo(op)
  151. {
  152. this.checkPatchErrorsSoon();
  153. (function (opname, _opid)
  154. {
  155. const oldValues = {};
  156. for (let i = 0; i < op.portsIn.length; i++)
  157. {
  158. oldValues[op.portsIn[i].name] = op.portsIn[i].get();
  159. if (op.portsIn[i].anim) oldValues[op.portsIn[i].name + "_anim"] = op.portsIn[i].anim.getSerialized();
  160. }
  161. undo.add({
  162. "title": "delete op",
  163. "context": {
  164. "opname": opname
  165. },
  166. "undo": function ()
  167. {
  168. const newop = gui.corePatch().addOp(opname, op.uiAttribs, _opid);
  169. if (newop)
  170. {
  171. for (const i in oldValues)
  172. {
  173. const port = newop.getPortByName(i);
  174. if (port)
  175. {
  176. port.set(oldValues[i]);
  177. gui.emitEvent("portValueEdited", newop, port, oldValues[i]);
  178. if (oldValues[i + "_anim"])
  179. {
  180. port.setAnimated(true);
  181. port.anim.deserialize(oldValues[i + "_anim"]);
  182. }
  183. }
  184. }
  185. }
  186. },
  187. "redo": function ()
  188. {
  189. gui.corePatch().deleteOp(_opid, false);
  190. }
  191. });
  192. }(op.objName, op.id));
  193. }
  194. setProject(proj, cb)
  195. {
  196. if (!this._patchRenderer)
  197. {
  198. this._log.error("no patchrenderer...");
  199. cb();
  200. return;
  201. }
  202. const perf = gui.uiProfiler.start("[patchview] setproject");
  203. this._p.logStartup("gui set project");
  204. if (proj && proj.ui)
  205. {
  206. this.store.setProject(proj);
  207. if (proj.ui.renderer)
  208. {
  209. if (proj.ui.renderer.w * proj.ui.renderer.s > document.body.clientWidth * 0.9 || proj.ui.renderer.h * proj.ui.renderer.s > document.body.clientHeight * 0.9)
  210. {
  211. proj.ui.renderer.w = 640;
  212. proj.ui.renderer.h = 360;
  213. }
  214. gui.rendererWidth = proj.ui.renderer.w;
  215. gui.rendererHeight = proj.ui.renderer.h;
  216. if (gui.corePatch().cgl)gui.corePatch().cgl.canvasScale = proj.ui.renderer.s || 1;
  217. gui.setLayout();
  218. }
  219. // gui.setTimeLineLength(proj.ui.timeLineLength);
  220. }
  221. gui.setProject(proj);
  222. this._patchRenderer.setProject(proj);
  223. this.store.setServerDate(proj.updated);
  224. if (gui.isRemoteClient)
  225. {
  226. if (cb) cb();
  227. return;
  228. }
  229. perf.finish();
  230. this._p.logStartup("loadProjectDependencies...");
  231. gui.serverOps.loadProjectDependencies(proj, (project) =>
  232. {
  233. this._p.logStartup("loadProjectDependencies done");
  234. this._p.logStartup("deserialize...");
  235. const perf3 = gui.uiProfiler.start("[core] deserialize");
  236. gui.corePatch().deSerialize(project);
  237. perf3.finish();
  238. const perf2 = gui.uiProfiler.start("[patchview] setproject2");
  239. this._p.logStartup("deserialize done");
  240. undo.clear();
  241. const ops = gui.corePatch().ops;
  242. if (!gui.isRemoteClient)
  243. {
  244. for (let i = 0; i < ops.length; i++)
  245. if (ops[i].uiAttribs.selected) this.selectOpId(ops[i].id);
  246. if (!this._showingNavHelperEmpty && gui.corePatch().ops.length == 0)
  247. {
  248. this._showingNavHelperEmpty = true;
  249. ele.show(ele.byId("patchnavhelperEmpty"));
  250. }
  251. }
  252. gui.patchView.checkPatchOutdated();
  253. if (gui.project() && gui.project().ui) gui.metaTexturePreviewer.deserialize(gui.project().ui.texPreview);
  254. gui.patchView.removeLostSubpatches();
  255. perf2.finish();
  256. if (cb) cb();
  257. });
  258. }
  259. _initListeners()
  260. {
  261. }
  262. /**
  263. * @param {String} id
  264. */
  265. switch(id)
  266. {
  267. const views = ele.byId("patchviews");
  268. for (let i = 0; i < views.children.length; i++)
  269. {
  270. views.children[i].style.display = "none";
  271. views.children[i].classList.remove("visible");
  272. }
  273. const el = document.getElementById(id);
  274. el.classList.add("visible");
  275. el.style.display = "block";
  276. this._patchRenderer = this._pvRenderers[id];
  277. gui.setLayout();
  278. }
  279. updateBoundingRect()
  280. {
  281. const el = PatchView.getElement();
  282. if (el) this.boundingRect = el.getBoundingClientRect();
  283. }
  284. /**
  285. * @returns {Boolean}
  286. */
  287. hasFocus()
  288. {
  289. return this._patchRenderer.isFocused();
  290. }
  291. /**
  292. * @param {UiOp} op
  293. */
  294. testCollision(op)
  295. {
  296. if (userSettings.get(UserSettings.PREF_CHECK_OP_COLLISIONS) === false) return;
  297. if (!op || !op.uiAttribs) return;
  298. let count = 0;
  299. let collided = {};
  300. for (let j = 0; j < gui.corePatch().ops.length; j++)
  301. {
  302. const b = gui.corePatch().ops[j];
  303. if (!b || !b.uiAttribs || b.deleted || b == op) continue;
  304. if (b.uiAttribs.subPatch != op.uiAttribs.subPatch) continue;
  305. if (!b.uiAttribs.translate) continue;
  306. if (!op.uiAttribs.translate) continue;
  307. if (collided[b.id]) continue;
  308. const glopA = this._patchRenderer.getGlOp(op);
  309. const glopB = this._patchRenderer.getGlOp(b);
  310. if (!glopA || !glopB) return;
  311. let found = true;
  312. if (!op.uiAttribs.resizable && !b.uiAttribs.resizable)
  313. while (found)
  314. {
  315. found = false;
  316. if (
  317. (
  318. glopA.x >= glopB.x && glopA.x <= glopB.x + glopB.w &&
  319. glopA.y >= glopB.y && glopA.y <= glopB.y + glopB.h
  320. )
  321. ||
  322. (
  323. glopA.x + glopA.w >= glopB.x && glopA.x + glopA.w <= glopB.x + glopB.w &&
  324. glopA.y + glopA.h >= glopB.y && glopA.y + glopA.h <= glopB.y + glopB.h
  325. )
  326. ||
  327. (
  328. glopA.x >= glopB.x && glopA.x <= glopB.x + glopB.w &&
  329. glopA.y + glopA.h >= glopB.y && glopA.y + glopA.h <= glopB.y + glopB.h
  330. )
  331. ||
  332. (
  333. glopA.x + glopA.w >= glopB.x && glopA.x + glopA.w <= glopB.x + glopB.w &&
  334. glopA.y >= glopB.y && glopA.y <= glopB.y + glopB.h
  335. )
  336. )
  337. {
  338. let mulDirY = 1;
  339. if (op.isLinkedOut() && !op.isLinkedIn()) mulDirY = -1; // move upwards
  340. let y = Snap.snapOpPosY(b.uiAttribs.translate.y + mulDirY * (uiconfig.snapY / 2 + glopB.h));
  341. let x = op.uiAttribs.translate.x;
  342. const link = op.isConnectedTo(b);
  343. if (link)
  344. {
  345. let p = link.portIn;
  346. if (link.portOut.op == op) p = link.portOut;
  347. const otherPort = link.getOtherPort(p);
  348. x = otherPort.op.uiAttribs.translate.x + otherPort.op.getPortPosX(otherPort.name);
  349. }
  350. op.setUiAttrib({ "translate": { "x": x, "y": y } });
  351. gui.patchView.testCollision(op);
  352. found = true;
  353. count++;
  354. collided[b.id] = true;
  355. collided[op.id] = true;
  356. }
  357. if (count > 100)
  358. {
  359. this._log.log("count 100");
  360. return;
  361. }
  362. }
  363. }
  364. }
  365. focus()
  366. {
  367. if (this._patchRenderer && this._patchRenderer.focus) this._patchRenderer.focus();
  368. }
  369. clearPatch()
  370. {
  371. this._patchRenderer.dispose();
  372. this._p.clear();
  373. }
  374. /**
  375. * @param {string} id
  376. * @param {GlPatch} pr
  377. */
  378. setPatchRenderer(id, pr)
  379. {
  380. this._pvRenderers[id] = pr;
  381. if (!this._patchRenderer) this._patchRenderer = pr;
  382. }
  383. /**
  384. * @param {string} filename
  385. * @param {PointerEvent} event
  386. */
  387. addAssetOpAuto(filename, event)
  388. {
  389. if (gui.getRestriction() < Gui.RESTRICT_MODE_FULL) return;
  390. const ops = opNames.getOpsForFilename(filename);
  391. if (ops.length == 0)
  392. {
  393. notify("No default op for filetype");
  394. return;
  395. }
  396. const opname = ops[0];
  397. /** @type {import("cables/src/core/core_op.js").OpUiAttribs} */
  398. const uiAttr = { "subPatch": this.getCurrentSubPatch() };
  399. let coordArr = this._patchRenderer.screenToPatchCoord(150, 150);
  400. if (event && this._patchRenderer.screenToPatchCoord)
  401. {
  402. coordArr = this._patchRenderer.screenToPatchCoord(event.clientX || event.x, event.clientY || event.y);
  403. }
  404. const coord = { "x": coordArr[0], "y": coordArr[1] };
  405. coord.x = Snap.snapOpPosX(coord.x);
  406. coord.y = Snap.snapOpPosY(coord.y);
  407. uiAttr.translate = { "x": coord.x, "y": coord.y };
  408. gui.serverOps.loadOpDependencies(opname, () =>
  409. {
  410. const op = gui.corePatch().addOp(opname, uiAttr);
  411. for (let i = 0; i < op.portsIn.length; i++)
  412. if (op.portsIn[i].uiAttribs.display == "file")
  413. op.portsIn[i].set(filename);
  414. // op.refreshParams();
  415. // this.centerSelectOp(op.opId);
  416. this.gotoOp(op.opId, {});
  417. });
  418. }
  419. /**
  420. * @param {string} opname
  421. * @param {AddOpOptions} [options]
  422. */
  423. addOp(opname, options)
  424. {
  425. gui.jobs().start({ "id": "loadOpDependencies" });
  426. gui.serverOps.loadOpDependencies(opname, () =>
  427. {
  428. gui.jobs().finish("loadOpDependencies");
  429. options = options || {};
  430. const uiAttribs = options.uiAttribs || {};
  431. if (options.subPatch) uiAttribs.subPatch = options.subPatch;
  432. if (options.createdLocally) uiAttribs.createdLocally = true;
  433. if (!uiAttribs.subPatch)
  434. {
  435. uiAttribs.subPatch = this.getCurrentSubPatch();
  436. }
  437. const op = this._p.addOp(opname, uiAttribs);
  438. if (!op) return;
  439. if (this._showingNavHelperEmpty)
  440. {
  441. document.getElementById("patchnavhelperEmpty").style.display = "none";
  442. }
  443. // todo options:
  444. // - putIntoLink
  445. // ...?
  446. // positioning ?
  447. if (options.linkNewOpToPort)
  448. {
  449. if (options.linkOnlyFirstPort)
  450. {
  451. if (options.linkNewOpToPort && op.portsIn[0] && op.portsIn[0].type == options.linkNewOpToPort.type)
  452. {
  453. gui.corePatch().link(
  454. options.linkNewOpToOp,
  455. options.linkNewOpToPort.getName(),
  456. op,
  457. op.portsIn[0].getName());
  458. this.alignOpBelowOp(op, options.linkNewOpToOp);
  459. }
  460. }
  461. else
  462. {
  463. const foundPort = op.findFittingPort(options.linkNewOpToPort);
  464. if (foundPort)
  465. {
  466. if (op.objName == defaultOps.defaultOpNames.number)
  467. {
  468. const oldValue = options.linkNewOpToPort.get();
  469. op.getPort("value").set(oldValue);
  470. op.setTitle(options.linkNewOpToPort.getName());
  471. }
  472. if (op.objName == defaultOps.defaultOpNames.string)
  473. {
  474. const oldValue = options.linkNewOpToPort.get();
  475. op.getPort("value").set(oldValue);
  476. op.setTitle(options.linkNewOpToPort.getName());
  477. }
  478. gui.corePatch().link(
  479. options.linkNewOpToOp,
  480. options.linkNewOpToPort.getName(),
  481. op,
  482. foundPort.getName());
  483. }
  484. }
  485. }
  486. if (options.linkNewLink)
  487. {
  488. let op1 = null;
  489. let op2 = null;
  490. let port1 = null;
  491. let port2 = null;
  492. if (options.linkNewLink.p1)
  493. {
  494. // patch_link
  495. op1 = options.linkNewLink.p1.op;
  496. op2 = options.linkNewLink.p2.op;
  497. port1 = options.linkNewLink.p1.thePort;
  498. port2 = options.linkNewLink.p2.thePort;
  499. }
  500. else if (options.linkNewLink.portIn && options.linkNewLink.portOut)
  501. {
  502. // core link
  503. op2 = options.linkNewLink.portIn.op;
  504. op1 = options.linkNewLink.portOut.op;
  505. port2 = options.linkNewLink.portIn;
  506. port1 = options.linkNewLink.portOut;
  507. }
  508. let foundPort1 = null;
  509. let foundPort2 = null;
  510. if (port1 && port2)
  511. {
  512. foundPort1 = op.findFittingPort(port1);
  513. foundPort2 = op.findFittingPort(port2);
  514. }
  515. if (foundPort2 && foundPort1)
  516. {
  517. for (const il in port1.links)
  518. {
  519. if (
  520. (port1.links[il].portIn == port1 && port1.links[il].portOut == port2) ||
  521. (port1.links[il].portOut == port1 && port1.links[il].portIn == port2)) port1.links[il].remove();
  522. }
  523. gui.corePatch().link(
  524. op,
  525. foundPort1.getName(),
  526. op1,
  527. port1.getName()
  528. );
  529. gui.corePatch().link(
  530. op,
  531. foundPort2.getName(),
  532. op2,
  533. port2.getName()
  534. );
  535. }
  536. }
  537. if (options.onOpAdd) options.onOpAdd(op);
  538. });
  539. }
  540. /**
  541. * @param {string} opname
  542. * @param {string} opid
  543. * @param {string} portname
  544. * @param {function} [cb]
  545. */
  546. addOpAndLink(opname, opid, portname, cb)
  547. {
  548. const oldOp = gui.corePatch().getOpById(opid);
  549. const trans = {
  550. "x": oldOp.uiAttribs.translate.x,
  551. "y": oldOp.uiAttribs.translate.y - gluiconfig.newOpDistanceY
  552. };
  553. gui.patchView.addOp(opname, {
  554. "onOpAdd": (newOp) =>
  555. {
  556. let newPort = newOp.getFirstOutPortByType(oldOp.getPortByName(portname).type);
  557. if (oldOp.getPortByName(portname).direction == Port.DIR_OUT)
  558. newPort = newOp.getFirstInPortByType(oldOp.getPortByName(portname).type);
  559. gui.corePatch().link(oldOp, portname, newOp, newPort.name);
  560. newOp.setUiAttrib({
  561. "translate": trans,
  562. "subPatch": this.getCurrentSubPatch()
  563. });
  564. this.testCollision(newOp);
  565. if (cb) cb(newOp);
  566. }
  567. });
  568. }
  569. showSelectedOpsPanel()
  570. {
  571. const ops = this.getSelectedOps();
  572. const numops = ops.length;
  573. if (numops > 0)
  574. {
  575. let mulSubs = false;
  576. for (let i = 0; i < ops.length; i++) if (ops[i].uiAttribs.subPatch != ops[0].uiAttribs.subPatch) { mulSubs = true; break; }
  577. const html = getHandleBarHtml(
  578. "params_ops", {
  579. "isDevEnv": platform.isDevEnv(),
  580. "config": platform.config,
  581. "showDevInfos": userSettings.get(UserSettings.PREF_DEVINFOS),
  582. "bounds": this.getSelectionBounds(),
  583. "numOps": numops,
  584. "mulSubs": mulSubs,
  585. "commentColors": uiconfig.commentColors
  586. });
  587. gui.opParams.clear();
  588. ele.byId(gui.getParamPanelEleId()).innerHTML = html;
  589. gui.setTransformGizmo(null);
  590. gui.showInfo(GuiText.patchSelectedMultiOps);
  591. }
  592. else
  593. {
  594. this.showDefaultPanel();
  595. }
  596. }
  597. showDefaultPanel()
  598. {
  599. gui.setTransformGizmo(null);
  600. gui.opParams.clear();
  601. gui.patchParamPanel.show();
  602. }
  603. /**
  604. * @param {string} subPatch
  605. * @param {boolean} [noUnselect]
  606. */
  607. selectAllOpsSubPatch(subPatch, noUnselect)
  608. {
  609. const ops = gui.corePatch().getSubPatchOps(subPatch);
  610. for (let i = 0; i < ops.length; i++)
  611. {
  612. const op = ops[i];
  613. if (op)
  614. {
  615. if ((op.uiAttribs.subPatch || 0) == subPatch && !op.uiAttribs.selected)
  616. {
  617. op.uiAttr({ "selected": true });
  618. // if (op.isSubPatchOp())
  619. // this.selectAllOpsSubPatch(op.patchId.get(), true);
  620. }
  621. else if (!noUnselect) op.uiAttr({ "selected": false });
  622. }
  623. }
  624. this.showSelectedOpsPanel();
  625. }
  626. /**
  627. * @param {boolean} [setUiError]
  628. */
  629. checkPatchOutdated(setUiError)
  630. {
  631. const perf = gui.uiProfiler.start("checkpatcherrors");
  632. this.hasOldOps = false;
  633. for (let i = 0; i < this._p.ops.length; i++)
  634. {
  635. const doc = gui.opDocs.getOpDocByName(this._p.ops[i].objName);
  636. if (setUiError) this._p.ops[i].setUiError("outdated", null);
  637. if ((doc && doc.oldVersion) || namespace.isDeprecatedOp(this._p.ops[i].objName))
  638. {
  639. this.hasOldOps = true;
  640. perf.finish();
  641. if (setUiError) this._p.ops[i].setUiError("outdated", "Outdated op in example patch");
  642. else return;
  643. }
  644. }
  645. perf.finish();
  646. }
  647. checkPatchErrorsSoon()
  648. {
  649. this._checkErrorTimeout = setTimeout(() =>
  650. {
  651. clearTimeout(this._checkErrorTimeout);
  652. this.checkPatchOutdated();
  653. this.checkPatchErrors();
  654. }, 500);
  655. }
  656. checkPatchErrors()
  657. {
  658. // if (gui.unload) return;
  659. // const perf = gui.uiProfiler.start("checkpatcherrors");
  660. // const hadErrors = this.hasUiErrors;
  661. // this.hasUiErrors = false;
  662. // const patchSummary = gui.getPatchSummary();
  663. // let isExamplePatch = false;
  664. // if (patchSummary)
  665. // isExamplePatch = patchSummary.isBasicExample || (patchSummary.exampleForOps && patchSummary.exampleForOps.length > 0);
  666. // if (!this._checkErrorTimeout)
  667. // {
  668. // gui.patchView.checkPatchOutdated(isExamplePatch); // first time also check outdated ops..
  669. // if (isExamplePatch) CmdPatch.clearOpTitles(); // examples should not have edited op titles...
  670. // }
  671. // const ops = gui.corePatch().ops;
  672. // for (let i = 0; i < ops.length; i++)
  673. // if (ops[i].uiAttribs && ops[i].uiAttribs.uierrors)
  674. // for (let j = 0; j < ops[i].uiAttribs.uierrors.length; j++)
  675. // if (ops[i].uiAttribs.uierrors[j].level == 2)
  676. // {
  677. // this.hasUiErrors = true;
  678. // break;
  679. // }
  680. // if (hadErrors != this.hasUiErrors)
  681. // gui.corePatch().emitEvent("warningErrorIconChange");
  682. // let showAttentionIcon = this.hasUiErrors;
  683. // if (this.hasOldOps && (patchSummary && patchSummary.isBasicExample || isExamplePatch)) showAttentionIcon = true;
  684. // clearTimeout(this._checkErrorTimeout);
  685. // const elError = ele.byId("nav-item-error");
  686. // const wasHidden = elError.classList.contains("hidden");
  687. // if (showAttentionIcon) ele.show(elError);
  688. // else ele.hide(elError);
  689. // const elIcon = ele.byId("nav-item-error-icon");
  690. // if (showAttentionIcon) elIcon.style["background-color"] = "red";
  691. // if (wasHidden != elError.classList.contains("hidden")) gui.setLayout();
  692. // perf.finish();
  693. // this._checkErrorTimeout = setTimeout(this.checkPatchErrors.bind(this), 5000);
  694. }
  695. /**
  696. * @param {string} subPatch
  697. */
  698. centerSubPatchBounds(subPatch)
  699. {
  700. const bounds = this.getSubPatchBounds(subPatch);
  701. const ops = this._p.ops;
  702. let count = 0;
  703. for (let j = 0; j < ops.length; j++)
  704. if (ops[j].uiAttribs.subPatch == subPatch && ops[j].uiAttribs && ops[j].uiAttribs.translate)
  705. {
  706. count++;
  707. ops[j].setPos(
  708. ops[j].uiAttribs.translate.x - bounds.minX - bounds.size[0] / 2,
  709. ops[j].uiAttribs.translate.y - bounds.minY - bounds.size[1] / 2
  710. );
  711. }
  712. }
  713. /**
  714. * @param {string} subPatchId
  715. */
  716. getSubPatchBounds(subPatchId)
  717. {
  718. if (subPatchId == undefined) subPatchId = this.getCurrentSubPatch();
  719. const perf = gui.uiProfiler.start("patch.getSubPatchBounds");
  720. const ops = this._p.ops;
  721. const theOps = [];
  722. for (let j = 0; j < ops.length; j++)
  723. if (ops[j].uiAttribs.subPatch == subPatchId)
  724. // if (ops[j].objName.indexOf("Ops.Ui.") == -1 && ops[j].objName.indexOf("Ops.Dev.Ui.") == -1)
  725. if (ops[j].objName != defaultOps.defaultOpNames.subPatchInput2 && ops[j].objName != defaultOps.defaultOpNames.subPatchOutput2)
  726. theOps.push(ops[j]);
  727. let bounds = this.getOpBounds(theOps);
  728. perf.finish();
  729. return bounds;
  730. }
  731. getOpBounds(ops, options = {})
  732. {
  733. if (options.minWidth == undefined) options.minWidth = 100;
  734. const bb = new BoundingBox();
  735. for (let j = 0; j < ops.length; j++)
  736. {
  737. if (ops[j].uiAttribs && ops[j].uiAttribs.translate)
  738. {
  739. bb.applyPos(ops[j].uiAttribs.translate.x, ops[j].uiAttribs.translate.y, 0);
  740. const glop = this.patchRenderer.getGlOp(ops[j]);
  741. if (glop) bb.applyPos(ops[j].uiAttribs.translate.x + glop.w, ops[j].uiAttribs.translate.y + glop.h, 0);
  742. else bb.applyPos(ops[j].uiAttribs.translate.x + gluiconfig.opWidth, ops[j].uiAttribs.translate.y + gluiconfig.opHeight, 0);
  743. }
  744. }
  745. bb.calcCenterSize();
  746. return bb;
  747. }
  748. /**
  749. * @param {number} [minWidth]
  750. */
  751. getSelectionBounds(minWidth)
  752. {
  753. const ops = this.getSelectedOps();
  754. return this.getOpBounds(ops, { "minWidth": minWidth });
  755. }
  756. /**
  757. * @param {number} primAxis
  758. * @param {number} secAxis
  759. * @param {number} primAxisB
  760. * @param {number} secAxisB
  761. */
  762. getDistScore(primAxis, secAxis, primAxisB, secAxisB)
  763. {
  764. let score = 0;
  765. if (primAxis != primAxisB)
  766. score = Math.abs(primAxis - primAxisB);
  767. if (secAxis != secAxisB)
  768. score += (Math.abs(secAxis - secAxisB)) * 2;
  769. return score;
  770. }
  771. getClosestOp()
  772. {
  773. let coordArr = this._patchRenderer.screenToPatchCoord(150, 150);
  774. let minDist = 999999;
  775. let foundOp = null;
  776. const cursub = this.getCurrentSubPatch();
  777. for (let i = 0; i < this._p.ops.length; i++)
  778. {
  779. if (this._p.ops[i].getSubPatch() == cursub && this._p.ops[i].uiAttribs.translate)
  780. {
  781. const a = this.getDistScore(this._p.ops[i].uiAttribs.translate.x, this._p.ops[i].uiAttribs.translate.y, coordArr[0], coordArr[1]);
  782. if (a < minDist)
  783. {
  784. minDist = a;
  785. foundOp = this._p.ops[i];
  786. }
  787. }
  788. }
  789. return foundOp;
  790. }
  791. /**
  792. * @param {number} x
  793. * @param {number} y
  794. */
  795. cursorNavOps(x, y)
  796. {
  797. const ops = this.getSelectedOps();
  798. let curOp;
  799. if (ops.length == 0) curOp = this.getClosestOp();
  800. else curOp = ops[0];
  801. if (!curOp) return;
  802. const cursub = this.getCurrentSubPatch();
  803. let foundOp = null;
  804. let foundOpScore = 9999999;
  805. for (let i = 0; i < this._p.ops.length; i++)
  806. {
  807. const op = this._p.ops[i];
  808. if (op.getSubPatch() == cursub && op.uiAttribs.translate)
  809. {
  810. if (y == 1 && op.uiAttribs.translate.y > curOp.uiAttribs.translate.y)
  811. {
  812. const score = this.getDistScore(curOp.uiAttribs.translate.y, curOp.uiAttribs.translate.x, op.uiAttribs.translate.y, op.uiAttribs.translate.x);
  813. // this._log.log(" score", op.name, score);
  814. if (score < foundOpScore)
  815. {
  816. foundOp = op;
  817. foundOpScore = score;
  818. }
  819. }
  820. else
  821. if (y == -1 && op.uiAttribs.translate.y < curOp.uiAttribs.translate.y)
  822. {
  823. const score = this.getDistScore(curOp.uiAttribs.translate.y, curOp.uiAttribs.translate.x, op.uiAttribs.translate.y, op.uiAttribs.translate.x);
  824. // this._log.log(" score", op.name, score);
  825. if (score < foundOpScore)
  826. {
  827. foundOp = op;
  828. foundOpScore = score;
  829. }
  830. }
  831. else
  832. if (x == 1 && op.uiAttribs.translate.x > curOp.uiAttribs.translate.x)
  833. {
  834. const score = this.getDistScore(curOp.uiAttribs.translate.x, curOp.uiAttribs.translate.y, op.uiAttribs.translate.x, op.uiAttribs.translate.y);
  835. // this._log.log(" score", op.name, score);
  836. if (score < foundOpScore)
  837. {
  838. foundOp = op;
  839. foundOpScore = score;
  840. }
  841. }
  842. else
  843. if (x == -1 && op.uiAttribs.translate.x < curOp.uiAttribs.translate.x)
  844. {
  845. const score = this.getDistScore(curOp.uiAttribs.translate.x, curOp.uiAttribs.translate.y, op.uiAttribs.translate.x, op.uiAttribs.translate.y);
  846. // this._log.log(" score", op.name, score);
  847. if (score < foundOpScore)
  848. {
  849. foundOp = op;
  850. foundOpScore = score;
  851. }
  852. }
  853. }
  854. }
  855. if (foundOp)
  856. {
  857. this.setSelectedOpById(foundOp.id);
  858. this.focusOp(foundOp.id);
  859. }
  860. }
  861. getSelectedOpsIds()
  862. {
  863. const perf = gui.uiProfiler.start("patchview getSelectedOpsIds");
  864. const ops = [];
  865. for (let i = 0; i < this._p.ops.length; i++)
  866. if (this._p.ops[i].uiAttribs.selected)
  867. ops.push(this._p.ops[i].id);
  868. perf.finish();
  869. return ops;
  870. }
  871. /**
  872. * @returns {UiOp[]}
  873. */
  874. getSelectedOps()
  875. {
  876. const perf = gui.uiProfiler.start("patchview getSelectedOps");
  877. /** @type {UiOp[]} */
  878. const ops = [];
  879. for (let i = 0; i < this._p.ops.length; i++)
  880. if (this._p.ops[i] && this._p.ops[i].uiAttribs && this._p.ops[i].uiAttribs.selected)
  881. ops.push(/** @type {UiOp} */ (this._p.ops[i]));
  882. perf.finish();
  883. return ops;
  884. }
  885. getNumSelectedOps()
  886. {
  887. const perf = gui.uiProfiler.start("patchview getNumSelectedOps");
  888. let count = 0;
  889. for (let i = 0; i < this._p.ops.length; i++)
  890. if (this._p.ops[i] && this._p.ops[i].uiAttribs && this._p.ops[i].uiAttribs.selected)
  891. count++;
  892. perf.finish();
  893. return count;
  894. }
  895. /** @param {boolean} [firstOnly] */
  896. unlinkSelectedOps(firstOnly)
  897. {
  898. const undoGroup = undo.startGroup();
  899. const ops = this.getSelectedOps();
  900. if (firstOnly)
  901. {
  902. for (const i in ops)
  903. {
  904. if (ops[i].portsIn.length > 0 && ops[i].portsOut.length > 0)
  905. {
  906. let portIn = ops[i].getFirstPortIn();
  907. let portOut = ops[i].getFirstPortOut();
  908. if (portOut.type == portIn.type && (portOut.isLinked() || portIn.isLinked()))
  909. {
  910. let outerIn = [];
  911. let outerOut = [];
  912. let relink = portOut.isLinked() && portIn.isLinked();
  913. if (relink)
  914. {
  915. for (let o = 0; o < portIn.links.length; o++)
  916. outerOut.push(portIn.links[o].getOtherPort(portIn));
  917. for (let o = 0; o < portOut.links.length; o++)
  918. outerIn.push(portOut.links[o].getOtherPort(portOut));
  919. }
  920. portOut.removeLinks();
  921. portIn.removeLinks();
  922. if (relink)
  923. {
  924. for (let j = 0; j < outerIn.length; j++)
  925. for (let o = 0; o < outerOut.length; o++)
  926. ops[i].patch.link(outerIn[j].op, outerIn[j].getName(), outerOut[o].op, outerOut[o].getName());
  927. }
  928. }
  929. }
  930. }
  931. }
  932. else
  933. {
  934. for (const i in ops) ops[i].unLinkReconnectOthers();
  935. }
  936. undo.endGroup(undoGroup, "Unlink selected Ops");
  937. }
  938. deleteSelectedOps()
  939. {
  940. if (gui.getRestriction() < Gui.RESTRICT_MODE_FULL) return;
  941. const undoGroup = undo.startGroup();
  942. const ids = [];
  943. const ops = this.getSelectedOps();
  944. for (let i = 0; i < ops.length; i++) ids.push(ops[i].id);
  945. for (let i = 0; i < ids.length; i++) this._p.deleteOp(ids[i], true);
  946. undo.endGroup(undoGroup, "Delete selected ops");
  947. }
  948. createAreaFromSelection()
  949. {
  950. // const selectedOus = this.getSelectedOps();
  951. const bounds = this.getSelectionBounds();
  952. const padding = 80;
  953. const trans = {
  954. "x": Snap.snapOpPosX(bounds.minX - 0.8 * padding),
  955. "y": Snap.snapOpPosY(bounds.minY - 1.2 * padding)
  956. };
  957. const areaOp = this._p.addOp(defaultOps.defaultOpNames.uiArea, {
  958. "translate": trans,
  959. "subPatch": this.getCurrentSubPatch(),
  960. "area": {
  961. "w": Snap.snapOpPosX(bounds.maxX - bounds.minX + (2.75 * padding)),
  962. "h": Snap.snapOpPosY(bounds.maxY - bounds.minY + (2 * padding))
  963. }
  964. });
  965. (function (opid)
  966. {
  967. undo.add({
  968. "title": "paste op",
  969. "undo": function ()
  970. {
  971. gui.corePatch().deleteOp(opid, true);
  972. },
  973. "redo": function ()
  974. {
  975. gui.corePatch().addOp(defaultOps.defaultOpNames.uiArea, {
  976. "translate": trans,
  977. "area": {
  978. "w": Snap.snapOpPosX(bounds.maxX - bounds.minX + (2.75 * padding)),
  979. "h": Snap.snapOpPosY(bounds.maxY - bounds.minY + (2.2 * padding))
  980. }
  981. });
  982. }
  983. });
  984. }(areaOp.id));
  985. }
  986. createSubPatchFromSelection(version = 0, next = null, options = {})
  987. {
  988. let opname = defaultOps.defaultOpNames.subPatch;
  989. if (version == 2) opname = defaultOps.defaultOpNames.subPatch2;
  990. const selectedOps = this.getSelectedOps();
  991. gui.serverOps.loadOpDependencies(opname,
  992. () =>
  993. {
  994. const bounds = this.getSelectionBounds();
  995. let trans = {
  996. "x": bounds.minX + (bounds.maxX - bounds.minX) / 2,
  997. "y": bounds.minY
  998. };
  999. if (options.translate) trans = options.translate;
  1000. // opname = defaultOps.defaultOpNames.subPatch;
  1001. // if (version == 2)opname = defaultOps.defaultOpNames.subPatch2;
  1002. const patchOp = this._p.addOp(opname, { "translate": trans, "subPatch": this.getCurrentSubPatch() });
  1003. const patchId = patchOp.patchId.get();
  1004. if (version < 2)
  1005. {
  1006. for (let i in selectedOps)
  1007. {
  1008. // if (selectedOps[i].uiAttribs.subPatch == this.getCurrentSubPatch())
  1009. selectedOps[i].setUiAttribs({ "subPatch": patchId });
  1010. }
  1011. for (let i = 0; i < selectedOps.length; i++)
  1012. {
  1013. for (let j = 0; j < selectedOps[i].portsIn.length; j++)
  1014. {
  1015. const theOp = selectedOps[i];
  1016. let found = null;
  1017. for (let k = 0; k < theOp.portsIn[j].links.length; k++)
  1018. {
  1019. const otherPort = theOp.portsIn[j].links[k].getOtherPort(theOp.portsIn[j]);
  1020. const otherOp = otherPort.op;
  1021. if (otherOp.uiAttribs.subPatch != patchId)
  1022. {
  1023. theOp.portsIn[j].links[k].remove();
  1024. k--;
  1025. if (found)
  1026. {
  1027. this._p.link(
  1028. otherPort.op,
  1029. otherPort.getName(),
  1030. patchOp,
  1031. found);
  1032. }
  1033. else
  1034. {
  1035. this._p.link(
  1036. otherPort.op,
  1037. otherPort.getName(),
  1038. patchOp,
  1039. patchOp.dyn.name);
  1040. found = patchOp.addSubLink(theOp.portsIn[j], otherPort);
  1041. }
  1042. }
  1043. }
  1044. if (theOp.portsOut[j])
  1045. {
  1046. for (let k = 0; k < theOp.portsOut[j].links.length; k++)
  1047. {
  1048. const otherPortOut = theOp.portsOut[j].links[k].getOtherPort(theOp.portsOut[j]);
  1049. if (otherPortOut)
  1050. {
  1051. const otherOpOut = otherPortOut.op;
  1052. if (otherOpOut.uiAttribs.subPatch != patchId)
  1053. {
  1054. theOp.portsOut[j].links[k].remove();
  1055. this._p.link(
  1056. otherPortOut.op,
  1057. otherPortOut.getName(),
  1058. patchOp,
  1059. patchOp.dynOut.name);
  1060. patchOp.addSubLink(theOp.portsOut[j], otherPortOut);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. else
  1069. {
  1070. for (let i in selectedOps)
  1071. {
  1072. if (selectedOps[i].uiAttribs.subPatch == this.getCurrentSubPatch())
  1073. selectedOps[i].setUiAttribs({ "subPatch": patchId });
  1074. }
  1075. this.setPositionSubPatchInputOutputOps();
  1076. if (next) next(patchId, patchOp);
  1077. // }, 100);
  1078. }
  1079. gui.patchView.setCurrentSubPatch(this.getCurrentSubPatch(), () =>
  1080. {
  1081. this._p.emitEvent("subpatchCreated");
  1082. });
  1083. });
  1084. }
  1085. /**
  1086. * @param {string} [patchId]
  1087. */
  1088. setPositionSubPatchInputOutputOps(patchId)
  1089. {
  1090. const b = this.getSubPatchBounds(patchId);
  1091. if (!patchId) return;
  1092. let patchInputOPs = this._p.getSubPatchOpsByName(patchId, defaultOps.defaultOpNames.subPatchInput2);
  1093. let patchOutputOPs = this._p.getSubPatchOpsByName(patchId, defaultOps.defaultOpNames.subPatchOutput2);
  1094. if (patchInputOPs.length == 0)
  1095. {
  1096. if (this._p.clearSubPatchCache) this._p.clearSubPatchCache(patchId);
  1097. this._p.addOp(defaultOps.defaultOpNames.subPatchInput2, { "subPatch": patchId, "translate": { "x": 0, "y": 0 } });
  1098. this._p.addOp(defaultOps.defaultOpNames.subPatchOutput2, { "subPatch": patchId, "translate": { "x": 0, "y": 0 } });
  1099. }
  1100. if (patchInputOPs.length > 1) this._log.warn("too many input ops?");
  1101. if (patchOutputOPs.length > 1) this._log.warn("too many output ops?");
  1102. let patchInputOP = patchInputOPs[0];
  1103. let patchOutputOP = patchOutputOPs[0];
  1104. let x = 0;
  1105. if (patchInputOP || patchOutputOP)
  1106. {
  1107. x = (patchInputOP || patchOutputOP).uiAttribs.translate.x;
  1108. if (x < b.minX) x = b.minX;
  1109. if (x > b.maxX) x = b.maxX;
  1110. }
  1111. if (patchInputOP)
  1112. {
  1113. let y = Math.min(patchInputOP.uiAttribs.translate.y, b.minY - gluiconfig.newOpDistanceY * 2);
  1114. patchInputOP.setUiAttribs(
  1115. {
  1116. "translate":
  1117. {
  1118. "x": x,
  1119. "y": y
  1120. }
  1121. });
  1122. }
  1123. if (patchOutputOP)
  1124. {
  1125. let y = Math.max(patchOutputOP.uiAttribs.translate.y, b.maxY + gluiconfig.newOpDistanceY * 2);
  1126. patchOutputOP.setUiAttribs(
  1127. {
  1128. "translate":
  1129. {
  1130. "x": x,
  1131. "y": y
  1132. }
  1133. });
  1134. }
  1135. }
  1136. getSubPatchName(subpatch)
  1137. {
  1138. if (subpatch == 0) return "Main";
  1139. const op = gui.corePatch().getSubPatchOuterOp(subpatch);
  1140. if (!op) return null;
  1141. return op.name;
  1142. }
  1143. /**
  1144. * @param {string | number} subId
  1145. * @param {Object[]} [arr]
  1146. */
  1147. getSubpatchPathArray(subId, arr)
  1148. {
  1149. arr = arr || [];
  1150. const ops = gui.corePatch().ops;
  1151. for (let i = 0; i < ops.length; i++)
  1152. {
  1153. if (ops[i].isSubPatchOp() && ops[i].patchId)
  1154. {
  1155. if (ops[i].patchId.get() == subId)
  1156. {
  1157. let type = "subpatch";
  1158. if (ops[i].isSubPatchOp()) type = "blueprint_subpatch2";
  1159. const patchInfo = {
  1160. "name": ops[i].name,
  1161. "patchid": ops[i].patchId.get(),
  1162. // "id": ops[i].patchId.get(),
  1163. "type": type
  1164. };
  1165. arr.push(patchInfo);
  1166. if (ops[i].uiAttribs.subPatch !== Patch.DEFAULT_SUBPATCHID) this.getSubpatchPathArray(ops[i].uiAttribs.subPatch, arr);
  1167. }
  1168. }
  1169. }
  1170. return arr;
  1171. }
  1172. removeLostSubpatches()
  1173. {
  1174. let countSubs = {};
  1175. let foundSubPatchOps = {};
  1176. const ops = gui.corePatch().ops;
  1177. for (let i = 0; i < ops.length; i++)
  1178. {
  1179. if (!ops[i] || !ops[i].uiAttribs) continue;
  1180. const sub = ops[i].uiAttribs.subPatch || 0;
  1181. if (ops[i].isSubPatchOp()) foundSubPatchOps[ops[i].patchId.get()] = true;
  1182. countSubs[sub] = countSubs[sub] || 0;
  1183. countSubs[sub]++;
  1184. }
  1185. for (let subid in countSubs)
  1186. {
  1187. for (let _asub in foundSubPatchOps)
  1188. {
  1189. if (!foundSubPatchOps.hasOwnProperty(subid) && subid != Patch.DEFAULT_SUBPATCHID)
  1190. {
  1191. this._log.warn("found lost subpatch...", subid);
  1192. if (countSubs[subid] <= 2)
  1193. {
  1194. this._log.warn("deleted lost subpatch! ", subid);
  1195. for (let i = ops.length - 1; i >= 0; i--)
  1196. if (ops[i].uiAttribs.subPatch == subid)
  1197. ops[i].patch.deleteOp(ops[i].id);
  1198. countSubs[subid] = 1000;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. /**
  1205. * @param {boolean} sort
  1206. */
  1207. getSubPatches(sort) // flat list
  1208. {
  1209. let foundPatchIds = [];
  1210. const foundBlueprints = {};
  1211. let subPatches = [];
  1212. const ops = gui.corePatch().ops;
  1213. for (let i = 0; i < ops.length; i++)
  1214. {
  1215. if (ops[i].uiAttribs.hidden) continue;
  1216. if (ops[i].patchId && ops[i].patchId.get() !== 0)
  1217. {
  1218. foundPatchIds.push(ops[i].patchId.get());
  1219. }
  1220. }
  1221. for (let i = 0; i < ops.length; i++)
  1222. {
  1223. if (ops[i].uiAttribs.hidden) continue;
  1224. if (ops[i].uiAttribs)
  1225. {
  1226. if (ops[i].uiAttribs.subPatch)
  1227. {
  1228. // find lost ops, which are in subpatches, but no subpatch op exists for that subpatch..... :(
  1229. if (foundPatchIds.indexOf(ops[i].uiAttribs.subPatch) === -1) foundPatchIds.push(ops[i].uiAttribs.subPatch);
  1230. }
  1231. }
  1232. if (ops[i].isSubPatchOp() == 1 && ops[i].uiAttribs)
  1233. {
  1234. foundBlueprints[ops[i].id] = ops[i];
  1235. }
  1236. }
  1237. foundPatchIds = utils.uniqueArray(foundPatchIds);
  1238. for (let i = 0; i < foundPatchIds.length; i++)
  1239. {
  1240. let found = false;
  1241. for (let j = 0; j < ops.length; j++)
  1242. {
  1243. if (ops[j].patchId && ops[j].patchId.get() == foundPatchIds[i])
  1244. {
  1245. if (ops[j].uiAttribs.hidden)
  1246. {
  1247. found = true;
  1248. break;
  1249. }
  1250. const o = {
  1251. "opId": ops[j].id,
  1252. "name": ops[j].getTitle(),
  1253. "id": foundPatchIds[i]
  1254. };
  1255. o.subPatchVer = ops[j].storage.subPatchVer;
  1256. if (ops[j].storage && ops[j].storage.blueprint)
  1257. {
  1258. found = true;
  1259. o.type = "blueprintSub";
  1260. }
  1261. o.blueprintVer = ops[j].isSubPatchOp();
  1262. subPatches.push(o);
  1263. found = true;
  1264. }
  1265. }
  1266. if (!found && foundPatchIds[i] != 0)
  1267. {
  1268. subPatches.push({
  1269. "opId": null,
  1270. "name": "Lost subpatch " + foundPatchIds[i],
  1271. "id": foundPatchIds[i],
  1272. "type": "lostsubpatch"
  1273. });
  1274. }
  1275. }
  1276. for (const blueprintId in foundBlueprints)
  1277. {
  1278. const blueprintOp = foundBlueprints[blueprintId];
  1279. const blueprintName = blueprintOp.uiAttribs.extendTitle || "loading...";
  1280. subPatches.push(
  1281. {
  1282. "name": "Blueprint: " + blueprintName,
  1283. "id": blueprintOp.uiAttribs ? blueprintOp.uiAttribs.blueprintSubpatch : null,
  1284. "opId": blueprintOp.id,
  1285. "type": "blueprint"
  1286. });
  1287. }
  1288. if (sort) subPatches = subPatches.sort(function (a, b) { return a.name.localeCompare(b.name); });
  1289. return subPatches;
  1290. }
  1291. /**
  1292. * @param {string|number} subPatchId
  1293. * @returns {UiOp}
  1294. */
  1295. getSubPatchOuterOp(subPatchId)
  1296. {
  1297. return gui.corePatch().getSubPatchOuterOp(subPatchId);
  1298. }
  1299. /**
  1300. * @param {String|Number} currentSubPatch
  1301. */
  1302. updateSubPatchBreadCrumb(currentSubPatch)
  1303. {
  1304. this._patchRenderer.greyOut = false;
  1305. if (currentSubPatch === 0) ele.hide(this._eleSubpatchNav);
  1306. else ele.show(this._eleSubpatchNav);
  1307. const names = this.getSubpatchPathArray(currentSubPatch);
  1308. let str = "<a onclick=\"gui.patchView.setCurrentSubPatch(0)\">Main</a> ";
  1309. for (let i = names.length - 1; i >= 0; i--)
  1310. {
  1311. if (i >= 0) str += "<span class=\"sparrow\">&rsaquo;</span>";
  1312. if (i == 0)
  1313. str += "<a class=\"" + names[i].type + "\" onclick=\"gui.patchView.focusSubpatchOp('" + names[i].patchid + "');\"><span class=\"icon icon-op\" style=\"vertical-align: sub;\"></span> " + names[i].name + "</a>";
  1314. else
  1315. str += "<a class=\"" + names[i].type + "\" onclick=\"gui.patchView.clickSubPatchNav('" + names[i].patchid + "');\">" + names[i].name + "</a>";
  1316. }
  1317. if (names.length > 0)
  1318. {
  1319. if (names[0].type == "blueprint_subpatch")
  1320. {
  1321. this._patchRenderer.greyOut = true;
  1322. let blueprintPatchId = names[0].blueprintPatchId;
  1323. if (!blueprintPatchId)
  1324. {
  1325. const firstBlueprint = names.find((name) => { return name.blueprintPatchId; });
  1326. if (firstBlueprint) blueprintPatchId = firstBlueprint.blueprintPatchId;
  1327. }
  1328. let bpText = "<span class=\"icon icon-external\"></span> Open patch";
  1329. let bpClick = "window.open('" + platform.getCablesUrl() + "/edit/" + blueprintPatchId + "', '_blank');";
  1330. if (gui.patchId === blueprintPatchId || gui.project().shortId === blueprintPatchId)
  1331. {
  1332. bpText = "Go to subpatch";
  1333. let subpatchId = names[0].blueprintLocalSubpatch;
  1334. if (subpatchId) bpClick = "gui.patchView.setCurrentSubPatch('" + subpatchId + "');CABLES.CMD.UI.centerPatchOps();gui.patchParamPanel.show();";
  1335. }
  1336. str += "<a style=\"margin:0;\" target=\"_blank\" onclick=\"" + bpClick + "\">" + bpText + "</a>";
  1337. gui.restriction.setMessage("blueprint", "This is a blueprint subpatch, changes will not be saved!");
  1338. }
  1339. }
  1340. else
  1341. {
  1342. gui.restriction.setMessage("blueprint", null);
  1343. }
  1344. document.getElementById("subpatch_breadcrumb").innerHTML = str;
  1345. }
  1346. /**
  1347. * @param {ClipboardEvent} e
  1348. */
  1349. clipboardCutOps(e)
  1350. {
  1351. this.clipboardCopyOps(e);
  1352. this.deleteSelectedOps();
  1353. gui.patchParamPanel.show(true);
  1354. }
  1355. /**
  1356. * @param {Op[]} selectedOps
  1357. * @param _options
  1358. */
  1359. serializeOps(selectedOps, _options = {})
  1360. {
  1361. function arrayContains(arr, obj)
  1362. {
  1363. return arr.indexOf(obj) > -1;
  1364. }
  1365. const ops = [];
  1366. const opIds = [];
  1367. for (const i in selectedOps)
  1368. {
  1369. if (selectedOps[i].storage && selectedOps[i].storage.blueprint) delete selectedOps[i].storage.blueprint;
  1370. ops.push(selectedOps[i].getSerialized());
  1371. opIds.push(selectedOps[i].id);
  1372. }
  1373. for (let i = 0; i < ops.length; i++)
  1374. {
  1375. if (ops[i].storage && ops[i].storage.ref) delete ops[i].storage.ref;
  1376. if (ops[i].uiAttribs && ops[i].uiAttribs.blueprintSubpatch2) delete ops[i].uiAttribs.blueprintSubpatch2;
  1377. if (ops[i].uiAttribs && ops[i].uiAttribs.selected) delete ops[i].uiAttribs.selected;
  1378. // remove links that are not fully copied...
  1379. if (ops[i].portsIn)
  1380. {
  1381. for (let j = 0; j < ops[i].portsIn.length; j++)
  1382. {
  1383. delete ops[i].portsIn[j].expose;
  1384. if (ops[i].portsIn[j].links)
  1385. {
  1386. let k = ops[i].portsIn[j].links.length;
  1387. while (k--)
  1388. {
  1389. if (ops[i].portsIn[j].links[k] && ops[i].portsIn[j].links[k].objIn && ops[i].portsIn[j].links[k].objOut)
  1390. {
  1391. if (!arrayContains(opIds, ops[i].portsIn[j].links[k].objIn) || !arrayContains(opIds, ops[i].portsIn[j].links[k].objOut))
  1392. {
  1393. const p = selectedOps[0].patch.getOpById(ops[i].portsIn[j].links[k].objOut).getPort(ops[i].portsIn[j].links[k].portOut);
  1394. ops[i].portsIn[j].links[k] = null;
  1395. if (p && (p.type === Port.TYPE_STRING || p.type === Port.TYPE_NUMBER))
  1396. {
  1397. ops[i].portsIn[j].value = p.get();
  1398. }
  1399. }
  1400. }
  1401. }
  1402. // numLinks += ops[i].portsIn[j].links.length;
  1403. }
  1404. }
  1405. }
  1406. if (ops[i].portsOut) for (let j = 0; j < ops[i].portsOut.length; j++)
  1407. {
  1408. delete ops[i].portsOut[j].expose;
  1409. if (ops[i].portsOut[j].links)
  1410. {
  1411. let k = ops[i].portsOut[j].links.length;
  1412. while (k--)
  1413. {
  1414. if (ops[i].portsOut[j].links[k] && ops[i].portsOut[j].links[k].objIn && ops[i].portsOut[j].links[k].objOut)
  1415. {
  1416. if (!arrayContains(opIds, ops[i].portsOut[j].links[k].objIn) || !arrayContains(opIds, ops[i].portsOut[j].links[k].objOut))
  1417. {
  1418. const p = selectedOps[0].patch.getOpById(ops[i].portsOut[j].links[k].objOut).getPort(ops[i].portsOut[j].links[k].portOut);
  1419. ops[i].portsOut[j].links[k] = null;
  1420. if (p && (p.type === Port.TYPE_STRING || p.type === Port.TYPE_NUMBER))
  1421. {
  1422. ops[i].portsOut[j].value = p.get();
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. }
  1430. return { "ops": ops };
  1431. }
  1432. /**
  1433. * @param {ClipboardEvent} e
  1434. */
  1435. clipboardCopyOps(e)
  1436. {
  1437. let selectedOps = this.getSelectedOps();
  1438. const ser = this.serializeOps(selectedOps);
  1439. const ops = ser.ops;
  1440. ops.forEach((op) =>
  1441. {
  1442. op.objName = gui.serverOps.getOpNameByIdentifier(op.opId);
  1443. });
  1444. const objStr = JSON.stringify({
  1445. "ops": ops
  1446. });
  1447. notify("Copied " + ops.length + " ops");
  1448. e.clipboardData.setData("text/plain", objStr);
  1449. e.preventDefault();
  1450. }
  1451. /**
  1452. * @param {ClipboardEvent} e
  1453. * @param {String} oldSub
  1454. * @param {Number} mouseX
  1455. * @param {Number} mouseY
  1456. * @param {Function} [next]
  1457. */
  1458. clipboardPaste(e, oldSub = "0", mouseX = 0, mouseY = 0, next = null)
  1459. {
  1460. const currentSubPatch = this.getCurrentSubPatch();
  1461. this.isPasting = true;
  1462. if (e.clipboardData.types.indexOf("text/plain") == -1)
  1463. {
  1464. // this._log.error("clipboard not type text");
  1465. // notifyError("Paste failed");
  1466. return;
  1467. }
  1468. let str = e.clipboardData.getData("text/plain");
  1469. e.preventDefault();
  1470. str = str.replace("```", "");
  1471. str = str.replace("```", "");
  1472. let pastedJson = null;
  1473. try
  1474. {
  1475. pastedJson = JSON.parse(str);
  1476. this.currentOpPaste = pastedJson;
  1477. }
  1478. catch (exp)
  1479. {
  1480. this._log.warn("pasting failed...");
  1481. }
  1482. if (this.newPatchOpPaste && this.newPatchOpPaste == str)
  1483. {
  1484. return;
  1485. }
  1486. this.newPatchOpPaste = null;
  1487. const undoGroup = undo.startGroup();
  1488. if (!pastedJson || !pastedJson.ops) return;
  1489. if (currentSubPatch)
  1490. {
  1491. const subOuter = gui.patchView.getSubPatchOuterOp(currentSubPatch);
  1492. if (subOuter && subOuter.objName)
  1493. {
  1494. for (let i = 0; i < pastedJson.ops.length; i++)
  1495. {
  1496. const pastedOp = pastedJson.ops[i];
  1497. if (pastedOp.objName)
  1498. {
  1499. const pasteProblem = namespace.getNamespaceHierarchyProblem(subOuter.objName, pastedOp.objName);
  1500. if (pasteProblem)
  1501. {
  1502. notifyError("Paste failed", pasteProblem, { "force": true });
  1503. return;
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }
  1509. /** @type {Op} */
  1510. let focusSubpatchop = null;
  1511. gui.serverOps.loadProjectDependencies(pastedJson, (project, newOps) =>
  1512. {
  1513. // change ids
  1514. project = Patch.replaceOpIds(project, { "parentSubPatchId": oldSub });
  1515. for (const i in project.ops)
  1516. {
  1517. project.ops[i].uiAttribs.pasted = true;
  1518. }
  1519. { // change position of ops to paste
  1520. let minx = Number.MAX_VALUE;
  1521. let miny = Number.MAX_VALUE;
  1522. for (const i in project.ops)
  1523. {
  1524. if (project.ops[i].uiAttribs && project.ops[i].uiAttribs && project.ops[i].uiAttribs.translate && project.ops[i].uiAttribs.subPatch == this.getCurrentSubPatch())
  1525. {
  1526. minx = Math.min(minx, project.ops[i].uiAttribs.translate.x);
  1527. miny = Math.min(miny, project.ops[i].uiAttribs.translate.y);
  1528. }
  1529. }
  1530. for (const i in project.ops)
  1531. {
  1532. if (project.ops[i].uiAttribs && project.ops[i].uiAttribs && project.ops[i].uiAttribs.translate)
  1533. {
  1534. let x = project.ops[i].uiAttribs.translate.x + mouseX - minx;
  1535. let y = project.ops[i].uiAttribs.translate.y + mouseY - miny;
  1536. if (userSettings.get(UserSettings.PREF_SNAPTOGRID))
  1537. {
  1538. x = Snap.snapOpPosX(x);
  1539. y = Snap.snapOpPosY(y);
  1540. }
  1541. project.ops[i].uiAttribs.translate.x = x;
  1542. project.ops[i].uiAttribs.translate.y = y;
  1543. }
  1544. (function (opid)
  1545. {
  1546. undo.add({
  1547. "title": "paste op",
  1548. "undo": function ()
  1549. {
  1550. gui.corePatch().deleteOp(opid, true);
  1551. },
  1552. "redo": function ()
  1553. {
  1554. gui.patchView.clipboardPaste(e);
  1555. }
  1556. });
  1557. }(project.ops[i].id));
  1558. }
  1559. }
  1560. notify("Pasted " + project.ops.length + " ops");
  1561. if (newOps && newOps.length > 0)
  1562. {
  1563. let notifyText = "Created " + newOps.length + " patch op";
  1564. if (newOps.length > 1) notifyText += "s";
  1565. notifyWarn(notifyText, "clipboard cleared");
  1566. }
  1567. gui.corePatch().deSerialize(project);
  1568. this.isPasting = false;
  1569. if (focusSubpatchop) this.patchRenderer.focusOpAnim(focusSubpatchop.id);
  1570. this.currentOpPaste = null;
  1571. if (next) next(project.ops, focusSubpatchop);
  1572. });
  1573. undo.endGroup(undoGroup, "Paste");
  1574. this.setCurrentSubPatch(currentSubPatch);
  1575. this.unselectOpsFromOtherSubpatches();
  1576. }
  1577. duplicateSelectedOps()
  1578. {
  1579. const selectedOps = this.getSelectedOps();
  1580. if (selectedOps.length == 0) return;
  1581. const externalLinks = [];
  1582. for (let i = 0; i < selectedOps.length; i++)
  1583. {
  1584. const ports = selectedOps[i].portsIn.concat(selectedOps[i].portsOut);
  1585. for (let j = 0; j < ports.length; j++)
  1586. {
  1587. for (let k = 0; k < ports[j].links.length; k++)
  1588. {
  1589. const otherPort = ports[j].links[k].getOtherPort(ports[j]);
  1590. if (!otherPort || selectedOps.includes(otherPort.op)) continue;
  1591. if (otherPort.direction == Port.DIR_IN && otherPort.type != Port.TYPE_TRIGGER) continue;
  1592. externalLinks.push({ "opId": selectedOps[i].id, "portName": ports[j].name, "otherPort": otherPort });
  1593. }
  1594. }
  1595. }
  1596. const bounds = this.getSelectionBounds(0);
  1597. const offsetX = this.patchRenderer.viewBox.mousePatchX - bounds.minX;
  1598. const offsetY = this.patchRenderer.viewBox.mousePatchY - bounds.minY;
  1599. const ser = this.serializeOps(selectedOps);
  1600. const oldIds = [];
  1601. for (let i = 0; i < ser.ops.length; i++)
  1602. {
  1603. ser.ops[i].objName = gui.serverOps.getOpNameByIdentifier(ser.ops[i].opId);
  1604. oldIds.push(ser.ops[i].id);
  1605. }
  1606. Patch.replaceOpIds(ser, { "parentSubPatchId": this.getCurrentSubPatch() });
  1607. const newIds = {};
  1608. for (let i = 0; i < ser.ops.length; i++)
  1609. {
  1610. newIds[oldIds[i]] = ser.ops[i].id;
  1611. ser.ops[i].uiAttribs.pasted = true;
  1612. if (ser.ops[i].uiAttribs.translate)
  1613. {
  1614. let x = ser.ops[i].uiAttribs.translate.x + offsetX;
  1615. let y = ser.ops[i].uiAttribs.translate.y + offsetY;
  1616. if (userSettings.get(UserSettings.PREF_SNAPTOGRID))
  1617. {
  1618. x = Snap.snapOpPosX(x);
  1619. y = Snap.snapOpPosY(y);
  1620. }
  1621. ser.ops[i].uiAttribs.translate.x = x;
  1622. ser.ops[i].uiAttribs.translate.y = y;
  1623. }
  1624. }
  1625. const undoGroup = undo.startGroup();
  1626. this._p.deSerialize(ser);
  1627. for (let i = 0; i < externalLinks.length; i++)
  1628. {
  1629. const newOp = this._p.getOpById(newIds[externalLinks[i].opId]);
  1630. const otherPort = externalLinks[i].otherPort;
  1631. if (newOp) this._p.link(newOp, externalLinks[i].portName, otherPort.op, otherPort.name);
  1632. }
  1633. const originalIds = [];
  1634. for (let i = 0; i < selectedOps.length; i++) originalIds.push(selectedOps[i].id);
  1635. undo.add({
  1636. "title": "duplicate ops",
  1637. "undo": () =>
  1638. {
  1639. for (const oldId in newIds) this._p.deleteOp(newIds[oldId], true);
  1640. },
  1641. "redo": () =>
  1642. {
  1643. this.patchRenderer.unselectAll();
  1644. for (let i = 0; i < originalIds.length; i++) this.patchRenderer.selectOpId(originalIds[i]);
  1645. this.duplicateSelectedOps();
  1646. }
  1647. });
  1648. undo.endGroup(undoGroup, "Duplicate");
  1649. this.patchRenderer.unselectAll();
  1650. for (const oldId in newIds) this.patchRenderer.selectOpId(newIds[oldId]);
  1651. notify("Duplicated " + ser.ops.length + " ops");
  1652. }
  1653. addSpaceBetweenOpsX()
  1654. {
  1655. const bounds = this.getSelectionBounds(0);
  1656. const ops = gui.patchView.getSelectedOps();
  1657. const centerX = (bounds.minX + bounds.maxX) / 2;
  1658. const undoGroup = undo.startGroup();
  1659. for (let j = 0; j < ops.length; j++)
  1660. {
  1661. const diffX = ops[j].uiAttribs.translate.x - centerX;
  1662. this.setOpPos(ops[j], Snap.snapOpPosX(centerX + (diffX * 1.2)), ops[j].uiAttribs.translate.y);
  1663. }
  1664. undo.endGroup(undoGroup, "add space x");
  1665. }
  1666. addSpaceBetweenOpsY()
  1667. {
  1668. const bounds = this.getSelectionBounds(0);
  1669. const ops = gui.patchView.getSelectedOps();
  1670. const centerY = (bounds.minY + bounds.maxY) / 2;
  1671. const undoGroup = undo.startGroup();
  1672. for (let j = 0; j < ops.length; j++)
  1673. {
  1674. const diffY = ops[j].uiAttribs.translate.y - centerY;
  1675. this.setOpPos(ops[j], ops[j].uiAttribs.translate.x, Snap.snapOpPosY(centerY + (diffY * 1.8)));
  1676. }
  1677. undo.endGroup(undoGroup, "add space y");
  1678. }
  1679. /**
  1680. * @param {UiOp[]} ops
  1681. */
  1682. compressSelectedOps(ops)
  1683. {
  1684. if (!ops || ops.length === 0) return;
  1685. const undoGroup = undo.startGroup();
  1686. this.saveUndoSelectedOpsPositions(ops);
  1687. this.cleanOps(ops);
  1688. undo.endGroup(undoGroup, "Compress Ops");
  1689. }
  1690. /**
  1691. * @param {UiOp[]} ops
  1692. */
  1693. tidyUpOps(ops)
  1694. {
  1695. if (!ops || ops.length === 0) ops = gui.corePatch().getSubPatchOps(this.getCurrentSubPatch());
  1696. const layoutOps = [];
  1697. for (const op of ops)
  1698. if (op.uiAttribs.translate && this.patchRenderer.getGlOp(op)) layoutOps.push(op);
  1699. if (layoutOps.length === 0) return;
  1700. const layout = new PatchLayout(this.patchRenderer);
  1701. const pos = layout.layout(layoutOps, gui.corePatch().getSubPatchOps(this.getCurrentSubPatch()));
  1702. if (typeof pos == "string") return notifyWarn("Could not tidy up ops", pos);
  1703. this.patchRenderer.subPatchOpAnimStart(this.getOpBounds(layoutOps), () =>
  1704. {
  1705. const undoGroup = undo.startGroup();
  1706. for (const op of pos.keys())
  1707. {
  1708. const p = pos.get(op);
  1709. if (op.uiAttribs.translate.x != p.x || op.uiAttribs.translate.y != p.y) this.setOpPos(op, p.x, p.y);
  1710. }
  1711. undo.endGroup(undoGroup, "Tidy up ops");
  1712. this.patchRenderer.subPatchOpAnimEndBounds(this.getOpBounds(layoutOps));
  1713. this.centerView();
  1714. });
  1715. }
  1716. /**
  1717. * @param {Op[]} ops
  1718. */
  1719. cleanOps(ops)
  1720. {
  1721. new opCleaner(ops, this.patchRenderer);
  1722. }
  1723. /**
  1724. * @param {UiOp[]} ops
  1725. */
  1726. alignSelectedOpsVert(ops)
  1727. {
  1728. if (ops.length == 1)
  1729. {
  1730. const op = ops[0];
  1731. if (op.getFirstPortIn() && op.getFirstPortIn().links.length)
  1732. {
  1733. const pre = op.getFirstPortIn().links[0].portOut.op;
  1734. if (pre.uiAttribs.translate && op.uiAttribs.translate)
  1735. op.setUiAttrib({ "translate": { "x": pre.uiAttribs.translate.x, "y": op.uiAttribs.translate.y } });
  1736. }
  1737. }
  1738. if (ops.length > 0)
  1739. {
  1740. let sum = 0;
  1741. for (const j in ops) sum += ops[j].uiAttribs.translate.x;
  1742. let avg = sum / ops.length;
  1743. if (userSettings.get(UserSettings.PREF_SNAPTOGRID)) avg = Snap.snapOpPosX(avg);
  1744. for (const j in ops) this.setOpPos(ops[j], avg, ops[j].uiAttribs.translate.y);
  1745. }
  1746. return ops;
  1747. }
  1748. /**
  1749. * @param {Op[]} ops
  1750. */
  1751. alignSelectedOpsHor(ops)
  1752. {
  1753. if (ops.length > 0)
  1754. {
  1755. let sum = 0;
  1756. for (const j in ops) sum += ops[j].uiAttribs.translate.y;
  1757. let avg = sum / ops.length;
  1758. if (userSettings.get(UserSettings.PREF_SNAPTOGRID)) avg = Snap.snapOpPosY(avg);
  1759. for (const j in ops) this.setOpPos(ops[j], ops[j].uiAttribs.translate.x, avg);
  1760. }
  1761. return ops;
  1762. }
  1763. /**
  1764. * @param {UiOp} opBelow
  1765. * @param {UiOp} opAbove
  1766. */
  1767. alignOpBelowOp(opBelow, opAbove)
  1768. {
  1769. let y = opAbove.uiAttribs.translate.y + 0;
  1770. opBelow.setUiAttribs({ "translate": { "x": opAbove.uiAttribs.translate.x, "y": y } });
  1771. this.testCollision(opBelow);
  1772. }
  1773. /**
  1774. * @param {UiOp | Op} op
  1775. * @param {number} x
  1776. * @param {number} y
  1777. */
  1778. setOpPos(op, x, y)
  1779. {
  1780. if (op && op.uiAttribs && op.uiAttribs.translate)
  1781. {
  1782. const oldX = op.uiAttribs.translate.x;
  1783. const oldY = op.uiAttribs.translate.y;
  1784. undo.add({
  1785. "title": "Move op",
  1786. "context": {
  1787. "opname": op.name
  1788. },
  1789. "undo": function ()
  1790. {
  1791. op.setUiAttribs({ "translate": { "x": oldX, "y": oldY } });
  1792. },
  1793. "redo": function ()
  1794. {
  1795. op.setUiAttribs({ "translate": { "x": x, "y": y } });
  1796. }
  1797. });
  1798. }
  1799. op.setUiAttribs({
  1800. "translate":
  1801. {
  1802. "x": x,
  1803. "y": y
  1804. }
  1805. });
  1806. }
  1807. /**
  1808. * @param {UiOp[]} selectedOps
  1809. */
  1810. saveUndoSelectedOpsPositions(selectedOps)
  1811. {
  1812. const opPositions = [];
  1813. for (let j = 0; j < selectedOps.length; j++)
  1814. {
  1815. const obj = {};
  1816. obj.id = selectedOps[j].id;
  1817. if (!selectedOps[j].uiAttribs) selectedOps[j].uiAttribs = {};
  1818. if (!selectedOps[j].uiAttribs.translate) selectedOps[j].uiAttribs.translate = { "x": 0, "y": 0 };
  1819. obj.x = selectedOps[j].uiAttribs.translate.x;
  1820. obj.y = selectedOps[j].uiAttribs.translate.y;
  1821. opPositions.push(obj);
  1822. }
  1823. undo.add({
  1824. "title": "save op positions",
  1825. "undo": function ()
  1826. {
  1827. const changedOps = [];
  1828. for (let j = 0; j < opPositions.length; j++)
  1829. {
  1830. const obj = opPositions[j];
  1831. const op = gui.corePatch().getOpById(obj.id);
  1832. gui.patchView.setOpPos(op, obj.x, obj.y);
  1833. changedOps.push(op);
  1834. }
  1835. },
  1836. "redo": function ()
  1837. {
  1838. // gui.scene().addOp(objName, op.uiAttribs, opid);
  1839. }
  1840. });
  1841. }
  1842. alignOps(selectedOps)
  1843. {
  1844. const undoGroup = undo.startGroup();
  1845. this.saveUndoSelectedOpsPositions(selectedOps);
  1846. this.alignSelectedOpsVert(selectedOps);
  1847. undo.endGroup(undoGroup, "Align Ops");
  1848. return selectedOps;
  1849. }
  1850. unlinkPort(opid, portid)
  1851. {
  1852. const op = gui.corePatch().getOpById(opid);
  1853. const p = op.getPortById(portid);
  1854. if (!p)
  1855. {
  1856. this._log.warn("[unlinkport] portnot found ");
  1857. return;
  1858. }
  1859. const undoGroup = undo.startGroup();
  1860. p.removeLinks();
  1861. undo.endGroup(undoGroup, "Unlink Port");
  1862. }
  1863. /**
  1864. * @param {MouseEvent} e
  1865. * @param {string} opid
  1866. * @param {string} pid
  1867. * @param {string} op2id
  1868. */
  1869. linkPortToOp(e, opid, pid, op2id)
  1870. {
  1871. let op1 = /** @type {UiOp} */ (this._p.getOpById(opid));
  1872. let op2 = /** @type {UiOp} */ (this._p.getOpById(op2id));
  1873. const p = op1.getPort(pid);
  1874. let showConverter = gui.longLinkHover;
  1875. let numPerfectFit = op2.countFittingPorts(p, false);
  1876. let numFitting = op2.countFittingPorts(p, showConverter);
  1877. if (numFitting == 0 && !showConverter)
  1878. {
  1879. showConverter = true;
  1880. numFitting = op2.countFittingPorts(p, true);
  1881. }
  1882. const isInnerOp = op2.objName == defaultOps.defaultOpNames.subPatchInput2 || op2.objName == defaultOps.defaultOpNames.subPatchOutput2;
  1883. const isbpOp = op2.isSubPatchOp() || isInnerOp;
  1884. if (isbpOp || (numFitting > 0 && numPerfectFit != 1))
  1885. {
  1886. new SuggestPortDialog(op2, p, e, (thePort, newOpId, options, useconverter) =>
  1887. {
  1888. if (options.createSpOpPort)
  1889. {
  1890. subPatchOpUtil.addPortToBlueprint(options.op.opId, p, {
  1891. "reverseDir": !isInnerOp,
  1892. "cb": (newPortJson, newOp, sugg) =>
  1893. {}
  1894. });
  1895. }
  1896. else
  1897. {
  1898. op2 = /** @type {UiOp} */ (this._p.getOpById(newOpId));
  1899. if (Link.canLink(thePort, p))
  1900. {
  1901. this._p.link(op1, pid, op2, thePort.name);
  1902. }
  1903. else
  1904. {
  1905. gui.patchView.linkPorts(opid, pid, op2id, thePort.id, e);
  1906. }
  1907. }
  1908. }, null, showConverter);
  1909. }
  1910. else
  1911. {
  1912. const fitp = op2.findFittingPort(p, showConverter);
  1913. if (fitp)
  1914. {
  1915. if (fitp.type == p.type) this._p.link(op1, pid, op2, fitp.name);
  1916. else gui.patchView.linkPorts(opid, p.name, op2id, fitp.name, e);
  1917. }
  1918. else
  1919. {
  1920. console.log("no fitp");
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * @param {MouseEvent} e
  1926. * @param {string} opid
  1927. * @param {string[]} opids
  1928. * @param {string[]} portnames
  1929. * @param {boolean} showConverters
  1930. */
  1931. linkPortsToOp(e, opid, opids, portnames, showConverters = false)
  1932. {
  1933. if (!opids || opids.length == 0 || !portnames || portnames.length == 0) return;
  1934. const op1 = this._p.getOpById(opid);
  1935. let op2 = this._p.getOpById(opids[0]);
  1936. const p = op2.getPort(portnames[0]);
  1937. const numFitting = op1.countFittingPorts(p, showConverters);
  1938. if (numFitting > 1)
  1939. {
  1940. new SuggestPortDialog(op1, p, e, (suggport) =>
  1941. {
  1942. if (suggport)
  1943. for (let i = 0; i < portnames.length; i++)
  1944. {
  1945. op2 = this._p.getOpById(opids[i]);
  1946. this._p.link(op2, portnames[i], op1, suggport.id);
  1947. }
  1948. }, null, true);
  1949. }
  1950. else
  1951. {
  1952. const fitp = op1.findFittingPort(p, showConverters);
  1953. if (fitp)
  1954. for (let i = 0; i < portnames.length; i++)
  1955. {
  1956. op2 = this._p.getOpById(opids[i]);
  1957. this._p.link(op2, portnames[i], op1, fitp.name);
  1958. }
  1959. }
  1960. }
  1961. /**
  1962. * @param {string} opid
  1963. * @param {string} pid
  1964. * @param {string} op2id
  1965. * @param {string} p2id
  1966. * @param {MouseEvent} event
  1967. */
  1968. linkPorts(opid, pid, op2id, p2id, event)
  1969. {
  1970. /** @type {Op} */
  1971. let op1 = this._p.getOpById(opid);
  1972. /** @type {Op} */
  1973. let op2 = this._p.getOpById(op2id);
  1974. if (!op1 || !op2)
  1975. {
  1976. console.log("no linkop");
  1977. return;
  1978. }
  1979. // helper number2string auto insert....
  1980. let p1 = op1.getPortByName(pid);
  1981. let p2 = op2.getPortByName(p2id);
  1982. let pInput = p1;
  1983. let pOutput = p2;
  1984. if (!p1) return;
  1985. if (p1.direction == Port.DIR_OUT)
  1986. {
  1987. pInput = p2;
  1988. pOutput = p1;
  1989. }
  1990. const converters = getConverters(p1, p2);
  1991. if (converters.length == 1)
  1992. {
  1993. convertPorts(p1, p2, converters[0]);
  1994. return;
  1995. }
  1996. if (converters.length > 1)
  1997. {
  1998. const suggs = [];
  1999. for (let i = 0; i < converters.length; i++)
  2000. {
  2001. let convStr =
  2002. "<span style=\"pointer-events:none\" class=\"" + "port_text_color_" + pOutput.getTypeString().toLowerCase() + "\">▐ →</span> " +
  2003. "<span style=\"pointer-events:none\" class=\"" + "port_text_color_" + pInput.getTypeString().toLowerCase() + "\">▌</span>";
  2004. suggs.push({
  2005. "name": convStr + opNames.getShortName(converters[i].op),
  2006. "class": "port_text_color_" + p2.getTypeString().toLowerCase()
  2007. });
  2008. }
  2009. new SuggestionDialog(suggs, op2, event, null, function (sid)
  2010. {
  2011. convertPorts(p1, p2, converters[sid]);
  2012. });
  2013. return;
  2014. }
  2015. this._p.link(op1, pid, op2, p2id);
  2016. }
  2017. /**
  2018. * @param {number} [x]
  2019. * @param {number} [y]
  2020. */
  2021. centerView(x, y)
  2022. {
  2023. if (this._patchRenderer)
  2024. if (this._patchRenderer.center) this._patchRenderer.center(x, y);
  2025. else this._log.warn("patchRenderer has no function center");
  2026. }
  2027. pauseInteraction()
  2028. {
  2029. this._patchRenderer.pauseInteraction();
  2030. }
  2031. resumeInteraction()
  2032. {
  2033. this._patchRenderer.resumeInteraction();
  2034. }
  2035. /** @returns {String} */
  2036. getCurrentSubPatch()
  2037. {
  2038. return this._patchRenderer.getCurrentSubPatch();
  2039. }
  2040. serialize(dataUi)
  2041. {
  2042. this._patchRenderer.serialize(dataUi);
  2043. }
  2044. /**
  2045. * @param {string} subpatch
  2046. * @param {Function} [next]
  2047. */
  2048. setCurrentSubPatch(subpatch, next)
  2049. {
  2050. const curSub = this.getCurrentSubPatch();
  2051. if (curSub != subpatch)
  2052. {
  2053. gui.restriction.setMessage("subpatchref", null);
  2054. if (subpatch != Patch.DEFAULT_SUBPATCHID)
  2055. {
  2056. const outerOp = this.getSubPatchOuterOp(subpatch);
  2057. const ops = gui.savedState.getUnsavedPatchSubPatchOps();
  2058. for (let i = 0; i < ops.length; i++)
  2059. {
  2060. if (ops[i].op && outerOp && ops[i].op.opId == outerOp.opId && ops[i].op != outerOp)
  2061. {
  2062. let subid = ops[i].subId;
  2063. gui.restriction.setMessage("subpatchref", "changed reference in patch: a unsaved reference of this subpatch ops exists in your patch. <br/>saving this can will overwrite references!<br/><a class='link' onclick='gui.patchView.setCurrentSubPatch(\"" + subid + "\")'>goto patch</a>");
  2064. }
  2065. }
  2066. }
  2067. if (this._patchRenderer.setCurrentSubPatch)
  2068. {
  2069. this._patchRenderer.setCurrentSubPatch(subpatch,
  2070. () =>
  2071. {
  2072. gui.patchView.updateSubPatchBreadCrumb(subpatch);
  2073. if (ele.byId("subpatchlist")) this.showDefaultPanel(); // update subpatchlist because its already visible
  2074. if (next) next();
  2075. });
  2076. }
  2077. else this._log.warn("patchRenderer has no function setCurrentSubPatch");
  2078. gui.corePatch().emitEvent("subpatchesChanged");
  2079. }
  2080. }
  2081. getLastFocussedOp()
  2082. {
  2083. return gui.opParams.getCurrentOp();
  2084. }
  2085. /**
  2086. * @param {string} opId
  2087. * @param {GotoOpOptions} [options]
  2088. */
  2089. gotoOp(opId, options = {})
  2090. {
  2091. if (this._patchRenderer.gotoOp) this._patchRenderer.gotoOp(opId, options);
  2092. else this._log.warn("patchRenderer has no function gotoOp");
  2093. }
  2094. /**
  2095. * @param {string} opid
  2096. */
  2097. focusOp(opid)
  2098. {
  2099. if (this._patchRenderer.focusOp) this._patchRenderer.focusOp(opid);
  2100. else this._log.warn("patchRenderer has no function focusOp");
  2101. }
  2102. unselectAllOps()
  2103. {
  2104. for (let i = 0; i < this._p.ops.length; i++)
  2105. if (this._p.ops[i].uiAttribs.selected) this._p.ops[i].setUiAttribs({ "selected": false });
  2106. }
  2107. unselectOpsFromOtherSubpatches()
  2108. {
  2109. const ops = this.getSelectedOps();
  2110. for (let i = 0; i < ops.length; i++)
  2111. if (ops[i].uiAttribs.subPatch != this.getCurrentSubPatch())
  2112. ops[i].setUiAttribs({ "selected": false });
  2113. }
  2114. /**
  2115. * @param {String} id
  2116. */
  2117. selectOpId(id)
  2118. {
  2119. const op = this._p.getOpById(id);
  2120. if (op) op.setUiAttribs({ "selected": true });
  2121. }
  2122. /**
  2123. * @param {String} opid
  2124. */
  2125. centerSelectOp(opid)
  2126. {
  2127. this.setSelectedOpById(opid);
  2128. this._patchRenderer.viewBox.centerSelectedOps();
  2129. if (gui.patchView.getSelectedOps().length == 1) this.focusOpAnim(gui.patchView.getSelectedOps()[0].id);
  2130. this.focus();
  2131. }
  2132. /**
  2133. * @param {String} opid
  2134. */
  2135. setSelectedOpById(opid)
  2136. {
  2137. if (this._patchRenderer.setSelectedOpById) this._patchRenderer.setSelectedOpById(opid);
  2138. // else if (this._patchRenderer.selectOpId) this._patchRenderer.selectOpId(opid);
  2139. else this._log.warn("patchRenderer has no function setSelectedOpById");
  2140. }
  2141. /**
  2142. * @param {String} id
  2143. */
  2144. selectChilds(id)
  2145. {
  2146. const op = gui.corePatch().getOpById(id);
  2147. op.selectChilds();
  2148. }
  2149. setUnsaved()
  2150. {
  2151. // gui.setStateUnsaved({ "subPatch": this.getCurrentSubPatch });
  2152. // gui.savedState.setUnSaved("patchview??", this.getCurrentSubPatch());
  2153. gui.savedState.setUnSaved("patchview??");
  2154. }
  2155. /**
  2156. * @param {Port} p1
  2157. * @param {Port} p2
  2158. */
  2159. _portValidate(p1, p2)
  2160. {
  2161. if (p1.type != Port.TYPE_OBJECT) return;
  2162. let inp = null;
  2163. let outp = null;
  2164. if (p1.direction === Port.DIR_IN)
  2165. {
  2166. inp = p1;
  2167. outp = p2;
  2168. }
  2169. else
  2170. {
  2171. inp = p2;
  2172. outp = p1;
  2173. }
  2174. const id = "_validator" + inp.name;
  2175. inp.op.setUiError(id, null);
  2176. if (!inp.isLinked()) return;
  2177. if (inp.uiAttribs.ignoreObjTypeErrors) return;
  2178. if (outp.get() == null) return;
  2179. if (p1.uiAttribs.objType && p2.uiAttribs.objType)
  2180. {
  2181. if (p1.uiAttribs.objType == p2.uiAttribs.objType) return;
  2182. if (p1.uiAttribs.objType.indexOf("sg_") == 0 && p2.uiAttribs.objType.indexOf("sg_") == 0) return;
  2183. }
  2184. const errorMsg = "Object in port <b>" + inp.name + "</b> is not of type " + inp.uiAttribs.objType;
  2185. const lvl = 1;
  2186. // check if both have defined objtype
  2187. if (p1.uiAttribs.objType && p2.uiAttribs.objType && p1.uiAttribs.objType != p2.uiAttribs.objType)
  2188. {
  2189. inp.op.setUiError(id, errorMsg, lvl);
  2190. return;
  2191. }
  2192. // validate by object value
  2193. if (inp.uiAttribs.objType && outp.get())
  2194. {
  2195. if (inp.uiAttribs.objType == "texture" && !(outp.get() instanceof WebGLTexture)) inp.op.setUiError(id, errorMsg, lvl);
  2196. if (inp.uiAttribs.objType == "geometry" && !(outp.get() instanceof Geometry)) inp.op.setUiError(id, errorMsg, lvl);
  2197. if (inp.uiAttribs.objType == "shader" && !(outp.get() instanceof Shader)) inp.op.setUiError(id, errorMsg, lvl);
  2198. if (inp.uiAttribs.objType == "element" && !(outp.get() instanceof Element)) inp.op.setUiError(id, errorMsg, lvl);
  2199. // * audio
  2200. if (inp.uiAttribs.objType == "audioBuffer" && !(outp.get() instanceof AudioBuffer)) inp.op.setUiError(id, errorMsg, lvl);
  2201. if (inp.uiAttribs.objType == "audioNode" && !(outp.get() instanceof AudioNode)) inp.op.setUiError(id, errorMsg, lvl);
  2202. }
  2203. }
  2204. /**
  2205. * @param {Port} p1
  2206. * @param {Port} p2
  2207. */
  2208. refreshCurrentOpParamsByPort(p1, p2)
  2209. {
  2210. if (this.isCurrentOp(p2.op) || this.isCurrentOp(p1.op)) gui.opParams.refresh();
  2211. }
  2212. /**
  2213. * @param {Op} op
  2214. */
  2215. isCurrentOp(op)
  2216. {
  2217. return gui.opParams.isCurrentOp(op);
  2218. }
  2219. /**
  2220. * @param {string} opid
  2221. */
  2222. isCurrentOpId(opid)
  2223. {
  2224. return gui.opParams.isCurrentOpId(opid);
  2225. }
  2226. /**
  2227. * @param {UiOp} origOp
  2228. * @param {UiOp} newOp
  2229. */
  2230. copyOpInputPorts(origOp, newOp)
  2231. {
  2232. for (let i = 0; i < origOp.portsIn.length; i++)
  2233. {
  2234. for (let j = 0; j < newOp.portsIn.length; j++)
  2235. {
  2236. if (newOp.portsIn[j].name.toLowerCase() == origOp.portsIn[i].name.toLowerCase())
  2237. {
  2238. newOp.portsIn[j].set(origOp.portsIn[i].get());
  2239. if (origOp.portsIn[i].anim)
  2240. {
  2241. newOp.portsIn[j].setAnimated(true);
  2242. newOp.portsIn[j].anim.clear();
  2243. newOp.portsIn[j].anim.deserialize(origOp.portsIn[j].anim.getSerialized());
  2244. }
  2245. }
  2246. }
  2247. }
  2248. }
  2249. /**
  2250. * @param {string} opid
  2251. * @param {string} opname
  2252. */
  2253. downGradeOp(opid, opname)
  2254. {
  2255. if (!gui.opDocs.getOpDocByName(opname))
  2256. {
  2257. notify("op has no versions....");
  2258. return;
  2259. }
  2260. const versions = gui.opDocs.getOpDocByName(opname).versions;
  2261. if (versions.length > 1)
  2262. {
  2263. let name = versions[0].name;
  2264. for (let i = 0; i < versions.length; i++)
  2265. {
  2266. if (versions[i].name == opname) break;
  2267. name = versions[i].name;
  2268. }
  2269. this.replaceOp(opid, name);
  2270. }
  2271. else
  2272. {
  2273. notify("could not downgrade: has no previous version");
  2274. }
  2275. this.unselectAllOps();
  2276. }
  2277. /**
  2278. * @param {string} opid
  2279. * @param {string} newOpObjName
  2280. */
  2281. replaceOpCheck(opid, newOpObjName)
  2282. {
  2283. gui.serverOps.loadOpDependencies(newOpObjName, () =>
  2284. {
  2285. this.addOp(newOpObjName, {
  2286. "onOpAdd": (newOp) =>
  2287. {
  2288. const origOp = this._p.getOpById(opid);
  2289. if (!newOp || !origOp)
  2290. {
  2291. this._log.warn("could not replace op.?", newOp, origOp);
  2292. return;
  2293. }
  2294. let allFine = true;
  2295. let html = "<h3>Replacing Op</h3>";
  2296. html += "Replacing <b>" + origOp.objName + "</b> with <b>" + newOp.objName + "</b><br/><br/>";
  2297. let htmlList = "";
  2298. htmlList += "<table>";
  2299. for (let i = 0; i < origOp.portsIn.length; i++)
  2300. {
  2301. let found = false;
  2302. htmlList += "<tr>";
  2303. htmlList += "<td>Port " + origOp.portsIn[i].name + "</td>";
  2304. for (let j = 0; j < newOp.portsIn.length; j++)
  2305. {
  2306. if (newOp.portsIn[j] && origOp.portsIn[i])
  2307. {
  2308. if (newOp.portsIn[j].name.toLowerCase() == origOp.portsIn[i].name.toLowerCase())
  2309. {
  2310. found = true;
  2311. break;
  2312. }
  2313. }
  2314. }
  2315. htmlList += "<td>";
  2316. if (!found)
  2317. {
  2318. htmlList += "NOT FOUND in new version!";
  2319. allFine = false;
  2320. }
  2321. htmlList += "</td>";
  2322. htmlList += "</tr>";
  2323. }
  2324. this._p.deleteOp(newOp.id);
  2325. htmlList += "</table>";
  2326. if (allFine)
  2327. {
  2328. gui.patchView.replaceOp(opid, newOpObjName);
  2329. return;
  2330. // html += "All old ports are available in the new op, it should be safe to replace with new version. Make sure you test if it behaves the same, very accurately.<br/><br/>";
  2331. }
  2332. else
  2333. {
  2334. html += "Not all old Ports are available in never version of the op. Make sure you test if it behaves the same, very accurately.<br/><br/>";
  2335. html += htmlList;
  2336. }
  2337. // html += "<br/><a onClick=\"\" class=\"bluebutton\">Really Upgrade</a>";
  2338. // html += "<a onClick=\"gui.closeModal();\" class=\"cblbutton\">Cancel</a>";
  2339. setTimeout(() =>
  2340. {
  2341. this.setSelectedOpById(origOp.id);
  2342. }, 100);
  2343. this.selectOpId(newOp.id);
  2344. gui.opParams.show(newOp.id);
  2345. this._patchRenderer.focusOpAnim(newOp.id);
  2346. new ModalDialog({ "html": html,
  2347. "showOkButton": true,
  2348. "okButton": { "text": "Really upgrade",
  2349. "callback": (done) =>
  2350. {
  2351. gui.patchView.replaceOp(opid, newOpObjName);
  2352. done();
  2353. } }
  2354. });
  2355. }
  2356. });
  2357. });
  2358. }
  2359. /**
  2360. * @param {string} opid
  2361. * @param {string} newOpObjName
  2362. * @param {function} cb
  2363. */
  2364. replaceOp(opid, newOpObjName, cb = null)
  2365. {
  2366. gui.serverOps.loadOpDependencies(newOpObjName, () =>
  2367. {
  2368. this.addOp(newOpObjName, {
  2369. "onOpAdd": (newOp) =>
  2370. {
  2371. const origOp = this._p.getOpById(opid);
  2372. if (origOp)
  2373. {
  2374. const oldUiAttribs = cloneObject(origOp.uiAttribs);
  2375. const theUiAttribs = {};
  2376. for (const i in oldUiAttribs)
  2377. {
  2378. if (i == "uierrors") continue;
  2379. theUiAttribs[i] = oldUiAttribs[i];
  2380. }
  2381. newOp.setUiAttrib(theUiAttribs);
  2382. gui.patchView.focusOpAnim(newOp.id);
  2383. this.copyOpInputPorts(origOp, newOp);
  2384. for (let i = 0; i < origOp.portsIn.length; i++)
  2385. {
  2386. for (let j = 0; j < origOp.portsIn[i].links.length; j++)
  2387. {
  2388. const otherPort = origOp.portsIn[i].links[j].getOtherPort(origOp.portsIn[i]);
  2389. // origOp.portsIn[i].links[j].remove(); not needed, if it IS needed, upgrade with multiple links on one port, links will be lost!!
  2390. this._p.link(otherPort.op, otherPort.name.toLowerCase(), newOp, origOp.portsIn[i].name.toLowerCase(), true);
  2391. }
  2392. }
  2393. for (let i = 0; i < origOp.portsOut.length; i++)
  2394. {
  2395. for (let j = 0; j < origOp.portsOut[i].links.length; j++)
  2396. {
  2397. const otherPort = origOp.portsOut[i].links[j].getOtherPort(origOp.portsOut[i]);
  2398. // origOp.portsOut[i].links[j].remove(); // not needed, if it IS needed, upgrade with multiple links on one port, links will be lost!!
  2399. // origOp.portsOut[i].links[j].link(otherPort, newOp.getPort(origOp.portsOut[i].name.toLowerCase(), true))
  2400. this._p.link(otherPort.op, otherPort.name.toLowerCase(), newOp, origOp.portsOut[i].name.toLowerCase(), true);
  2401. }
  2402. }
  2403. this._p.deleteOp(origOp.id);
  2404. setTimeout(() =>
  2405. {
  2406. newOp.setUiAttrib(theUiAttribs);
  2407. this.setCurrentSubPatch(oldUiAttribs.subPatch || 0, () =>
  2408. {
  2409. if (cb) cb();
  2410. });
  2411. }, 100);
  2412. }
  2413. else
  2414. {
  2415. this._log.error("no origop ?!");
  2416. }
  2417. }
  2418. });
  2419. });
  2420. }
  2421. // tempUnlinkOp()
  2422. // {
  2423. // if (this._lastTempOP)
  2424. // {
  2425. // this._lastTempOP.undoUnLinkTemporary();
  2426. // this._lastTempOP.setEnabled(true);
  2427. // this._lastTempOP = null;
  2428. // }
  2429. // else
  2430. // {
  2431. // const op = this.getSelectedOps()[0];
  2432. // if (op)
  2433. // {
  2434. // op.setEnabled(false);
  2435. // op.unLinkTemporary();
  2436. // this._lastTempOP = op;
  2437. // }
  2438. // }
  2439. // }
  2440. toggleVisibility()
  2441. {
  2442. gui.patchView.element.classList.toggle("hidden");
  2443. gui.patchView.patchRenderer.vizLayer._eleCanvas.classList.toggle("hidden");
  2444. gui.emitEvent("canvasModeChange");
  2445. }
  2446. /**
  2447. * @param {boolean} b
  2448. */
  2449. setVisibility(b)
  2450. {
  2451. if (b)
  2452. {
  2453. gui.patchView.element.classList.remove("hidden");
  2454. gui.patchView.patchRenderer.vizLayer._eleCanvas.classList.remove("hidden");
  2455. }
  2456. else
  2457. {
  2458. gui.patchView.element.classList.add("hidden");
  2459. gui.patchView.patchRenderer.vizLayer._eleCanvas.classList.add("hidden");
  2460. }
  2461. }
  2462. setPortTitle(opId, portName, oldtitle)
  2463. {
  2464. new ModalDialog({
  2465. "prompt": true,
  2466. "title": "Set Title",
  2467. "text": "Enter a custom title for this port",
  2468. "promptValue": oldtitle,
  2469. "promptOk": function (name)
  2470. {
  2471. const op = gui.corePatch().getOpById(opId);
  2472. const p = op.getPort(portName);
  2473. p.setUiAttribs({ "title": name });
  2474. gui.opParams.show(opId);
  2475. }
  2476. });
  2477. }
  2478. /**
  2479. * @param {object} oldLink
  2480. * @param {Op} op
  2481. * @param {number} x
  2482. * @param {number} y
  2483. */
  2484. insertOpInLink(oldLink, op, x, y)
  2485. {
  2486. let newPortIn = op.getFirstPortIn();
  2487. let newPortOut = op.getFirstPortOut();
  2488. if (!newPortIn || !newPortOut) return;
  2489. if (newPortIn.isLinked() || newPortOut.isLinked()) return;
  2490. let portIn = oldLink.portIn;
  2491. let portOut = oldLink.portOut;
  2492. if (oldLink.p1 && oldLink.p2)
  2493. {
  2494. portIn = oldLink.p1.thePort;
  2495. portOut = oldLink.p2.thePort;
  2496. if (oldLink.p2.thePort.direction == Port.DIR_IN)
  2497. {
  2498. portIn = oldLink.p2.thePort;
  2499. portOut = oldLink.p1.thePort;
  2500. }
  2501. oldLink.unlink();
  2502. }
  2503. else
  2504. {
  2505. oldLink.remove();
  2506. }
  2507. if (portIn && portOut && newPortOut) // && !newPortIn.isLinked()
  2508. {
  2509. if (Link.canLink(newPortIn, portOut)) //! portOut.isLinked() &&
  2510. {
  2511. gui.corePatch().link(
  2512. op,
  2513. newPortIn.getName(),
  2514. portOut.op,
  2515. portOut.getName()
  2516. );
  2517. gui.corePatch().link(
  2518. op,
  2519. newPortOut.getName(),
  2520. portIn.op,
  2521. portIn.getName()
  2522. );
  2523. op.setUiAttrib({ "translate": { "x": x, "y": y } });
  2524. }
  2525. else
  2526. {
  2527. gui.corePatch().link(portIn.op, portIn.getName(), portOut.op, portOut.getName());
  2528. }
  2529. }
  2530. }
  2531. pause()
  2532. {
  2533. if (this._patchRenderer && this._patchRenderer.pause) this._patchRenderer.pause();
  2534. }
  2535. resume()
  2536. {
  2537. if (this._patchRenderer && this._patchRenderer.resume) this._patchRenderer.resume();
  2538. }
  2539. /**
  2540. * @param {Number} x
  2541. * @param {Number} y
  2542. * @param {Number} w
  2543. * @param {Number} h
  2544. */
  2545. setSize(x, y, w, h)
  2546. {
  2547. if (this._patchRenderer) this._patchRenderer.setSize(x, y, w, h);
  2548. }
  2549. /**
  2550. * @param {number} step
  2551. */
  2552. zoomStep(step)
  2553. {
  2554. this._patchRenderer.zoomStep(step);
  2555. }
  2556. /**
  2557. * @param {UiOp} op1
  2558. * @param {UiOp} op2
  2559. */
  2560. suggestionBetweenTwoOps(op1, op2)
  2561. {
  2562. const mouseEvent =/** @type {MouseEvent} */ ({ "clientX": 400, "clientY": 400 });
  2563. let showConv = true;
  2564. /** @type {import("./suggestiondialog.js").SuggestionItem[]} */
  2565. const suggestions = [
  2566. {
  2567. "cb": () => { gui.patchView.suggestionBetweenTwoOps(op2, op1); },
  2568. "name": "OUT: " + op1.getTitle(),
  2569. "classname": ""
  2570. }];
  2571. if (!op1 || !op2) return;
  2572. for (let j = 0; j < op1.portsOut.length; j++)
  2573. {
  2574. const p = op1.portsOut[j];
  2575. const numFitting = op2.countFittingPorts(p, showConv);
  2576. let addText = "...";
  2577. if (numFitting > 0)
  2578. {
  2579. if (numFitting == 1)
  2580. {
  2581. const p2 = op2.findFittingPort(p, showConv);
  2582. addText = p2.title;
  2583. }
  2584. suggestions.push({
  2585. "p": p,
  2586. "name": p.title + " → " + addText,
  2587. "classname": "port_text_color_" + p.getTypeString().toLowerCase()
  2588. });
  2589. }
  2590. }
  2591. if (suggestions.length === 0)
  2592. {
  2593. notify("can not link!");
  2594. return;
  2595. }
  2596. const showSuggestions2 = (id) =>
  2597. {
  2598. if (suggestions[id].cb) return suggestions[id].cb();
  2599. const p = suggestions[id].p;
  2600. /** @type {import("./suggestiondialog.js").SuggestionItem[]} */
  2601. const sugIn =
  2602. [{
  2603. "cb": () => { gui.patchView.suggestionBetweenTwoOps(op2, op1); },
  2604. "name": "<span class=\"icon icon-op\"></span>IN: " + op2.getTitle(),
  2605. "classname": ""
  2606. }];
  2607. for (let i = 0; i < op2.portsIn.length; i++)
  2608. {
  2609. if (Link.canLink(op2.portsIn[i], p))
  2610. {
  2611. sugIn.push({
  2612. "p": op2.portsIn[i],
  2613. "name": "<span class=\"icon icon-arrow-right\"></span>" + op2.portsIn[i].title,
  2614. "classname": "port_text_color_" + op2.portsIn[i].getTypeString().toLowerCase()
  2615. });
  2616. }
  2617. }
  2618. if (sugIn.length == 1)
  2619. {
  2620. gui.corePatch().link(
  2621. p.op,
  2622. p.name,
  2623. sugIn[0].p.op,
  2624. sugIn[0].p.name);
  2625. return;
  2626. }
  2627. new SuggestionDialog(sugIn, op2, mouseEvent, null, function (sid)
  2628. {
  2629. gui.corePatch().link(
  2630. p.op,
  2631. p.name,
  2632. sugIn[sid].p.op,
  2633. sugIn[sid].p.name);
  2634. });
  2635. };
  2636. new SuggestionDialog(suggestions, op1, mouseEvent, null, showSuggestions2, false);
  2637. }
  2638. /**
  2639. * @param {String} col
  2640. */
  2641. setOpColor(col)
  2642. {
  2643. const selectedOps = this.getSelectedOps();
  2644. for (let i = 0; i < selectedOps.length; i++)
  2645. if (selectedOps[i].uiAttribs.hasArea)
  2646. return selectedOps[i].setUiAttrib({ "color": col });
  2647. for (let i = 0; i < selectedOps.length; i++)
  2648. selectedOps[i].setUiAttrib({ "color": col });
  2649. }
  2650. /**
  2651. * @param {string} opid
  2652. * @param {string} [portname]
  2653. */
  2654. resetOpValues(opid, portname)
  2655. {
  2656. const op = this._p.getOpById(opid);
  2657. if (!op)
  2658. {
  2659. this._log.error("reset op values: op not found...", opid);
  2660. return;
  2661. }
  2662. if (portname)
  2663. {
  2664. const p = op.getPortByName(portname);
  2665. const oldValue = p.get();
  2666. undo.add({
  2667. "title": "reset defaultvalue",
  2668. "undo": function ()
  2669. {
  2670. p.set(oldValue);
  2671. gui.opParams.show(op);
  2672. },
  2673. "redo": function ()
  2674. {
  2675. p.set(p.defaultValue);
  2676. gui.opParams.show(op);
  2677. }
  2678. });
  2679. p.set(p.defaultValue);
  2680. }
  2681. else
  2682. {
  2683. // all ops
  2684. for (let i = 0; i < op.portsIn.length; i++)
  2685. if (op.portsIn[i].defaultValue != null)
  2686. op.portsIn[i].set(op.portsIn[i].defaultValue);
  2687. }
  2688. gui.opParams.show(op);
  2689. }
  2690. // getBlueprintOpFromBlueprintSubpatchId(bpSubpatchId)
  2691. // {
  2692. // const ops = gui.corePatch().ops;
  2693. // for (let i = 0; i < ops.length; i++)
  2694. // if (ops[i].uiAttribs && ops[i].uiAttribs.blueprintSubpatch && ops[i].uiAttribs.blueprintSubpatch == bpSubpatchId)
  2695. // return ops[i];
  2696. // }
  2697. /**
  2698. * @param {string} subid
  2699. */
  2700. getAllOpsInBlueprint(subid)
  2701. {
  2702. const foundOps = [];
  2703. const ops = gui.corePatch().ops;
  2704. for (let i = 0; i < ops.length; i++)
  2705. {
  2706. if (ops[i].isInBlueprint2() == subid || ops[i].uiAttribs.subPatch == subid) foundOps.push(ops[i]);
  2707. }
  2708. return foundOps;
  2709. }
  2710. /**
  2711. * @param {string | number} subid
  2712. */
  2713. getAllSubPatchOps(subid)
  2714. {
  2715. const foundOps = [];
  2716. const ops = gui.corePatch().ops;
  2717. for (let i = 0; i < ops.length; i++)
  2718. {
  2719. if (ops[i] && ops[i].uiAttribs && ops[i].uiAttribs.subPatch == subid) foundOps.push(ops[i]);
  2720. }
  2721. return foundOps;
  2722. }
  2723. /**
  2724. * @param {Port} port
  2725. * @param {number} dir
  2726. */
  2727. setExposedPortOrder(port, dir)
  2728. {
  2729. const ports = this.getSubPatchExposedPorts(port.op.uiAttribs.subPatch);
  2730. gui.savedState.setUnSaved("exposedPortOrder", port.op.uiAttribs.subPatch);
  2731. function move(arr, from, to)
  2732. {
  2733. arr.splice(to, 0, arr.splice(from, 1)[0]);
  2734. }
  2735. const idx = ports.indexOf(port);
  2736. if (idx + dir >= 0) move(ports, idx, idx + dir);
  2737. for (let i = 0; i < ports.length; i++) ports[i].setUiAttribs({ "order": i });
  2738. const exposeOp = this.getSubPatchOuterOp(port.op.uiAttribs.subPatch);
  2739. if (gui.opParams.op == exposeOp) gui.opParams.show(this.getSubPatchOuterOp(port.op.uiAttribs.subPatch).id);
  2740. exposeOp.emitEvent(Op.EVENT_PORT_ORDER_CHANGE);
  2741. exposeOp.emitEvent(GlPort.EVENT_GLPORTORDER_CHANGED);
  2742. }
  2743. getSubPatchExposedPorts(_subid, _dir)
  2744. {
  2745. let foundPorts = [];
  2746. // const ops = this.getAllSubPatchOps(subid);
  2747. // for (let i = 0; i < ops.length; i++)
  2748. // {
  2749. // if (dir == undefined || dir === Port.DIR_IN)
  2750. // if (ops[i].portsIn)
  2751. // for (let j = 0; j < ops[i].portsIn.length; j++)
  2752. // if (ops[i].portsIn[j].uiAttribs.expose)foundPorts.push(ops[i].portsIn[j]);
  2753. // if (dir == undefined || dir === Port.DIR_OUT)
  2754. // for (let j = 0; j < ops[i].portsOut.length; j++)
  2755. // if (ops[i].portsOut[j].uiAttribs.expose)foundPorts.push(ops[i].portsOut[j]);
  2756. // }
  2757. // foundPorts = foundPorts.sort(function (a, b) { return (a.uiAttribs.order || 0) - (b.uiAttribs.order || 0); });
  2758. // for (let i = 0; i < foundPorts.length; i++)
  2759. return foundPorts;
  2760. }
  2761. /**
  2762. * @param {UiOp[]} ops
  2763. * @param {string} portName
  2764. * @param {any} valueNew
  2765. */
  2766. replacePortValues(ops, portName, valueNew, valueOld = undefined)
  2767. {
  2768. ops.forEach((op) =>
  2769. {
  2770. const port = op.getPortByName(portName);
  2771. if (port)
  2772. {
  2773. const value = port.get();
  2774. if (valueOld === undefined)
  2775. {
  2776. port.set(valueNew);
  2777. }
  2778. else
  2779. {
  2780. if (value === valueOld) port.set(valueNew);
  2781. }
  2782. }
  2783. });
  2784. }
  2785. highlightExamplePatchOps()
  2786. {
  2787. const patchSummary = gui.getPatchSummary();
  2788. if (patchSummary && patchSummary.exampleForOps && patchSummary.exampleForOps.length > 0)
  2789. {
  2790. let patchTitle = "";
  2791. const ops = gui.corePatch().ops;
  2792. for (let i = 0; i < ops.length; i++)
  2793. ops[i].setUiAttribs({ "color": null });
  2794. for (let j = 0; j < patchSummary.exampleForOps.length; j++)
  2795. {
  2796. patchTitle += getShortOpName(patchSummary.exampleForOps[j]) + " ";
  2797. const opz = gui.corePatch().getOpsByObjName(patchSummary.exampleForOps[j]);
  2798. for (let k = 0; k < opz.length; k++)
  2799. {
  2800. opz[k].setUiAttribs({ "color": "#5dc0fd" });
  2801. }
  2802. }
  2803. if (gui.user.isStaff) PatchView.addUiErrorOutdatedOps();
  2804. patchTitle += " Example";
  2805. if (gui.user.isStaff && patchSummary.title != patchTitle && platform.isTrustedPatch() && gui.user.hasWriteRights)
  2806. {
  2807. this.store.setPatchName(patchTitle);
  2808. }
  2809. }
  2810. if (!patchSummary) { console.error("has no patch summary"); }
  2811. }
  2812. static addUiErrorOutdatedOps()
  2813. {
  2814. const ops = gui.corePatch().ops;
  2815. for (let i = 0; i < ops.length; i++)
  2816. {
  2817. const doc = gui.opDocs.getOpDocByName(ops[i].objName);
  2818. if (!doc || doc.oldVersion)
  2819. ops[i].setUiError("nodoc", "outdated op in example patch!");
  2820. }
  2821. }
  2822. warnLargestPort()
  2823. {
  2824. let max = 0;
  2825. let maxName = "unknown";
  2826. let ser = "";
  2827. let maxValue = "";
  2828. let maxId = "";
  2829. try
  2830. {
  2831. for (const i in this._p.ops)
  2832. {
  2833. for (let j in this._p.ops[i].portsIn)
  2834. {
  2835. if (this._p.ops[i].portsIn[j].uiAttribs.ignoreBigPort) continue;
  2836. ser = JSON.stringify(this._p.ops[i].portsIn[j].getSerialized());
  2837. if (ser.length > max)
  2838. {
  2839. max = ser.length;
  2840. maxValue = ser;
  2841. maxName = this._p.ops[i].name + " - in: " + this._p.ops[i].portsIn[j].name;
  2842. maxId = this._p.ops[i].id;
  2843. }
  2844. }
  2845. for (let j in this._p.ops[i].portsOut)
  2846. {
  2847. if (this._p.ops[i].portsOut[j].uiAttribs.ignoreBigPort) continue;
  2848. ser = JSON.stringify(this._p.ops[i].portsOut[j].getSerialized());
  2849. if (ser.length > max)
  2850. {
  2851. max = ser.length;
  2852. maxValue = ser;
  2853. maxName = this._p.ops[i].name + " - out: " + this._p.ops[i].portsOut[j].name;
  2854. maxId = this._p.ops[i].id;
  2855. }
  2856. }
  2857. }
  2858. if (max > 10000)
  2859. {
  2860. const txt = "warning big port: " + maxName + " / " + max + " chars";
  2861. notify(txt);
  2862. this._log.log(txt);
  2863. }
  2864. }
  2865. catch (e)
  2866. {
  2867. // TEST GIT SHIT
  2868. this._log.error(e);
  2869. }
  2870. finally
  2871. {
  2872. }
  2873. }
  2874. updateBlueprints(blueprintOps = [])
  2875. {
  2876. blueprintOps.forEach((blueprintOp) =>
  2877. {
  2878. blueprintOp.updateBlueprint();
  2879. });
  2880. }
  2881. /**
  2882. * @param {string} opid
  2883. */
  2884. focusOpAnim(opid)
  2885. {
  2886. this._patchRenderer.focusOpAnim(opid);
  2887. }
  2888. getPatchOpsUsedInPatch()
  2889. {
  2890. const patch = gui.corePatch();
  2891. const ops = patch.ops;
  2892. return ops.filter((op) =>
  2893. {
  2894. return namespace.isPatchOp(op.objName);
  2895. });
  2896. }
  2897. getUserOpsUsedInPatch()
  2898. {
  2899. const patch = gui.corePatch();
  2900. const ops = patch.ops;
  2901. return ops.filter((op) =>
  2902. {
  2903. return namespace.isUserOp(op.objName);
  2904. });
  2905. }
  2906. getUrlInputPorts()
  2907. {
  2908. let ports = [];
  2909. const patch = gui.corePatch();
  2910. const ops = patch.ops;
  2911. for (let i = 0; i < ops.length; i++)
  2912. {
  2913. for (let j = 0; j < ops[i].portsIn.length; j++)
  2914. {
  2915. if (ops[i].portsIn[j].uiAttribs.display == "file")ports.push(ops[i].portsIn[j]);
  2916. }
  2917. }
  2918. return ports;
  2919. }
  2920. }