Home Reference Source

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

  1. import { Logger, ele, CablesConstants, TalkerAPI } from "cables-shared-client";
  2. import { utils } from "cables";
  3. import ItemManager from "./tabs/tab_item_manager.js";
  4. import { getHandleBarHtml } from "../utils/handlebars.js";
  5. import ModalDialog from "../dialogs/modaldialog.js";
  6. import { GuiText } from "../text.js";
  7. import { notify, notifyError, notifyWarn } from "../elements/notification.js";
  8. import opNames from "../opnameutils.js";
  9. import Gui, { gui } from "../gui.js";
  10. import { platform } from "../platform.js";
  11. import { UserSettings, userSettings } from "./usersettings.js";
  12. import DragNDrop from "./filemanager_dragdrop.js";
  13. /** Manages the files/assets of the patch. */
  14. export default class FileManager
  15. {
  16. /** @type {string[]} */
  17. static updatedFiles = [];
  18. #fileSource = "patch";
  19. _filterType = null;
  20. _filePortEle = null;
  21. /** @type {HTMLElement} */
  22. _filePortElePreview = null;
  23. _firstTimeOpening = true;
  24. _refreshDelay = null;
  25. _orderReverse = false;
  26. /** @type {object} */
  27. _files = [];
  28. /**
  29. * @param {Function} cb
  30. * @param {boolean} userInteraction
  31. */
  32. constructor(cb, userInteraction)
  33. {
  34. this._log = new Logger("filemanager");
  35. this._manager = new ItemManager("Files", gui.mainTabs);
  36. this._order = userSettings.get(UserSettings.PREF_FILEMANAGER_ORDER) || "name";
  37. gui.maintabPanel.show(userInteraction);
  38. DragNDrop.loadImage();
  39. this._manager.setDisplay(userSettings.get(UserSettings.PREF_FILEMANAGER_DISPLAY) || "icons");
  40. this.reload(cb);
  41. gui.on(Gui.EVENT_OP_SELECTIONCHANGED, (e) =>
  42. {
  43. if (this._filePortOp && this._filePortOp != e)
  44. {
  45. this.cancelFileSelectOp();
  46. }
  47. });
  48. this._manager.addEventListener("onItemsSelected", (items) =>
  49. {
  50. this.setDetail(items);
  51. });
  52. this._manager.addEventListener("close", () =>
  53. {
  54. gui.fileManager = null;
  55. });
  56. if (platform.frontendOptions.isElectron)
  57. gui.on("patchsaved", () =>
  58. {
  59. if (!ele.byId("filemanagercontainer")) return;
  60. gui.refreshFileManager();
  61. });
  62. }
  63. /**
  64. * @param {boolean} userInteraction
  65. */
  66. show(userInteraction)
  67. {
  68. gui.maintabPanel.show(userInteraction);
  69. gui.maintabPanel.show(true);
  70. }
  71. refresh()
  72. {
  73. CABLES.idleCallback(
  74. () =>
  75. {
  76. this.setSource(this.#fileSource);
  77. });
  78. }
  79. cancelFileSelectOp()
  80. {
  81. this._filePortElePreview = null;
  82. this._filePortEle = null;
  83. this._filePortOp = null;
  84. if (this._filterType)
  85. {
  86. this._filterType = null;
  87. this._buildHtml();
  88. }
  89. }
  90. /**
  91. * @param {HTMLElement} portEle
  92. * @param {import("../core_extend_op.js").UiOp} [op]
  93. * @param {undefined} [previewEle]
  94. */
  95. setFilePort(portEle, op, previewEle)
  96. {
  97. if (!portEle)
  98. {
  99. this.cancelFileSelectOp();
  100. }
  101. else
  102. {
  103. this._filePortElePreview = previewEle;
  104. this._filePortEle = portEle;
  105. this._filePortOp = op;
  106. gui.fileManager.setFilter("");
  107. }
  108. this.updateHeader();
  109. }
  110. /**
  111. * @param {function} [cb]
  112. */
  113. reload(cb)
  114. {
  115. this._manager.clear();
  116. this.#fileSource = this.#fileSource || "patch";
  117. // if (this._firstTimeOpening) this._fileSource = "patch";
  118. if (gui.isGuestEditor())
  119. {
  120. this._buildHtml();
  121. return;
  122. }
  123. // const eleContent = ele.byQuery("#item_manager .filelistcontainer");
  124. // if (eleContent)eleContent.innerHTML = "<div class=\"loading\" style=\"margin-top:50px;\"></div>";
  125. gui.jobs().start({
  126. "id": "getFileList",
  127. "title": "Loading file list"
  128. });
  129. this._getFilesFromSource(this.#fileSource, (files) =>
  130. {
  131. if (!files) files = [];
  132. const patchFiles = files.filter((file) => { return file.projectId && file.projectId === gui.project()._id; });
  133. this._firstTimeOpening = false;
  134. this._files = files;
  135. this._buildHtml();
  136. if (cb) cb();
  137. gui.jobs().finish("getFileList");
  138. });
  139. }
  140. _getFilesFromSource(source, cb)
  141. {
  142. platform.talkerAPI.send(
  143. TalkerAPI.CMD_GET_FILE_LIST,
  144. {
  145. "source": source,
  146. "references": true
  147. },
  148. (err, remoteFiles) =>
  149. {
  150. if (err)
  151. {
  152. this._log.error(err);
  153. cb([]);
  154. }
  155. else
  156. {
  157. if (cb) cb(remoteFiles);
  158. }
  159. }
  160. );
  161. }
  162. _createItem(items, file, filterType)
  163. {
  164. let size = "";
  165. if (file.s) size = Math.ceil(file.s / 1024) + " kb";
  166. const item = {
  167. "title": file.n,
  168. "shortTitle": file.n.replaceAll(".", "<wbr>."),
  169. "id": file._id || "lib" + utils.uuid(),
  170. "p": file.p,
  171. "dir": file.d,
  172. "updated": file.updated,
  173. "sizeKb": size,
  174. "size": file.s,
  175. "file": file,
  176. "isReference": file.isReference,
  177. "hasReference": file.hasReference,
  178. "isLibraryFile": file.isLibraryFile,
  179. "referenceCount": file.referenceCount,
  180. "projectId": file.projectId,
  181. "icon": file.icon || "file"
  182. };
  183. if (file.t === "SVG") item.preview = file.p;
  184. else if (file.t === "image") item.preview = file.p;
  185. else if (file.t === "dir") item.divider = file.n;
  186. if (item.preview && FileManager.updatedFiles.indexOf(file.n) > -1) item.preview += "?cb=" + Math.random();
  187. if (!filterType) items.push(item);
  188. else
  189. {
  190. if (this._compareFilter(file, filterType)) items.push(item);
  191. if (file.t == "dir")
  192. {
  193. // subdir has file with correct file type ??
  194. for (let i = 0; i < file.c.length; i++)
  195. {
  196. if (this._compareFilter(file.c[i], filterType))
  197. {
  198. items.push(item);
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. if (file.c) for (let i = 0; i < file.c.length; i++) this._createItem(items, file.c[i], filterType);
  205. }
  206. /**
  207. * @param {Object} file
  208. * @param {string|string[]} filterType
  209. */
  210. _compareFilter(file, filterType)
  211. {
  212. if (typeof filterType == "string")
  213. {
  214. if (filterType === file.t) return true;
  215. }
  216. else
  217. {
  218. if (Array.isArray(filterType))
  219. {
  220. for (let i = 0; i < filterType.length; i++)
  221. {
  222. if (file.n.toLowerCase().indexOf(filterType[i].toLowerCase()) > 0) return true;
  223. }
  224. }
  225. }
  226. return false;
  227. }
  228. _buildHtml(o)
  229. {
  230. const items = [];
  231. if (!this._files) this._files = [];
  232. if (this._order == "size")
  233. {
  234. this._files.sort(function (a, b)
  235. {
  236. return a.s - b.s;
  237. });
  238. }
  239. if (this._order == "date")
  240. {
  241. this._files.sort(function (a, b)
  242. {
  243. return b.d - a.d;
  244. });
  245. }
  246. if (this._order == "name")
  247. {
  248. this._files.sort(function (a, b)
  249. {
  250. return (a.name || "").toLowerCase()
  251. .localeCompare((b.name || "").toLowerCase());
  252. });
  253. }
  254. if (this._order == "type")
  255. {
  256. this._files.sort(function (a, b)
  257. {
  258. return (a.t || "").toLowerCase()
  259. .localeCompare((b.t || "").toLowerCase());
  260. });
  261. }
  262. if (this._orderReverse) this._files.reverse();
  263. for (let i = 0; i < this._files.length; i++)
  264. {
  265. this._createItem(items, this._files[i], this._filterType);
  266. }
  267. this._manager.listHtmlOptions.showHeader = this.#fileSource !== "lib";
  268. this._manager.listHtmlOptions.order = this._order;
  269. this._manager.listHtmlOptions.orderReverse = this._orderReverse;
  270. this._manager.setItems(items);
  271. this.updateHeader();
  272. if (this._files.length == 0)
  273. {
  274. const els = ele.byQuery("#filemanagercontainer .filelistcontainer");
  275. if (els)
  276. {
  277. let uploadText = "";
  278. if (platform.frontendOptions.uploadFiles)
  279. {
  280. uploadText = "<br/><br/><br/><br/><div class=\"text-center\">This Patch contains no files yet!<br/><br/>";
  281. uploadText += "<a class=\"button-small\" onclick=\"CABLES.CMD.PATCH.uploadFileDialog();\">Upload files</a> or ";
  282. uploadText += "use files from our <a class=\"button-small\" onclick=\"gui.fileManager.setSource('lib');\">Library</a>";
  283. }
  284. else
  285. {
  286. uploadText = "<br/><br/><br/><br/><div class=\"text-center\">Patch does not use any files, yet!<br/><br/>";
  287. uploadText += "Drag them onto the patchfiled to use them";
  288. }
  289. uploadText += "</div>";
  290. els.innerHTML = uploadText;
  291. }
  292. }
  293. }
  294. /**
  295. * @param {string} f
  296. */
  297. setFilter(f)
  298. {
  299. this._manager.setTitleFilter(f);
  300. }
  301. /**
  302. * @param {string} o
  303. */
  304. setOrder(o)
  305. {
  306. if (this._order != o) this._orderReverse = false;
  307. else this._orderReverse = !this._orderReverse;
  308. this._order = o;
  309. userSettings.set(UserSettings.PREF_FILEMANAGER_ORDER, this._order);
  310. this._buildHtml();
  311. }
  312. /**
  313. * @param {string} f
  314. */
  315. setFilterType(f)
  316. {
  317. this._filterType = f;
  318. this._buildHtml();
  319. }
  320. /**
  321. * @param {string} s
  322. * @param {Function} [cb]
  323. */
  324. setSource(s, cb)
  325. {
  326. this.#fileSource = s;
  327. this.updateHeader();
  328. this.reload(cb);
  329. }
  330. /**
  331. * @param {string} filename
  332. */
  333. _selectFile(filename)
  334. {
  335. this._manager.unselectAll();
  336. const item = this._manager.getItemByTitle(filename);
  337. console.log("get by title", filename, item);
  338. if (!item) return;
  339. this._manager.selectItemById(item.id);
  340. const el = ele.byId("item" + item.id);
  341. if (el) el.scrollIntoView();
  342. }
  343. /**
  344. * @param {string} filename
  345. */
  346. selectFile(filename)
  347. {
  348. if (this.#fileSource === "patch")
  349. {
  350. this._selectFile(filename);
  351. }
  352. else
  353. {
  354. if (filename.indexOf(gui.project()._id) > -1)
  355. {
  356. this.setSource(
  357. "patch",
  358. () =>
  359. {
  360. this._selectFile(filename);
  361. }
  362. );
  363. }
  364. }
  365. gui.maintabPanel.show(true);
  366. const item = this._manager.getItemByTitleContains(filename);
  367. if (item && !item.isLibraryFile) this.setDetail([item]);
  368. }
  369. setDisplay(type)
  370. {
  371. userSettings.set(UserSettings.PREF_FILEMANAGER_DISPLAY, type);
  372. this._manager.setDisplay(type);
  373. this._manager.setItems();
  374. this.updateHeader();
  375. }
  376. updateHeader(detailItems)
  377. {
  378. if (gui.isGuestEditor())
  379. {
  380. if (ele.byId("itemmanager_header")) ele.byId("itemmanager_header").innerHTML = (GuiText.guestHint);
  381. return;
  382. }
  383. const html = getHandleBarHtml("filemanager_header", {
  384. "fileSelectOp": this._filePortOp,
  385. "filterType": this._filterType,
  386. "source": this.#fileSource,
  387. "display": this._manager.getDisplay(),
  388. "filter": this._manager.titleFilter
  389. });
  390. if (ele.byId("itemmanager_header")) ele.byId("itemmanager_header").innerHTML = (html);
  391. const elSwitchIcons = ele.byId("switch-display-icons");
  392. const elSwitchList = ele.byId("switch-display-list");
  393. if (elSwitchIcons)
  394. {
  395. elSwitchIcons.addEventListener(
  396. "click",
  397. function ()
  398. {
  399. // elSwitchIcons.classList.add("switch-active");
  400. // elSwitchList.classList.remove("switch-active");
  401. this.setDisplay("icons");
  402. }.bind(this)
  403. );
  404. }
  405. if (elSwitchList)
  406. {
  407. elSwitchList.addEventListener(
  408. "click",
  409. () =>
  410. {
  411. // elSwitchList.classList.add("switch-active");
  412. // elSwitchIcons.classList.remove("switch-active");
  413. this.setDisplay("list");
  414. }
  415. );
  416. }
  417. }
  418. setDetail(detailItems)
  419. {
  420. let html = "";
  421. ele.byId("item_details").innerHTML = "";
  422. if (detailItems.length === 1)
  423. {
  424. const detailItem = detailItems[0];
  425. const itemId = detailItem.id;
  426. let projectId = gui.project()._id;
  427. if (detailItem.isReference && detailItem.file) projectId = detailItem.file.projectId;
  428. const filename = detailItem.file ? detailItem.file.p : null;
  429. platform.talkerAPI.send(
  430. TalkerAPI.CMD_GET_FILE_DETAILS,
  431. {
  432. "projectId": projectId,
  433. "fileid": itemId,
  434. "filename": filename
  435. },
  436. function (err, r)
  437. {
  438. if (err)
  439. {
  440. html = err.msg;
  441. if (ele.byId("item_details")) ele.byId("item_details").innerHTML = html;
  442. return;
  443. }
  444. if (r.fileDb) r.ops = opNames.getOpsForFilename(r.fileDb.fileName);
  445. if (this.#fileSource !== "lib")
  446. {
  447. let downloadUrl = detailItem.p;
  448. if (detailItem.file && detailItem.file.cachebuster) downloadUrl += "?rnd=" + detailItem.file.cachebuster;
  449. const editableFiles = CablesConstants.EDITABLE_FILETYPES || [];
  450. const editable = !platform.isElectron() && editableFiles.includes(r.type);
  451. let assetPath = "";
  452. if (r && r.fileDb) assetPath = "/assets/" + r.fileDb.projectId + "/" + r.fileDb.fileName;
  453. if (platform.frontendOptions.isElectron) assetPath = r.path;
  454. html = getHandleBarHtml("filemanager_details", {
  455. "projectId": gui.project()._id,
  456. "file": r,
  457. "source": this.#fileSource,
  458. "isEditable": editable,
  459. "assetPath": assetPath,
  460. "isPlatformCommunity": platform.frontendOptions.hasCommunity,
  461. "isReference": detailItem.isReference,
  462. "isLibraryFile": detailItem.isLibraryFile,
  463. "referenceCount": detailItem.referenceCount,
  464. "projectUrl": platform.getCablesUrl() + "/edit/" + detailItem.projectId,
  465. "downloadUrl": downloadUrl,
  466. "assetPageUrl": platform.getCablesUrl() + "/asset/patches/?filename=" + detailItem.p
  467. });
  468. }
  469. else
  470. {
  471. // * it's a library file
  472. const item = detailItem;
  473. const fileParts = item.p.split("/assets/library/");
  474. const fileInfoPath = fileParts.length > 1 ? fileParts[1] : "";
  475. const fileCategory = fileInfoPath.split("/")[0];
  476. const fileName = fileInfoPath.split("/")[1];
  477. platform.talkerAPI.send(
  478. TalkerAPI.CMD_GET_LIBRARYFILE_DETAILS,
  479. {
  480. "filename": fileName,
  481. "fileCategory": fileCategory,
  482. "filepath": fileInfoPath
  483. },
  484. (_err, _r) =>
  485. {
  486. const itemInfo = _r;
  487. let templateName = "filemanager_details_lib";
  488. if (itemInfo.type) templateName += "_" + itemInfo.type;
  489. const templateOptions = {
  490. "filename": item.p,
  491. "file": item,
  492. "fileInfo": itemInfo
  493. };
  494. try
  495. {
  496. // * use file-type specific template
  497. html = getHandleBarHtml(templateName, templateOptions);
  498. }
  499. catch (e)
  500. {
  501. // * use default template
  502. html = getHandleBarHtml("filemanager_details_lib", templateOptions);
  503. }
  504. if (ele.byId("item_details"))
  505. ele.byId("item_details").innerHTML = html;
  506. }
  507. );
  508. }
  509. if (ele.byId("item_details"))
  510. ele.byId("item_details").innerHTML = html;
  511. ele.clickable(ele.byId("filecopyurl" + itemId),
  512. (e) =>
  513. {
  514. navigator.clipboard
  515. .writeText(r.path)
  516. .then(() =>
  517. {
  518. notify("Copied to clipboard");
  519. })
  520. .catch((copyError) =>
  521. {
  522. notifyWarn("Copied to clipboard failed");
  523. this._log.warn("copy to clipboard failed", copyError);
  524. });
  525. });
  526. ele.clickable(ele.byId("fileedit" + itemId),
  527. (e) =>
  528. {
  529. let fileName = r.fileDb.fileName;
  530. if (platform.frontendOptions.isElectron) fileName = r.path;
  531. gui.fileManagerEditor.editAssetTextFile(fileName, r.fileDb.type);
  532. });
  533. ele.clickable(ele.byId("filedelete" + itemId),
  534. (e) =>
  535. {
  536. const loadingModal = gui.startModalLoading("Checking asset dependencies");
  537. loadingModal.setTask("Checking patches and ops...");
  538. const fullName = "/assets/" + gui.project()._id + "/" + r.fileDb.fileName;
  539. platform.talkerAPI.send(
  540. TalkerAPI.CMD_GET_ASSET_USAGE_COUNT,
  541. { "filenames": [fullName] },
  542. (countErr, countRes) =>
  543. {
  544. gui.endModalLoading();
  545. let content = "";
  546. let allowDelete = true;
  547. if (countRes && countRes.data)
  548. {
  549. const otherCount = countRes.data.countPatches ? countRes.data.countPatches - 1 : 0;
  550. if (otherCount)
  551. {
  552. let linkText = otherCount + " other patch";
  553. if (otherCount > 1) linkText += "es";
  554. content += "It is used in <a href=\"" + platform.getCablesUrl() + "/asset/patches/?filename=" + fullName + "\" target=\"_blank\">" + linkText + "</a>";
  555. }
  556. if (countRes.data.countOps)
  557. {
  558. let linkText = countRes.data.countOps + " op";
  559. if (countRes.data.countOps > 1) linkText += "s";
  560. if (otherCount) content += "<br/>";
  561. content += "It is used in <a href=\"" + platform.getCablesUrl() + "/asset/patches/?filename=" + fullName + "\" target=\"_blank\">" + linkText + "</a>";
  562. allowDelete = false;
  563. }
  564. }
  565. else
  566. {
  567. content += "It may be used in other patches.";
  568. }
  569. let title = "Really delete this file?";
  570. let okButton = null;
  571. const patchSummary = gui.getPatchSummary();
  572. if (patchSummary && patchSummary.visibility == "public")content += "<div class=\"error warning-error warning-error-level2 text-center\"><br/><br/>this asset is in a public patch, please make sure your patch continues to work!<br/><br/><br/></div>";
  573. if (!allowDelete)
  574. {
  575. title = "You cannot delete this file!";
  576. }
  577. else
  578. {
  579. okButton = {
  580. "text": "Really delete",
  581. "cssClasses": "redbutton"
  582. };
  583. }
  584. const options = {
  585. "title": title,
  586. "html": content,
  587. "warning": true,
  588. "choice": allowDelete,
  589. "okButton": okButton
  590. };
  591. const modal = new ModalDialog(options);
  592. if (allowDelete)
  593. {
  594. modal.on("onSubmit", () =>
  595. {
  596. platform.talkerAPI.send(
  597. TalkerAPI.CMD_DELETE_FILE,
  598. { "fileid": r.fileDb._id },
  599. (errr, rr) =>
  600. {
  601. if (rr && rr.success)
  602. {
  603. this._manager.removeItem(itemId);
  604. this.reload();
  605. }
  606. else notifyError("Could not delete file. " + errr.msg);
  607. }
  608. );
  609. });
  610. }
  611. }
  612. );
  613. }
  614. );
  615. }.bind(this)
  616. );
  617. if (this._filePortEle)
  618. {
  619. if (this._filePortOp)
  620. gui.savedState.setUnSaved("filemanager", this._filePortOp.getSubPatch());
  621. this._filePortEle.value = detailItems[0].p;
  622. const event = document.createEvent("Event");
  623. event.initEvent("input", true, true);
  624. this._filePortEle.dispatchEvent(event);
  625. if (detailItems[0].t == "image" || detailItems[0].icon == "image")
  626. if (this._filePortElePreview)
  627. this._filePortElePreview.innerHTML = "<img class=\"dark\" src=\"" + detailItems[0].p + "\" style=\"max-width:100%;margin-top:10px;\"/>";
  628. if (this._filePortOp)
  629. gui.opParams.show(this._filePortOp);
  630. // this.refresh();
  631. }
  632. }
  633. else if (detailItems.length > 1)
  634. {
  635. let allSize = 0;
  636. for (let i = 0; i < detailItems.length; i++) allSize += detailItems[i].size;
  637. if (allSize) allSize = Math.ceil(allSize / 1024);
  638. html = "<div class=\"text-center\"><br/><br/>" + detailItems.length + " files selected<br/>";
  639. if (allSize) html += "Size: " + allSize + " kb<br/>";
  640. html += "<br/>";
  641. if (this.#fileSource == "patch") html += "<a class=\"cblbutton\" id=\"filesdeletmulti\">delete " + detailItems.length + " files</a>";
  642. html += "</div>";
  643. ele.byId("item_details").innerHTML = html;
  644. const elDelMulti = ele.byId("filesdeletmulti");
  645. if (elDelMulti)
  646. {
  647. elDelMulti.addEventListener(
  648. "click",
  649. (e) =>
  650. {
  651. const selectedItems = this._manager.getSelectedItems();
  652. this._manager.unselectAll();
  653. const selectedFileIds = [];
  654. const fullNames = [];
  655. for (let i = 0; i < selectedItems.length; i++)
  656. {
  657. const detailItem = selectedItems[i];
  658. selectedFileIds.push(detailItem.id);
  659. fullNames.push(detailItem.p);
  660. }
  661. const loadingModal = gui.startModalLoading("Checking asset dependencies");
  662. loadingModal.setTask("Checking patches and ops...");
  663. platform.talkerAPI.send(
  664. TalkerAPI.CMD_GET_ASSET_USAGE_COUNT,
  665. { "filenames": fullNames },
  666. (countErr, countRes) =>
  667. {
  668. gui.endModalLoading();
  669. let content = "";
  670. let allowDelete = true;
  671. let showAssets = false;
  672. if (countRes && countRes.data)
  673. {
  674. const projectId = gui.project().shortId || gui.project()._id;
  675. if (countRes.data.countPatches > 1)
  676. {
  677. let linkText = countRes.data.countPatches + " other patch";
  678. if (countRes.data.countPatches > 1) linkText += "es";
  679. content += "Some are used in " + linkText;
  680. showAssets = true;
  681. }
  682. if (countRes.data.countOps)
  683. {
  684. let linkText = countRes.data.countPatches + " op";
  685. if (countRes.data.countOps > 1) linkText += "s";
  686. if (countRes.data.countPatches > 1) content += "<br/>";
  687. content += "Some are used in " + linkText;
  688. allowDelete = false;
  689. showAssets = true;
  690. }
  691. }
  692. else
  693. {
  694. content += "They may be used in other patches.";
  695. }
  696. if (showAssets && countRes.data.assets)
  697. {
  698. content += "<br><ul>";
  699. countRes.data.assets.forEach((asset) =>
  700. {
  701. const link = platform.getCablesUrl() + "/asset/patches/?filename=" + asset;
  702. content += "<li>Check usages of <a href='" + link + "' target='_blank'>" + utils.filename(asset) + "</a></li>";
  703. });
  704. content += "</ul>";
  705. }
  706. let title = "Really delete " + selectedFileIds.length + " files?";
  707. if (!allowDelete)
  708. {
  709. title = "You cannot delete all of these files!";
  710. }
  711. const options = {
  712. "title": title,
  713. "html": content,
  714. "warning": true,
  715. "choice": allowDelete,
  716. "okButton": {
  717. "text": "Really delete",
  718. "cssClasses": "redbutton"
  719. }
  720. };
  721. const modal = new ModalDialog(options);
  722. if (allowDelete)
  723. {
  724. modal.on("onSubmit", () =>
  725. {
  726. selectedFileIds.forEach((fileId) =>
  727. {
  728. platform.talkerAPI.send(
  729. TalkerAPI.CMD_DELETE_FILE,
  730. {
  731. "fileid": fileId
  732. },
  733. (err, r) =>
  734. {
  735. if (r.success)
  736. {
  737. this._manager.removeItem(fileId);
  738. this.reload();
  739. }
  740. else
  741. {
  742. notifyError("error: could not delete file", err);
  743. this._log.warn(err);
  744. }
  745. this._manager.unselectAll();
  746. }
  747. );
  748. });
  749. });
  750. }
  751. }
  752. );
  753. }
  754. );
  755. }
  756. }
  757. }
  758. createFile()
  759. {
  760. new ModalDialog({
  761. "prompt": true,
  762. "title": "Create new file",
  763. "text": "Enter filename",
  764. "promptValue": "newfile.txt",
  765. "promptOk": (fn) =>
  766. {
  767. platform.talkerAPI.send(TalkerAPI.CMD_CREATE_NEW_FILE, { "name": fn }, (err, res) =>
  768. {
  769. if (err)
  770. {
  771. notifyError("Error: " + err.msg);
  772. gui.refreshFileManager();
  773. return;
  774. }
  775. if (res) notify("file created");
  776. gui.refreshFileManager();
  777. });
  778. }
  779. });
  780. }
  781. /**
  782. * @param {string} filename
  783. * @param {string} content
  784. * @param {Function} [cb]
  785. * @param {string} patchId
  786. */
  787. uploadFile(filename, content, cb = null, patchId = null)
  788. {
  789. gui.jobs().finish("uploadfile" + filename);
  790. gui.jobs().start({ "id": "uploadfile" + filename, "title": "uploading file " + filename });
  791. const data = {
  792. "fileStr": content,
  793. "filename": filename
  794. };
  795. if (patchId) data.patchId = patchId;
  796. platform.talkerAPI.send(
  797. TalkerAPI.CMD_UPLOAD_FILE, data, (err3, res3) =>
  798. {
  799. gui.savedState.setSaved("editorOnChangeFile");
  800. gui.jobs().finish("uploadfile" + filename);
  801. gui.refreshFileManager();
  802. if (cb)cb(err3, res3);
  803. }
  804. );
  805. }
  806. replaceAssetPorts(search, replace, cb = null)
  807. {
  808. const ops = gui.corePatch().ops;
  809. let numPorts = 0;
  810. for (let i = 0; i < ops.length; i++)
  811. {
  812. for (let j = 0; j < ops[i].portsIn.length; j++)
  813. {
  814. if (ops[i].portsIn[j].uiAttribs && ops[i].portsIn[j].uiAttribs.display && ops[i].portsIn[j].uiAttribs.display == "file")
  815. {
  816. this._log.log("filename:", ops[i].portsIn[j].get());
  817. let v = ops[i].portsIn[j].get();
  818. if (v) this._log.log("srch index", v.indexOf(search));
  819. if (v && v.indexOf(search) == 0)
  820. {
  821. numPorts++;
  822. this._log.log("found str!");
  823. v = replace + v.substring(search.length);
  824. ops[i].portsIn[j].set(v);
  825. this._log.log("result filename:", v);
  826. }
  827. }
  828. }
  829. }
  830. if (cb) cb(numPorts);
  831. }
  832. copyFileToPatch(url, options = null)
  833. {
  834. platform.talkerAPI.send(TalkerAPI.CMD_CONVERT_FILE, {
  835. "url": url,
  836. "converterId": "copytopatch",
  837. "options": options
  838. }, (err, res) =>
  839. {
  840. if (err)
  841. {
  842. if (err.msg === "OVER_QUOTA")
  843. {
  844. notifyError("Over storage quota!");
  845. }
  846. else
  847. {
  848. notifyError("Failed to copy file", err.msg);
  849. }
  850. gui.opParams.refresh();
  851. gui.refreshFileManager();
  852. }
  853. else
  854. {
  855. if (res && res.converterResult && res.converterResult.sourceUrl && res.converterResult.targetUrl)
  856. {
  857. this.replaceAssetPorts(res.converterResult.sourceUrl, res.converterResult.targetUrl, (numPorts) =>
  858. {
  859. gui.setStateUnsaved();
  860. notify("Copied file, updated " + numPorts + " ports");
  861. gui.opParams.refresh();
  862. gui.refreshFileManager();
  863. });
  864. }
  865. }
  866. });
  867. }
  868. }