js/trans.js

  1. /**=====LICENSE STATEMENT START=====
  2. Translator++
  3. CAT (Computer-Assisted Translation) tools and framework to create quality
  4. translations and localizations efficiently.
  5. Copyright (C) 2018 Dreamsavior<dreamsavior@gmail.com>
  6. This program is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. =====LICENSE STATEMENT END=====*/
  17. /**
  18. * @file trans.js The core class of Translator++
  19. * @author Dreamsavior
  20. * File version: 2024-04-03 14:22:34.304
  21. */
  22. /**
  23. * Executed each time trans file is loaded or initialized
  24. * @event Trans#transLoaded
  25. */
  26. window.fs = require('graceful-fs');
  27. window.afs = require('await-fs');
  28. window.nwPath = require('path');
  29. window.spawn = require('child_process').spawn;
  30. window.debounce = require("debounce");
  31. window.BatchTranslate = require('www/js/BatchTranslate.js');
  32. //================================================================
  33. //
  34. // COMMON FUNCTION
  35. //
  36. //================================================================
  37. /**
  38. * Insert an array into another array at some index
  39. * @global
  40. * @param {Array} array - Source array
  41. * @param {Number} index - Index to insert at
  42. * @param {Array} arrayToInsert - Array to insert
  43. * @returns {Array} - Merged array
  44. */
  45. window.insertArrayAt = function(array, index, arrayToInsert) {
  46. Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
  47. return array;
  48. }
  49. global.common ||= {}
  50. common.arrayExchange = function(arr, fromIndex, toIndex) {
  51. // exchange an array value by index (single)
  52. var element = arr[fromIndex];
  53. arr.splice(fromIndex, 1);
  54. arr.splice(toIndex, 0, element);
  55. }
  56. common.arrayExchangeBatch = function(input, fromIndex, toIndex) {
  57. // exchange an array value by indexes(array)
  58. if (Array.isArray(fromIndex) == false) {
  59. common.arrayExchange(input, fromIndex, toIndex);
  60. }
  61. for (var i=fromIndex.length-1; i>=0; i--) {
  62. common.arrayExchange(input, fromIndex[i], toIndex);
  63. }
  64. return input;
  65. }
  66. common.arrayMove = function(array, fromIndex, to) {
  67. // move an array index to new index
  68. if(Array.isArray(array) == false) return array;
  69. if( to === fromIndex ) return array;
  70. var target = array[fromIndex];
  71. var increment = to < fromIndex ? -1 : 1;
  72. for(var k = fromIndex; k != to; k += increment){
  73. array[k] = array[k + increment];
  74. }
  75. array[to] = target;
  76. return array;
  77. }
  78. common.arrayMoveBatch = function(array, fromIndex, to) {
  79. if (Array.isArray(fromIndex) == false) {
  80. return common.arrayMove(array, fromIndex, to);
  81. }
  82. var n=0;
  83. for (var i=fromIndex.length-1; i>=0; i--) {
  84. array = common.arrayMove(array, fromIndex[i]+n, to);
  85. n++;
  86. }
  87. return array;
  88. }
  89. common.escapeSelector = function(string) {
  90. string = string||"";
  91. if (typeof string !== 'string') return false;
  92. //return string.replace( /(:|\.|\[|\]|,|=|@)/g, "\\$1" );
  93. //return string.replace( /(:|\.|\[|\]|,|=|@|\s|\(|\))/g, "\\$1" );
  94. //return '"'+string+'"';
  95. return ('"'+CSS.escape(string)+'"')
  96. }
  97. common.arrayInsert =function(thisArray, index, item ) {
  98. thisArray.splice( index, 0, item );
  99. return thisArray;
  100. };
  101. common.batchArrayInsert = function(thisArray, index, item ) {
  102. for (var i=0; i<thisArray.length; i++) {
  103. this.arrayInsert(thisArray[i], index, item);
  104. }
  105. return thisArray;
  106. };
  107. var FileLoader = function() {
  108. this.handler = {};
  109. }
  110. FileLoader.prototype.add = function(extension, handler) {
  111. // handler is function with arguments : filepath
  112. this.handler[extension] = handler;
  113. }
  114. FileLoader.prototype.open = function(extension, handler) {
  115. // handler is function with arguments : filepath
  116. //this.handler['extension'] = handler;
  117. }
  118. window.FileLoader = FileLoader;
  119. //================================================================
  120. //
  121. // T R A N S C L A S S
  122. //
  123. //================================================================
  124. /**
  125. * @class
  126. * @classdesc
  127. * The core class of Translator++
  128. * Handle basic logic of Translator++ application
  129. * This class will have one instance for each window. Which is `window.trans`
  130. */
  131. class Trans extends require('www/js/BasicEventHandler.js') {
  132. constructor() {
  133. super($(document));
  134. this.init();
  135. }
  136. }
  137. /**
  138. * Maximum column allowed in the grid
  139. */
  140. Trans.maxCols = 15;
  141. /**
  142. * Handle cell level information
  143. * @class
  144. * @since 4.4.4
  145. * @classdesc
  146. * Manage cell's additional informations
  147. */
  148. Trans.CellInfo = function() {
  149. }
  150. /**
  151. * Get all cell information
  152. * @param {String} file - The file ID
  153. * @returns {Array} - The cell information
  154. */
  155. Trans.CellInfo.prototype.getAll = function(file) {
  156. if (!file) return;
  157. if (!trans?.project?.files?.[file]) return;
  158. var obj = trans.getObjectById(file);
  159. if (!obj.cellInfo) obj.cellInfo = [];
  160. return obj.cellInfo;
  161. }
  162. /**
  163. * Get row information
  164. * @param {String} file - The file ID
  165. * @param {Number} row - The row number
  166. * @returns {Array} - The row information
  167. */
  168. Trans.CellInfo.prototype.getRow = function(file, row) {
  169. var cellInf = this.getAll(file);
  170. if (!cellInf) return;
  171. return cellInf[row];
  172. }
  173. /**
  174. * Get cell information
  175. * @param {String} file - The file ID
  176. * @param {Number} row - The row number
  177. * @param {Number} col - The column number
  178. * @returns {Object} - The cell information
  179. */
  180. Trans.CellInfo.prototype.getCell = function(file, row, col) {
  181. var rowInf = this.getRow(file, row);
  182. if (!rowInf) return;
  183. return rowInf[col];
  184. }
  185. /**
  186. * Get the best translation cell information
  187. * @param {String} file - The file ID
  188. * @param {Number} row - The row number
  189. * @param {String} key - The key to get
  190. * @returns {Object} - The cell information
  191. */
  192. Trans.CellInfo.prototype.getBestCellInfo = function(file, row, key) {
  193. var data = trans.getData(file);
  194. var col = trans.getTranslationColFromRow(data[row]);
  195. var cellInfo = this.getCell(file, row, col);
  196. if (!cellInfo) return cellInfo;
  197. if (key) return cellInfo[key];
  198. return cellInfo;
  199. }
  200. /**
  201. * Get configuration of a cell
  202. * @param {String} key - The key to get
  203. * @param {String} file - The file ID
  204. * @param {Number} row - The row number
  205. * @param {Number} col - The column number
  206. * @returns {*} - The value of the key
  207. */
  208. Trans.CellInfo.prototype.get = function(key, file, row, col) {
  209. var cellInf = this.getCell(file, row, col);
  210. if (!cellInf) return;
  211. return cellInf[key];
  212. }
  213. /**
  214. * Set cell information
  215. * @param {String} key - The key to set
  216. * @param {*} value - The value to set
  217. * @param {String} file - The file ID
  218. * @param {Number} row - The row number
  219. * @param {Number} col - The column number
  220. * @returns {Boolean} - True if success
  221. */
  222. Trans.CellInfo.prototype.set = function(key, value, file, row, col) {
  223. //console.log("Setting cell info with options:", arguments);
  224. var cellInf = this.getAll(file);
  225. cellInf[row] = cellInf[row] || [];
  226. cellInf[row][col] = cellInf[row][col] || {};
  227. cellInf[row][col][key] = value;
  228. return true;
  229. }
  230. /**
  231. * Delete cell information
  232. * @param {String} key - The key to delete
  233. * @param {String} file - The file ID
  234. * @param {Number} row - The row number
  235. * @param {Number} col - The column number
  236. * @returns {Boolean} - True if success
  237. */
  238. Trans.CellInfo.prototype.delete = function(key, file, row, col) {
  239. //console.log("Setting cell info with options:", arguments);
  240. var cellInf = this.getAll(file);
  241. cellInf[row] = cellInf[row] || [];
  242. cellInf[row][col] = cellInf[row][col] || {};
  243. delete cellInf[row][col][key]
  244. return true;
  245. }
  246. /**
  247. * Delete row information
  248. * @param {String} file - The file ID
  249. * @param {Number} row - The row number
  250. * @returns {Boolean} - True if success
  251. */
  252. Trans.CellInfo.prototype.deleteRow = function(file, row) {
  253. var cellInf = this.getAll(file)
  254. if (empty(cellInf)) return;
  255. if (Array.isArray(cellInf)) {
  256. cellInf.splice(row, 1);
  257. } else {
  258. delete cellInf[row];
  259. }
  260. }
  261. // Trans.CellInfo.prototype.moveColumn = function(file, from, to) {
  262. // var cellInf = this.getAll(file)
  263. // if (empty(cellInf)) return;
  264. // if (Array.isArray(cellInf)) {
  265. // cellInf.splice(row, 1);
  266. // } else {
  267. // delete cellInf[row];
  268. // }
  269. // return true;
  270. // }
  271. Trans.CellInfo.prototype.deleteCell = function(file, rowId, cellId) {
  272. var thisRow = this.getRow(file, rowId);
  273. if (!Array.isArray(thisRow)) return;
  274. thisRow.splice(cellId, 1);
  275. return true;
  276. }
  277. Trans.CellInfo.prototype.moveCell = function(file, rowId, from, to) {
  278. var thisRow = this.getRow(file, rowId);
  279. if (!Array.isArray(thisRow)) return;
  280. common.arrayMoveBatch(thisRow, from, to);
  281. return true;
  282. }
  283. /**
  284. * Create a new event with JQuery eventing convenience
  285. * Equal to `$(document).on()`
  286. * @param {String} evt - Event name
  287. * @param {Function} fn - Function to trigger
  288. * @since 4.3.20
  289. * trans.on('transLoaded', (e, opt)=> {
  290. * // do something
  291. * })
  292. */
  293. /**
  294. * Removes an event
  295. * Equal to `$(document).off()`
  296. * @param {String} evt - Event name
  297. * @param {Function} fn - Function to trigger
  298. * @since 4.3.20
  299. * @example
  300. * trans.off('transLoaded', (e, opt)=> {
  301. * // do something
  302. * })
  303. */
  304. /**
  305. * Run the event once
  306. * Trigger an event and immediately removes it
  307. * Equal to `$(document).one()`
  308. * @param {String} evt - Event name
  309. * @param {Function} fn - Function to trigger
  310. * @since 4.3.20
  311. */
  312. /**
  313. * Trigger an event
  314. * Equal to `$(document).trigger()`
  315. * @param {String} evt - Event name
  316. * @param {Function} fn - Function to trigger
  317. * @since 4.3.20
  318. */
  319. /**
  320. * Initialization of the Trans object
  321. */
  322. Trans.prototype.init = function() {
  323. this.config ={
  324. loadRomaji :true,
  325. maxRequestLength:3000,
  326. autoSaveEvery :600,
  327. batchDelay :5000,
  328. rpgTransFormat :true,
  329. autoTranslate :false
  330. },
  331. /**
  332. * Index of key column. The column to store original texts.
  333. * @default 0
  334. */
  335. this.keyColumn = 0;
  336. this.isFreeEditing = false;
  337. this.gameTitle =""
  338. this.gameEngine =""
  339. this.projectId =""
  340. this.indexIds ={}
  341. this.fileListLoaded =false
  342. this.isLoadingFileList =false
  343. this.unsavedChange =false
  344. //files:{},
  345. this.gameFolder = ''
  346. this.currentFile = '' //current .trans file
  347. this.skipElement =['note', 'Comment', 'Script']
  348. /**
  349. * The current project
  350. */
  351. this.project =undefined
  352. this.timers ={}
  353. /**
  354. * The current active data on the grid
  355. */
  356. this.data =[];
  357. this.colHeaders =[t('Original Text'), t('Initial'), t('Machine translation'), t('Better translation'), t('Best translation')];
  358. this.onFileNavLoaded = function() {}
  359. this.onFileNavUnloaded = function() {}
  360. this.validateKey = function(value, callback) {
  361. console.log("key validator", value);
  362. if (value=='' || value==null) {
  363. callback(false);
  364. } else {
  365. callback(true);
  366. }
  367. }
  368. this.columns = [{
  369. readOnly: false,
  370. validator: this.validateKey,
  371. width: 150,
  372. //trimWhitespace: false
  373. },
  374. {
  375. readOnly: false,
  376. //trimWhitespace: false
  377. },
  378. {
  379. readOnly: false,
  380. //trimWhitespace: false
  381. },
  382. {
  383. readOnly: false,
  384. //trimWhitespace: false
  385. },
  386. {
  387. readOnly: false,
  388. //trimWhitespace: false
  389. }
  390. ];
  391. this.default = {};
  392. this.default.columns = [{
  393. readOnly: false,
  394. validator: this.validateKey,
  395. //trimWhitespace: false
  396. },
  397. {
  398. readOnly: false,
  399. //trimWhitespace: false
  400. },
  401. {
  402. readOnly: false,
  403. //trimWhitespace: false
  404. },
  405. {
  406. readOnly: false,
  407. //trimWhitespace: false
  408. },
  409. {
  410. readOnly: false,
  411. //trimWhitespace: false
  412. }
  413. ]
  414. /**
  415. * Whether trans is currently handling a project or not.
  416. */
  417. this.inProject = false;
  418. this.default.colHeaders =[t('Original Text'), t('Initial'), t('Machine translation'), t('Better translation'), t('Best translation')];
  419. }
  420. Trans.prototype.isTrans = function(obj) {
  421. if (!obj) return false;
  422. if (obj.constructor.name!=="Object" && obj.constructor.name!=="Trans") return false;
  423. if (!obj?.project?.files) return false;
  424. return true;
  425. }
  426. /**
  427. * Get project's option
  428. * Option are user editable configuration
  429. * @param {String} key
  430. */
  431. Trans.prototype.getOption = function(key) {
  432. if (!trans.project) return;
  433. trans.project.options ||= {};
  434. // override default behavior
  435. if (typeof trans.project.options.gridInfo == "undefined") {
  436. trans.project.options.gridInfo = {
  437. isRuleActive : true,
  438. enableTrail : true,
  439. viewTrail : false,
  440. viewOrganicCellMarker:true,
  441. rowHeaderInfo : false
  442. }
  443. }
  444. return trans.project.options[key];
  445. }
  446. Trans.prototype.setOption = function(key, value) {
  447. if (!trans.project) return;
  448. console.log("Setting option", key, value);
  449. trans.project.options ||= {};
  450. trans.project.options[key] = value;
  451. }
  452. /**
  453. * Get project configuration
  454. * Config are system defined configuration. Should not editable by user.
  455. * @param {String} key - The configuration key
  456. * @returns {*} - The configuration related to the Key
  457. */
  458. Trans.prototype.getConfig = function(key) {
  459. trans.project.config = trans.project.config || {};
  460. if (typeof key == "string") return trans.project.config[key];
  461. if (Array.isArray(key)) {
  462. var result = trans.project.config;
  463. try {
  464. for (var i=0; i<key.length; i++) {
  465. result = result[key[i]];
  466. }
  467. return result;
  468. } catch (e) {
  469. return;
  470. }
  471. }
  472. return;
  473. }
  474. /**
  475. * Set key-value pair of configuration
  476. * @param {(String|String[])} key - The key
  477. * @param {*} value - The value
  478. * @returns {Boolean} - True if success
  479. */
  480. Trans.prototype.setConfig = function(key, value) {
  481. trans.project.config = trans.project.config || {};
  482. if (typeof key == "string") {
  483. trans.project.config[key] = value;
  484. return true;
  485. }
  486. if (Array.isArray(key)) {
  487. var result = trans.project.config;
  488. try {
  489. for (var i=0; i<key.length-1; i++) {
  490. result[key[i]] = result[key[i]] || {};
  491. result = result[key[i]];
  492. }
  493. result[key[i]] = value;
  494. return true;
  495. } catch (e) {
  496. return;
  497. }
  498. }
  499. return;
  500. }
  501. /**
  502. * Check if a project is currently opened
  503. * @returns {Boolean} - Returns true if trans is in a project
  504. * @since 6.1.18
  505. */
  506. Trans.prototype.isInProject = function() {
  507. return this.inProject;
  508. }
  509. /**
  510. * Get the template path
  511. * @returns {String} - The path to the template file
  512. */
  513. Trans.prototype.getTemplatePath = function() {
  514. var templatePath = sys.config.templatePath||nw.App.manifest.localConfig.defaultTemplate
  515. fs = fs||require('fs')
  516. try {
  517. if (fs.existsSync(templatePath)) {
  518. return templatePath;
  519. }
  520. } catch (err) {
  521. return nwPath.join(__dirname, templatePath);
  522. }
  523. }
  524. /**
  525. * merge reference into files object in transObj.project
  526. * @function
  527. * @param {object} transObj instance of trans object
  528. * @returns {object} instance of trans object
  529. */
  530. Trans.prototype.mergeReference = function(transObj) {
  531. console.log("Merging reference");
  532. transObj = transObj||{};
  533. transObj.project = transObj.project||{};
  534. transObj.project.references = transObj.project.references||{};
  535. transObj.project.files = transObj.project.files||{};
  536. for (let ref in transObj.project.references) {
  537. console.log("assigning : ", ref);
  538. transObj.project.files[ref] = this.project.references[ref];
  539. }
  540. return transObj;
  541. }
  542. /**
  543. * determine wether the pathname is supported file formats
  544. * @function
  545. * @param {string} pathName
  546. * @returns {boolean} True if file is supported, otherwise false.
  547. */
  548. Trans.prototype.isFileSupported = function(pathName) {
  549. if (typeof pathName !== 'string') return false;
  550. var ext = common.getFileExtension(pathName);
  551. if (sys.supportedExtension.includes(ext)) return true;
  552. return false;
  553. }
  554. /**
  555. * do some action depending on the file type
  556. * @function
  557. * @param {string} file path to the file
  558. */
  559. Trans.prototype.openFile = function(file) {
  560. const spawn = require("child_process").spawn;
  561. if(this.isFileSupported(file) == false) return false;
  562. var ext = common.getFileExtension(file);
  563. if (typeof (this.fileLoader.handler[ext]) !== 'function') return false;
  564. if (this.fileListLoaded == false) {
  565. // load in this window
  566. ui.introWindowClose();
  567. this.fileLoader.handler[ext].apply(this, [file]);
  568. } else {
  569. // load on new window
  570. //var spawn = spawn || require('child_process').spawn;
  571. spawn(nw.process.execPath, [file], {
  572. detached :true
  573. });
  574. }
  575. }
  576. /**
  577. * Initialize the project
  578. * @function
  579. * @todo Implement this function
  580. */
  581. Trans.prototype.initProject = function() {
  582. if (typeof this.project !== 'undefined') {
  583. console.log("project is already been initialized! skipping!");
  584. return false
  585. }
  586. // this function is not done yet
  587. }
  588. /**
  589. * Close the current project
  590. * @function
  591. *
  592. */
  593. Trans.prototype.closeProject = function() {
  594. if (typeof this.project == 'undefined') {
  595. return false
  596. }
  597. if (typeof this.grid.destroy() == 'function') this.grid.destroy();
  598. this.unInitFileNav();
  599. this.unInitLocalStorage();
  600. this.project = {};
  601. this.init();
  602. ui.tableCornerHideLoading(true);
  603. ui.closeAllChildWindow();
  604. ui.ribbonMenu.clear();
  605. ui.clearActiveCellInfo();
  606. ui.clearPathInfo();
  607. ui.setWindowTitle("");
  608. trans.clearFooter();
  609. this.initTable();
  610. this.gridIsModified(false);
  611. }
  612. /**
  613. * Generates new dictionary table
  614. * @function
  615. * @returns {object} references object (trans.project.references)
  616. */
  617. Trans.prototype.generateNewDictionaryTable = function() {
  618. var thisID = "Common Reference";
  619. if (typeof this.project.files[thisID] !== 'undefined') return this.project.files[thisID];
  620. if (typeof this.project.references == 'object') {
  621. console.log("trans.project.reference is an object");
  622. for (var fileId in this.project.references) {
  623. this.project.files[fileId] = this.project.references[fileId];
  624. }
  625. } else {
  626. console.log("trans.project.reference is not an object");
  627. var templatePath = this.getTemplatePath()
  628. var templateObj = this.loadJSONSync(templatePath);
  629. console.log("template obj : ", templateObj);
  630. if (Boolean(templateObj) !== false) {
  631. this.project.references = templateObj.project.references;
  632. console.log("assigning reference : ", this.project.references);
  633. }
  634. this.mergeReference(trans);
  635. }
  636. return this.project.references;
  637. }
  638. /**
  639. * Initialize a new project
  640. * @function
  641. * @param {object} options
  642. * force
  643. * selectedFile {array}
  644. */
  645. Trans.prototype.createProject = function(options) {
  646. console.log("running trans.createProject");
  647. if (this.isLoadingFileList) return false;
  648. if (this.gameFolder == "") return false;
  649. var trans = this;
  650. options = options||{};
  651. options.force = options.force||"";
  652. options.selectedFile = options.selectedFile||"";
  653. options.onAfterLoading = options.onAfterLoading||function(responseData, event) {}; // eslint-disable-line
  654. options.options = options.options||{};
  655. this.isLoadingFileList = true;
  656. ui.showLoading();
  657. var thisArgs = {
  658. gameFolder :this.gameFolder,
  659. selectedFile :options.selectedFile,
  660. gameEngine :this.gameEngine,
  661. gameTitle :this.gameTitle,
  662. projectId :this.projectId,
  663. skipElement :this.skipElement,
  664. indexOriginal :0,
  665. indexTranslation:1,
  666. force :options.force,
  667. rpgTransFormat :trans.config.rpgTransFormat,
  668. options :options.options
  669. }
  670. console.log("Sending this args to loadGameInfo.php : ", thisArgs);
  671. php.spawn("loadGameInfo.php", {
  672. args:thisArgs,
  673. onData: function(buffer) {
  674. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput'});
  675. },
  676. onError:function(buffer) {
  677. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput', classStr:'stderr'});
  678. },
  679. onDone : function(data) {
  680. console.log("onDone event defined from trans.js");
  681. if (common.isJSON(data)) {
  682. trans.project = data;
  683. trans.currentFile = "";
  684. trans.gameTitle = data.gameTitle;
  685. trans.gameFolder = data.loc;
  686. trans.projectId = data.projectId;
  687. trans.gameEngine = data.gameEngine;
  688. trans.editorName = "Translator++";
  689. trans.editorVersion = nw.App.manifest.version;
  690. trans.generateHeader();
  691. trans.sanitize();
  692. //trans.removeAllDuplicates();
  693. trans.dataPadding();
  694. sys.updateLastOpenedProject();
  695. trans.autoSave();
  696. //JSON.parse(data);
  697. console.log(data);
  698. ui.setStatusBar(1, trans.gameTitle);
  699. /**
  700. * Executed when a project is created
  701. * @event Trans#projectCreated
  702. * @param {Trans} trans - Instance of the current trans data
  703. * @param {Object} data
  704. */
  705. trans.trigger("projectCreated", trans, data);
  706. if (typeof options.onAfterLoading == 'function') {
  707. options.onAfterLoading.call(trans, data, this);
  708. }
  709. trans.fileListLoaded = true;
  710. trans.isLoadingFileList = false;
  711. ui.showCloseButton();
  712. } else {
  713. // try to find link from console response
  714. var loadedData = $("<div>"+data+"</div>");
  715. var initPath = loadedData.find("#initialDataPath").attr("data-path");
  716. console.log("found initPath : "+initPath);
  717. //var initData = loadedData.find("#initialData").text();
  718. //console.log(JSON.parse(initData));
  719. if (Boolean(initPath) == false) {
  720. ui.loadingProgress("Error!", "Can not successfully parse your game! Read the documentation here: https://dreamsavior.net/?p=1311",
  721. {consoleOnly:true, mode:'consoleOutput'});
  722. ui.showCloseButton();
  723. trans.fileListLoaded = false;
  724. trans.isLoadingFileList = false;
  725. return;
  726. }
  727. try {
  728. fs.readFile(initPath, function (err, rawData) {
  729. if (err) {
  730. console.log("error opening file : "+initPath);
  731. ui.loadingProgress("Error!", "Error opening file : "+initPath,
  732. {consoleOnly:true, mode:'consoleOutput'});
  733. ui.showCloseButton();
  734. trans.fileListLoaded = false;
  735. trans.isLoadingFileList = false;
  736. throw err;
  737. } else {
  738. var strData = rawData.toString();
  739. var data = {};
  740. try {
  741. data = JSON.parse(strData);
  742. } catch (err) {
  743. ui.loadingProgress(t("Error!"), t("Error processing init file : ")+initPath+"\n"+err,
  744. {consoleOnly:true, mode:'consoleOutput'});
  745. ui.showCloseButton();
  746. trans.isLoadingFileList = false;
  747. return false;
  748. }
  749. if (Boolean(data['files']) == false) {
  750. ui.loadingProgress(t("Error!"), t("Error! File list not found in init file at : ")+initPath,
  751. {consoleOnly:true, mode:'consoleOutput'});
  752. ui.loadingProgress(t("Error!"), t("This means that your game was not successfully parsed. Please visit https://dreamsavior.net/?p=1311 for possible solution for this issue."),
  753. {consoleOnly:true, mode:'consoleOutput'});
  754. ui.showCloseButton();
  755. trans.isLoadingFileList = false;
  756. return false;
  757. }
  758. trans.project = data;
  759. trans.currentFile = "";
  760. trans.gameTitle = data.gameTitle;
  761. trans.gameFolder = data.loc;
  762. trans.projectId = data.projectId;
  763. trans.gameEngine = data.gameEngine;
  764. trans.editorName = "Translator++";
  765. trans.editorVersion = nw.App.manifest.version;
  766. trans.generateHeader();
  767. trans.sanitize();
  768. //trans.removeAllDuplicates();
  769. trans.dataPadding();
  770. sys.updateLastOpenedProject();
  771. trans.autoSave();
  772. //JSON.parse(data);
  773. console.log(data);
  774. ui.setStatusBar(1, trans.gameTitle);
  775. trans.trigger("projectCreated", trans, data);
  776. if (typeof options.onAfterLoading == 'function') {
  777. options.onAfterLoading.call(trans, data, this);
  778. }
  779. trans.fileListLoaded = true;
  780. trans.isLoadingFileList = false;
  781. ui.loadingProgress(t("Done!"), t("All done!"), {consoleOnly:false, mode:'consoleOutput'});
  782. ui.loadingEnd();
  783. }
  784. });
  785. } catch (error) {
  786. console.log("error opening file : "+initPath);
  787. ui.loadingProgress(t("Error!"), t("Error opening file : ")+initPath, {consoleOnly:false, mode:'consoleOutput'});
  788. ui.loadingProgress(t("Error!"), error, {consoleOnly:true, mode:'consoleOutput'});
  789. ui.loadingEnd();
  790. trans.fileListLoaded = false;
  791. trans.isLoadingFileList = false;
  792. }
  793. var $tmpPath = loadedData.find("#tmpPath");
  794. if ($tmpPath.length > 0) {
  795. ui.showOpenCacheButton($tmpPath.text());
  796. }
  797. }
  798. }
  799. });
  800. }
  801. Trans.prototype.procedureCreateProject =function(gamePath, options) {
  802. console.log("running trans.procedureCreateProject");
  803. console.log(arguments);
  804. if (typeof gamePath == 'undefined') return false;
  805. options = options||{};
  806. options.selectedFile = options.selectedFile||"";
  807. options.force = options.force||"";
  808. options.projectInfo = options.projectInfo||{
  809. id :"",
  810. title :""
  811. }
  812. options.options = options.options||{};
  813. options.gameEngine = options.gameEngine||"";
  814. //console.log(options);
  815. this.closeProject();
  816. this.projectId = options.projectInfo.id;
  817. this.gameTitle = options.projectInfo.title;
  818. this.gameFolder = gamePath;
  819. this.gameEngine = options.gameEngine;
  820. //console.log("=======================");
  821. //console.log("Running trans.initFileNav() with current trans : ");
  822. //console.log(trans);
  823. // close newProject dialog box if any
  824. ui.newProjectDialog.close();
  825. this.createProject({
  826. selectedFile:options.selectedFile,
  827. force:options.force,
  828. onAfterLoading:async function(rawData) { // eslint-disable-line
  829. this.drawFileSelector();
  830. // record the project creation options
  831. this.project.options = this.project.options || {};
  832. this.project.options.init = options.options || {};
  833. if (engines.hasHandler('onAfterCreateProject')) {
  834. await common.wait(100);
  835. await engines.handler('onAfterCreateProject').call(this, gamePath, options);
  836. }
  837. },
  838. options:options.options
  839. });
  840. }
  841. Trans.prototype.getRow = function(fileData, keyword) {
  842. // locate a row number of a key
  843. // returns row number
  844. if (typeof keyword !== 'string') return undefined;
  845. console.log("Get row", arguments);
  846. if (fileData.indexIsBuilt == false) {
  847. console.log("building index for the first time");
  848. this.buildIndexFromData(fileData);
  849. }
  850. fileData.indexIds = fileData.indexIds || {};
  851. console.log("getRow result is : ", fileData.indexIds[keyword]);
  852. return fileData.indexIds[keyword];
  853. }
  854. /**
  855. * update current trans with new jsonData
  856. * @param {Trans} jsonData - jsonData must contains jsonData.project.files
  857. * @param {*} options
  858. * @returns {Trans} - An updated trans data
  859. */
  860. Trans.prototype.updateProject = function(jsonData, options) {
  861. /* update current trans with new jsonData
  862. jsonData must contains :
  863. jsonData.project.files
  864. */
  865. if (typeof jsonData == 'string') jsonData = JSON.parse(jsonData);
  866. options = options||{};
  867. options.onAfterLoading = options.onAfterLoading||function(type, responseData, event) {};
  868. options.onSuccess = options.onSuccess||function(responseData, event) {};
  869. options.onFailed = options.onFailed||function(responseData, event) {};
  870. options.filePath = options.filePath||"";
  871. options.purgeNonExistingData ||= false;
  872. jsonData.project = jsonData.project || {};
  873. jsonData.project.files = jsonData.project.files || {};
  874. const projectCopy = jsonData;
  875. const oldProject = this.getSaveData();
  876. const oldFiles = oldProject.project.files||{};
  877. console.log("Base data", jsonData);
  878. console.log("Preserved current files", oldFiles);
  879. projectCopy.project.files = jsonData.project.files;
  880. for (let file in jsonData.project.files) {
  881. var thisFile = projectCopy.project.files[file];
  882. if (!oldFiles[file]) continue;
  883. if (!oldFiles[file].data) continue;
  884. if (oldFiles[file].data.length < 1) continue;
  885. console.log("%cprocessing file", "color:aqua", file);
  886. if (options.purgeNonExistingData) {
  887. // new trans as pointer, good if we don't want to preserve existing record
  888. for (let rowId=0; rowId < thisFile.data.length; rowId++ ) {
  889. let key = thisFile.data[rowId][0];
  890. var oldFileRow = this.getRow(oldFiles[file], key);
  891. console.log("%cKey", "color:aqua", key);
  892. console.log("%coldFileRow", "color:aqua", oldFileRow);
  893. if (typeof oldFileRow == 'undefined') continue;
  894. if (!oldFiles[file].data[oldFileRow]) continue;
  895. for (let x=1; x<oldFiles[file].data[oldFileRow].length; x++) {
  896. //console.log("%c--Assigning ", "color:aqua", oldFiles[file].data[oldFileRow][x], "to col", x);
  897. thisFile.data[rowId][x] = oldFiles[file].data[oldFileRow][x];
  898. }
  899. }
  900. } else {
  901. // preserve the old record that not exist in the newly updated data
  902. let thisOldFile = oldFiles[file];
  903. let contextCounter = 0;
  904. for (let rowId=0; rowId < thisOldFile.data.length; rowId++ ) {
  905. if (!thisOldFile.data[rowId]?.length) continue;
  906. let key = thisOldFile.data[rowId][0];
  907. if (!key) continue;
  908. var fileRow = this.getRow(thisFile, key);
  909. // console.log("%cKey", "color:aqua", key);
  910. // console.log("%coldFileRow", "color:aqua", fileRow);
  911. if (typeof fileRow == 'undefined') {
  912. //console.log("%cHandling non existing record", "color:aqua", thisOldFile.data[rowId]);
  913. let newLen = thisFile.data.push(thisOldFile.data[rowId]);
  914. let newIndex = newLen-1;
  915. // assign indexIds
  916. thisFile.data.indexIds ||= {};
  917. thisFile.data.indexIds[key] = newIndex;
  918. // assing context
  919. thisFile.context[newIndex] = ["RefreshCarryover/"+contextCounter]
  920. // assign cellInfo
  921. if (thisOldFile.cellInfo?.[rowId]) {
  922. thisFile.cellInfo ||= [];
  923. thisFile.cellInfo[newIndex] = thisOldFile.cellInfo[rowId]
  924. }
  925. if (thisOldFile.comments?.[rowId]) {
  926. thisFile.comments ||= [];
  927. thisFile.comments[newIndex] = thisOldFile.comments[rowId]
  928. }
  929. if (thisOldFile.parameters?.[rowId]) {
  930. thisFile.parameters ||= [];
  931. thisFile.parameters[newIndex] = thisOldFile.parameters[rowId]
  932. }
  933. if (thisOldFile.tags?.[rowId]) {
  934. thisFile.tags ||= [];
  935. thisFile.tags[newIndex] = thisOldFile.tags[rowId]
  936. }
  937. contextCounter++;
  938. continue;
  939. }
  940. // for (let x=1; x<thisOldFile.data[rowId].length; x++) {
  941. // //console.log("%c--Assigning ", "color:aqua", thisOldFile.data[rowId][x], "to col", x);
  942. // thisFile.data[fileRow][x] = thisOldFile.data[rowId][x];
  943. // }
  944. // console.log("%c--Assigning ", "color:aqua", thisOldFile.data[rowId], "to row", rowId);
  945. // assign data. Since the key is identical, we can safely copy the entire row
  946. thisFile.data[fileRow] = thisOldFile.data[rowId]
  947. // assign cellInfo
  948. if (thisOldFile.cellInfo?.[rowId]) {
  949. thisFile.cellInfo ||= [];
  950. thisFile.cellInfo[fileRow] = thisOldFile.cellInfo[rowId]
  951. }
  952. if (thisOldFile.comments?.[rowId]) {
  953. thisFile.comments ||= [];
  954. thisFile.comments[fileRow] = thisOldFile.comments[rowId]
  955. }
  956. if (thisOldFile.parameters?.[rowId]) {
  957. thisFile.parameters ||= [];
  958. thisFile.parameters[fileRow] = thisOldFile.parameters[rowId]
  959. }
  960. if (thisOldFile.tags?.[rowId]) {
  961. thisFile.tags ||= [];
  962. thisFile.tags[fileRow] = thisOldFile.tags[rowId]
  963. }
  964. }
  965. }
  966. }
  967. console.log("updatedProject", projectCopy);
  968. return projectCopy;
  969. }
  970. Trans.prototype.updateProject2 = function(updatedTrans, oldTrans = this.getSaveData()) {
  971. return updatedTrans
  972. }
  973. Trans.prototype.openFromTransObj = function(jsonData, options) {
  974. // open trans object from parsed jsonData or string
  975. if (typeof jsonData == 'string') jsonData = JSON.parse(jsonData);
  976. options = options||{};
  977. options.onAfterLoading = options.onAfterLoading||function(type, responseData, event) {};
  978. options.onSuccess = options.onSuccess||function(responseData, event) {};
  979. options.onFailed = options.onFailed||function(responseData, event) {};
  980. options.filePath = options.filePath||"";
  981. options.isNew = options.isNew || false;
  982. if (options.isNew) {
  983. jsonData = this.initTransData(jsonData);
  984. console.log(jsonData);
  985. }
  986. this.currentFile = options.filePath;
  987. this.applySaveData(jsonData);
  988. this.sanitize();
  989. this.grid.render();
  990. sys.insertOpenedFileHistory();
  991. // apply config to $DV.config;
  992. try {
  993. $DV.config.sl = this.project.options.sl||"ja";
  994. $DV.config.tl = this.project.options.tl||"en";
  995. } catch (e) {
  996. $DV.config.sl = "ja";
  997. $DV.config.tl = "en";
  998. }
  999. if (typeof options.onSuccess == 'function') options.onSuccess.call(this, jsonData);
  1000. if (typeof options.onAfterLoading == 'function') options.onAfterLoading.call(this, "success", jsonData);
  1001. this.updateStagingInfo();
  1002. this.isOpeningFile = false;
  1003. ui.hideBusyOverlay();
  1004. if (jsonData.project.selectedId) {
  1005. this.selectFile(jsonData.project.selectedId);
  1006. } else {
  1007. this.selectFile($(".fileList .data-selector").eq(0));
  1008. }
  1009. }
  1010. Trans.prototype.detectFormat = async function(path) {
  1011. if (!path) return false;
  1012. if (nwPath.extname(path).toLowerCase() == ".tpp") return "tpp";
  1013. if (nwPath.extname(path).toLowerCase() == ".trans") return "trans";
  1014. return false;
  1015. }
  1016. Trans.prototype.open = async function(filePath, options) {
  1017. filePath = filePath||this.currentFile;
  1018. if (filePath == "" || filePath == null || typeof filePath == 'undefined') return false;
  1019. console.log("opening project : ", filePath);
  1020. if (await this.detectFormat(filePath) == "tpp") {
  1021. return this.importTpp(filePath);
  1022. }
  1023. var trans = this;
  1024. options = options||{};
  1025. options.onAfterLoading = options.onAfterLoading||function(type, responseData, event) {};
  1026. options.onSuccess = options.onSuccess||function(responseData, event) {};
  1027. options.onFailed = options.onFailed||function(responseData, event) {};
  1028. trans.isOpeningFile = true;
  1029. ui.showBusyOverlay();
  1030. fs.readFile(filePath, function (err, data) {
  1031. if (err) {
  1032. //throw err;
  1033. console.log(err);
  1034. alert(t("error opening file (open): ")+filePath+"\r\n"+err);
  1035. if (typeof data != 'undefined') {
  1036. data = data.toString();
  1037. if (typeof options.onFailed =='function') options.onFailed.call(trans, data);
  1038. if (typeof options.onAfterLoading =='function') options.onAfterLoading.call(trans, "error", data);
  1039. }
  1040. ui.hideBusyOverlay();
  1041. } else {
  1042. data = data.toString();
  1043. var jsonData = {};
  1044. try {
  1045. jsonData = JSON.parse(data);
  1046. } catch (e) {
  1047. console.warn("Failed to parse JSON data");
  1048. alert("Failed to parse JSON data.\nThe .trans file is corrupted.");
  1049. if (typeof options.onAfterLoading == 'function') options.onAfterLoading.call(trans, "Failed", jsonData);
  1050. trans.isOpeningFile = false;
  1051. ui.hideBusyOverlay();
  1052. return;
  1053. }
  1054. console.log(jsonData);
  1055. trans.currentFile = filePath;
  1056. trans.applySaveData(jsonData);
  1057. trans.sanitize();
  1058. trans.grid.render();
  1059. sys.insertOpenedFileHistory();
  1060. // apply config to $DV.config;
  1061. try {
  1062. $DV.config.sl = trans.project.options.sl||"ja";
  1063. $DV.config.tl = trans.project.options.tl||"en";
  1064. } catch (e) {
  1065. $DV.config.sl = "ja";
  1066. $DV.config.tl = "en";
  1067. }
  1068. if (typeof options.onSuccess == 'function') options.onSuccess.call(trans, jsonData);
  1069. if (typeof options.onAfterLoading == 'function') options.onAfterLoading.call(trans, "success", jsonData);
  1070. trans.isOpeningFile = false;
  1071. ui.hideBusyOverlay();
  1072. if (jsonData.project.selectedId) {
  1073. trans.selectFile(jsonData.project.selectedId);
  1074. } else {
  1075. trans.selectFile($(".fileList .data-selector").eq(0));
  1076. }
  1077. trans.gridIsModified(false);
  1078. // open infobox
  1079. trans.project.options = trans.project.options || {}
  1080. console.log("displaying info ")
  1081. if (Boolean(trans.project.options.info) && trans.project.options.displayInfo) {
  1082. ui.showPopup("infobox_"+trans.project.projectId, trans.project.options.info, {
  1083. title : "Project's Info",
  1084. allExternal : true,
  1085. HTMLcleanup : true
  1086. });
  1087. }
  1088. // eval whether has error on paths
  1089. if (trans.isCacheError()) {
  1090. ui.addIconOverlay($(".button-properties"), "attention")
  1091. $(".button-properties").attr("title", "Project properties - Staging path error!")
  1092. } else {
  1093. ui.clearIconOverlay($(".button-properties"))
  1094. $(".button-properties").attr("title", "Project properties");
  1095. }
  1096. }
  1097. });
  1098. }
  1099. Trans.prototype.isCacheError = function() {
  1100. trans.project.cache = trans.project?.cache || {}
  1101. if (trans.project.cache.cachePath) {
  1102. if (common.isDir(trans.project.cache.cachePath) == false) {
  1103. return true;
  1104. }
  1105. }
  1106. return false;
  1107. }
  1108. Trans.prototype.getSl = function() {
  1109. // get source language
  1110. // this.project.options = this.project?.options || {}
  1111. sys.config.default = sys.config.default || {};
  1112. var sl = this.getOption("sl") || sys.config.default?.sl || $DV.config.sl;
  1113. return sl;
  1114. }
  1115. Trans.prototype.getTl = function() {
  1116. // get target language
  1117. // this.project.options = this.project.options || {}
  1118. sys.config.default = sys.config.default || {};
  1119. var tl = this.getOption("tl") || sys.config.default?.tl || $DV.config.tl;
  1120. return tl;
  1121. }
  1122. /**
  1123. * Set the source language of the current project
  1124. * @param {String} value - The source language's code
  1125. * @since 7.3.26
  1126. */
  1127. Trans.prototype.setSl = function(value) {
  1128. if (!this.project) return;
  1129. this.setOption("sl", value);
  1130. }
  1131. /**
  1132. * Set the target language of the current project
  1133. * @param {String} value - The target language's code
  1134. * @since 7.3.26
  1135. */
  1136. Trans.prototype.setTl = function(value) {
  1137. if (!this.project) return;
  1138. this.setOption("tl", value);
  1139. }
  1140. //================================================================
  1141. //
  1142. // HANDLING SAVE & LOAD DATA
  1143. //
  1144. //================================================================
  1145. Trans.prototype.applyNewData = function(newData) {
  1146. newData = newData||[[]];
  1147. for (var row=0; row<newData.length; row++) {
  1148. this.data[row] = newData[row];
  1149. }
  1150. }
  1151. Trans.prototype.applyNewHeader = function(newHeader) {
  1152. newHeader = newHeader||[];
  1153. for (var header=0; header<newHeader.length; header++) {
  1154. this.colHeaders[header] = newHeader[header];
  1155. }
  1156. }
  1157. Trans.prototype.generateId = function() {
  1158. const seed = "tppSZ698";
  1159. return common.makeid(10, seed);
  1160. }
  1161. Trans.prototype.initTransData = function(transData) {
  1162. // initialize new trans data created by other application
  1163. transData = transData||{};
  1164. var template = JSON.parse(fs.readFileSync("data/template.trans"));
  1165. // remove identity from template
  1166. template.project ||= {}
  1167. template.project.projectId = undefined;
  1168. template.project.buildOn = undefined;
  1169. var result = common.mergeDeep(template, transData);
  1170. result.project = result.project || {}
  1171. result.project.options = result.project.options || {}
  1172. result.project.options.init = result.project.options.init || {}
  1173. result.project.projectId = result.project.projectId || this.generateId(10);
  1174. result.project.buildOn = result.project.buildOn || common.formatDate(Date.now());
  1175. result.project.editorVersion = nw.App.manifest.version;
  1176. result.project.editorName = "Translator++";
  1177. return result;
  1178. }
  1179. Trans.prototype.createFileData = function(fullPath, defaultData, options={}) {
  1180. defaultData = defaultData || {}
  1181. fullPath = fullPath.replace(/\\/g, "/");
  1182. if (options?.leadSlash) {
  1183. if (fullPath.charAt(0) !== "/") fullPath = "/"+fullPath;
  1184. }
  1185. defaultData.basename = defaultData.basename||nwPath.basename(fullPath),
  1186. defaultData.filename = defaultData.filename||nwPath.basename(fullPath),
  1187. defaultData.path = defaultData.path||fullPath,
  1188. defaultData.relPath = defaultData.relPath||fullPath,
  1189. defaultData.data = defaultData.data||[[null]],
  1190. defaultData.originalFormat = defaultData.originalFormat||"Autogenerated TRANS obj",
  1191. defaultData.type = defaultData.type||""
  1192. defaultData.context = defaultData.context||[]
  1193. defaultData.tags = defaultData.tags||[]
  1194. if (typeof defaultData.extension == 'undefined') defaultData.extension = nwPath.extname(fullPath);
  1195. if (typeof defaultData.dirname == 'undefined') defaultData.dirname = nwPath.dirname(fullPath);
  1196. return defaultData;
  1197. }
  1198. Trans.prototype.validateTransData = function(transData) {
  1199. // standarized transData
  1200. /*
  1201. adapt from two dimensional array
  1202. */
  1203. var result = {};
  1204. if (Array.isArray(transData)) {
  1205. console.log("Case 1 - transData is array");
  1206. let templateObj = this.loadJSONSync(this.getTemplatePath());
  1207. let objName = "/main";
  1208. templateObj.project.files[objName] = this.createFileData(objName, {data:transData});
  1209. result = templateObj;
  1210. return result;
  1211. }
  1212. /*
  1213. object is in file structure
  1214. */
  1215. if (Boolean(transData.project)==false && Boolean(transData.files)==false && Array.isArray(transData.data)) {
  1216. console.log("Case 1 - transData is file structured");
  1217. let templateObj = this.loadJSONSync(this.getTemplatePath());
  1218. let objName = transData.path||"/main";
  1219. templateObj.project.files[objName] = this.createFileData(objName, {data:transData.data});
  1220. result = templateObj;
  1221. return result;
  1222. }
  1223. if ( Boolean(transData.project)==false && Boolean(transData.files)==true) {
  1224. result.project = transData;
  1225. } else {
  1226. result = transData;
  1227. }
  1228. result.project.gameTitle = result.project.gameTitle||t("untitled project");
  1229. result.project.gameEngine = result.project.gameEngine||"";
  1230. result.project.projectId = result.project.projectId||"";
  1231. result.project.buildOn = result.project.buildOn || common.formatDate();
  1232. result.project.files = result.project.files || {};
  1233. for (var id in result.project.files) {
  1234. result.project.files[id] = this.createFileData(id, result.project.files[id])
  1235. }
  1236. return result;
  1237. }
  1238. /**
  1239. * Normalize loaded column header
  1240. * Apply default value & unchangeable value into trans.columns
  1241. * Should be called each time trans files are loaded
  1242. */
  1243. Trans.prototype.normalizeHeader = function() {
  1244. for (var i=0; i<this.columns.length; i++) {
  1245. if (i == this.keyColumn) {
  1246. this.columns[i].validator = this.validateKey;
  1247. }
  1248. //this.columns[i].trimWhitespace = false;
  1249. this.columns[i].wordWrap = true;
  1250. }
  1251. }
  1252. /**
  1253. * Load the trans structured data into the current project
  1254. * @param {Object} saveData - Trans structured data
  1255. * @returns {Object} - Instance of Trans
  1256. */
  1257. Trans.prototype.applySaveData = function(saveData) {
  1258. console.log("entering trans.applySaveData");
  1259. console.log(saveData);
  1260. saveData = saveData||{};
  1261. saveData = this.validateTransData(saveData);
  1262. this.data = saveData.data||[[null]];
  1263. //trans.data = [[]];
  1264. this.columns = saveData.columns||this.default.columns||[];
  1265. this.normalizeHeader();
  1266. this.colHeaders = saveData.colHeaders||this.default.colHeaders||[];
  1267. this.project = saveData.project||{};
  1268. //this.indexIds = saveData.indexIds||{};
  1269. // FILLING ROOT VARIABLE based on game project
  1270. this.gameTitle = saveData.project.gameTitle||"";
  1271. this.gameEngine = saveData.project.gameEngine||"";
  1272. this.projectId = saveData.project.projectId||"";
  1273. this.gameFolder = saveData.project.loc||"";
  1274. // detecting fileList
  1275. if (saveData.fileListLoaded == false) {
  1276. try {
  1277. if (typeof saveData.project.files !== "undefined") saveData.fileListLoaded = true;
  1278. }
  1279. catch(err) {
  1280. saveData.fileListLoaded = false;
  1281. }
  1282. }
  1283. this.resetIndex();
  1284. this.fileListLoaded = saveData.fileListLoaded||false;
  1285. this.initFileNav();
  1286. this.refreshGrid();
  1287. ui.setWindowTitle();
  1288. ui.setStatusBar(1, this.gameTitle);
  1289. //engines.handler('onLoadTrans').apply(this, arguments);
  1290. return this;
  1291. }
  1292. /**
  1293. * Create a clone structure of the trans object that ready to be saved
  1294. * @param {Object} options
  1295. * @param {String} options.type - Type of the returned data (""||"json"||"lz")
  1296. * @returns {(Object|String)} - A clone of trans object
  1297. */
  1298. Trans.prototype.getSaveData = function(options) {
  1299. options = options||{};
  1300. options.filter = options.filter || [];
  1301. options.type = options.type || ""; // ""||"json"||"lz"
  1302. if (empty(this.project)) return;
  1303. if (empty(this.project.files)) return;
  1304. this.project.projectId = this.project.projectId || common.makeid(10);
  1305. //if (!this.project.projectId) return;
  1306. var projectClone = JSON.parse(JSON.stringify(this.project))||{};
  1307. if (options.filter.length > 0) {
  1308. console.log("filtering saved object", options);
  1309. if (typeof this.project !== 'undefined') {
  1310. if (typeof this.project.files !== 'undefined') {
  1311. projectClone.files = {};
  1312. for (var i=0; i<options.filter.length; i++) {
  1313. var thisId = options.filter[i];
  1314. console.log("testing "+thisId, this.project.files[thisId], this.project.files);
  1315. if (typeof this.project.files[thisId] == 'undefined') continue;
  1316. console.log("exist, assigning "+thisId);
  1317. projectClone.files[thisId] = JSON.parse(JSON.stringify(this.project.files[thisId]));
  1318. }
  1319. }
  1320. }
  1321. }
  1322. var saveData = {};
  1323. //saveData.data = this.data||[];
  1324. saveData.data = [[null]];
  1325. saveData.columns = this.columns||[];
  1326. saveData.colHeaders = this.colHeaders||[];
  1327. saveData.project = projectClone;
  1328. //saveData.indexIds = this.indexIds;
  1329. saveData.fileListLoaded = this.fileListLoaded;
  1330. // get column width
  1331. for (let i=0; i<this.grid.getColHeader().length; i++) {
  1332. if (!saveData.columns[i]) continue;
  1333. saveData.columns[i].width = this.grid.getColWidth(i);
  1334. }
  1335. // strip out reference data
  1336. for (var fileId in saveData.project.files) {
  1337. if (saveData.project.files[fileId].type == 'reference') {
  1338. saveData.project.references = saveData.project.references||{};
  1339. saveData.project.references[fileId] = JSON.parse(JSON.stringify(saveData.project.files[fileId]));
  1340. delete saveData.project.files[fileId];
  1341. }
  1342. }
  1343. if (options.type == "json") return JSON.stringify(saveData);
  1344. return saveData;
  1345. }
  1346. /**
  1347. * Compress an object
  1348. * @async
  1349. * @param {(Buffer|String|Object)} data
  1350. * @param {*} options
  1351. * @return {Promise<string>} - compressed data
  1352. */
  1353. Trans.prototype.compress = async function(data, options) {
  1354. options = options || {};
  1355. var buff = Buffer.from([]);
  1356. if (Buffer.isBuffer(data)) {
  1357. buff = data;
  1358. } else if (typeof data == "string") {
  1359. buff = Buffer.from(data);
  1360. } else if (typeof data == "object" && !empty(data)) {
  1361. buff = Buffer.from(JSON.stringify(data));
  1362. } else {
  1363. // generate buffer from trans
  1364. buff = Buffer.from(JSON.stringify(this.getSaveData()));
  1365. }
  1366. return common.gzip(buff, options);
  1367. }
  1368. /**
  1369. * Uncompress a string
  1370. * @async
  1371. * @param {(Buffer|String)} data - Compressed string
  1372. * @param {*} options
  1373. * @returns {Promise<string>} - uncompressed string
  1374. */
  1375. Trans.prototype.uncompress = async function(data, options) {
  1376. options = options || {};
  1377. var buff = Buffer.from([]);
  1378. if (Buffer.isBuffer(data)) {
  1379. buff = data;
  1380. } else if (typeof data == "string") {
  1381. buff = Buffer.from(data);
  1382. } else {
  1383. return console.error("Can not uncompress from data:", data, "Only buffer or string is accepted");
  1384. }
  1385. return common.gunzip(buff, options);
  1386. }
  1387. /**
  1388. * @async
  1389. * @param {(Buffer|String)} source - the source object
  1390. */
  1391. Trans.prototype.from = async function(source) {
  1392. var str = "";
  1393. var obj;
  1394. if (Buffer.isBuffer(source)) {
  1395. if (source.slice(0, 10).join(",") == "31,139,8,0") {
  1396. // gziped
  1397. str = await common.gunzip(source);
  1398. str = str.toString();
  1399. } else {
  1400. str = source.toString();
  1401. }
  1402. } else if (typeof source == "string") {
  1403. str = source;
  1404. }
  1405. if (str) {
  1406. if (JSON.isJSON(str) == false) return console.error("unknown format :", source);
  1407. obj = JSON.parse(str);
  1408. }
  1409. return obj;
  1410. }
  1411. /**
  1412. * Generate backup from given path of trans file
  1413. * @param {String} saveFile - Path to the file
  1414. */
  1415. Trans.prototype.createBackup = async function(saveFile) {
  1416. var backupLevel = parseInt(sys.getConfig("backupLevel"));
  1417. if (!sys.getConfig("autoBackup")) return;
  1418. if (!backupLevel) return;
  1419. if (!await common.isFileAsync(saveFile)) return console.warn("no such file ", saveFile);
  1420. if ([".trans", ".tpp"].includes(nwPath.extname(saveFile).toLowerCase()) == false) return;
  1421. // remove last file
  1422. await common.unlink(saveFile+`.${backupLevel}.bak`);
  1423. for (var i=backupLevel-1; i>=0; i--) {
  1424. if (i==0) {
  1425. await common.rename(saveFile, saveFile+`.${i+1}.bak`);
  1426. } else {
  1427. if (await common.isFileAsync(saveFile+`.${i}.bak`) == false) continue;
  1428. await common.rename(saveFile+`.${i}.bak`, saveFile+`.${i+1}.bak`)
  1429. }
  1430. }
  1431. }
  1432. /**
  1433. * Save project into .trans file with the new filename
  1434. * This function will open a blocking save dialog.
  1435. * @since 4.3.16
  1436. * @async
  1437. * @param {String} targetFile - Path to the file
  1438. * @param {Object} options - Object of the options
  1439. * @param {String} options.initiator - Who called the function user||auto
  1440. * @param {Function} options.onAfterLoading - Callback after the process is done
  1441. * @param {Function} options.onSuccess - Callback after the file is saved successfully
  1442. * @param {Function} options.onFailed - Callback when the error is occured
  1443. * @returns {Promise<string>} - The path where the file was saved
  1444. */
  1445. Trans.prototype.saveAs = async function(targetFile, options) {
  1446. var target = await ui.saveAs(targetFile || trans.currentFile || "");
  1447. console.log("Saving into : ", target);
  1448. if (!target) return "";
  1449. return await this.save(target, options);
  1450. }
  1451. /**
  1452. * Save project into .trans file
  1453. * @async
  1454. * @param {String} targetFile - Path to the file
  1455. * @param {Object} options - Object of the options
  1456. * @param {String} options.initiator - Who called the function user||auto
  1457. * @param {Function} options.onAfterLoading - Callback after the process is done
  1458. * @param {Function} options.onSuccess - Callback after the file is saved successfully
  1459. * @param {Function} options.onFailed - Callback when the error is occured
  1460. * @returns {Promise<string>} - The path where the file was saved
  1461. */
  1462. Trans.prototype.save = async function(targetFile, options) {
  1463. targetFile = targetFile||this.currentFile;
  1464. if (!targetFile) return await this.saveAs(targetFile, options);
  1465. var trans = this;
  1466. options = options||{};
  1467. options.initiator = options.initiator||"user";
  1468. options.filter = options.filter || [];
  1469. options.onAfterLoading = options.onAfterLoading||function(responseData, event) {};
  1470. options.onSuccess = options.onSuccess||function(responseData, event) {};
  1471. options.onFailed = options.onFailed||function(responseData, event) {};
  1472. if (trans.isSavingFile) return console.warn("Trans.prototype.save() is busy! Please wait until the previous save procedure to be completed before triggering another one!");
  1473. // data to save
  1474. console.log("Saving data to : "+targetFile);
  1475. var saveData = trans.getSaveData(options);
  1476. console.log(saveData);
  1477. trans.isSavingFile = true;
  1478. ui.saveIndicatorStart();
  1479. if (options.initiator == "user") await this.createBackup(targetFile);
  1480. return new Promise((resolve, reject)=> {
  1481. fs.writeFile(targetFile, JSON.stringify(saveData), (err) => {
  1482. if (err) {
  1483. if (typeof options.onFailed =='function') options.onFailed.call(trans, saveData, targetFile);
  1484. ui.saveIndicatorEnd()
  1485. console.warn("Failed to save to : ", targetFile, err );
  1486. reject();
  1487. } else {
  1488. if (options.initiator !== "auto") {
  1489. console.log(targetFile+' successfully saved!');
  1490. sys.insertOpenedFileHistory(targetFile,saveData.project.projectId,saveData.project.gameTitle, options.initiator);
  1491. this.currentFile = targetFile;
  1492. trans.gridIsModified(false);
  1493. ui.setWindowTitle();
  1494. }
  1495. if (typeof options.onSuccess == 'function') options.onSuccess.call(trans, saveData, targetFile);
  1496. resolve(targetFile);
  1497. }
  1498. options.onAfterLoading.call(trans, saveData, targetFile);
  1499. setTimeout(function(){
  1500. ui.saveIndicatorEnd()
  1501. }, 1000);
  1502. trans.isSavingFile = false;
  1503. });
  1504. })
  1505. }
  1506. /**
  1507. * Generating chache path
  1508. */
  1509. Trans.prototype.generateCachePath = function() {
  1510. this.project.cache = this.project.cache || {}
  1511. this.project.cache.cacheID = this.project.cache.cacheID||this.project.projectId;
  1512. if (!this.project.cache.cacheID) this.project.cache.cacheID = this.project.projectId = common.makeid(10)
  1513. console.log("Joining", sys.config.stagingPath, this.project.cache.cacheID);
  1514. this.project.cache.cachePath = this.project.cache.cachePath || nwPath.join(sys.config.stagingPath, this.project.cache.cacheID);
  1515. try {
  1516. fs.mkdirSync(this.project.cache.cachePath, {recursive:true})
  1517. } catch (e) {
  1518. console.warn(e);
  1519. }
  1520. }
  1521. /**
  1522. * Trigger auto save procedure
  1523. * @async
  1524. * @param {Object} options
  1525. * @param {String} [options.initiator=auto] - Who call this function
  1526. * @param {Function} options.onSuccess - Called when success
  1527. * @returns {String} - Path to the saved file if success
  1528. */
  1529. Trans.prototype.autoSave = async function(options) {
  1530. options = options||{};
  1531. if (typeof this.project == 'undefined') {
  1532. options.onSuccess = options.onSuccess || function(){};
  1533. options.onSuccess.call(this);
  1534. return false;
  1535. }
  1536. try {
  1537. if (!this.project.cache.cachePath) {
  1538. this.generateCachePath();
  1539. } else {
  1540. if (!common.isDir(this.project.cache.cachePath)) this.generateCachePath();
  1541. }
  1542. } catch (e) {
  1543. console.warn(e)
  1544. }
  1545. options.initiator = "auto";
  1546. var path = nwPath.join(this.project.cache.cachePath,"autosave.json");
  1547. await this.save(path, options);
  1548. return path;
  1549. }
  1550. /**
  1551. * Return processed fileData on success. A transmutable function.
  1552. * @param {Object} fileData - Object of the file (trans.project.files[filePath])
  1553. * @param {Boolean} force - Force rebuilding the index
  1554. * @returns {Object} fileData (mutable)
  1555. */
  1556. Trans.prototype.buildIndexFromData = function(fileData, force) {
  1557. // fileData is file object :
  1558. // ex. trans.project.files['main']
  1559. // return processed fileData on success
  1560. // transmutable function
  1561. var key = 0;
  1562. if (typeof fileData !== 'object') return console.warn("fileData is not an object");
  1563. if (Array.isArray(fileData.data) == false) return console.warn("fileData.data is not a valid array");
  1564. if (fileData.indexIsBuilt && !force) return fileData;
  1565. fileData.data = fileData.data || [];
  1566. fileData.indexIds = fileData.indexIds || {}
  1567. for (var row = 0; row<fileData.data.length; row++) {
  1568. var thisRow = fileData.data[row];
  1569. if (!thisRow[key]) continue;
  1570. fileData.indexIds[thisRow[key]] = row;
  1571. }
  1572. fileData.indexIsBuilt= true
  1573. return fileData;
  1574. }
  1575. /**
  1576. * merge externalTrans into targetTrans
  1577. * by default targetTrans = current project
  1578. * @param {Object} externalTrans - External instance of Trans object to be exported
  1579. * @param {Object} [targetTrans=this] - existing instance of Trans object
  1580. * @param {Object} options
  1581. * @param {Boolean} options.overwrite - Will overwrite if the same file object exist
  1582. * @param {Boolean} options.all - Will merge all file object if True
  1583. * @param {Object} options.targetPair - Target files
  1584. * @param {String[]} options.files - List of source files
  1585. * @returns {Object} - merged trans
  1586. */
  1587. Trans.prototype.mergeTrans = function(externalTrans, targetTrans, options) {
  1588. // merge externalTrans into targetTrans
  1589. // bydefault targetTrans = current project;
  1590. var key = 0;
  1591. targetTrans = targetTrans || this;
  1592. targetTrans.project = targetTrans.project || {};
  1593. targetTrans.project.files = targetTrans.project.files || {};
  1594. externalTrans = externalTrans || {};
  1595. externalTrans.project = externalTrans.project || {}
  1596. externalTrans.project.files = externalTrans.project.files || {};
  1597. options = options || {};
  1598. options.overwrite = options.overwrite || false;
  1599. options.targetPair = options.targetPair||{};
  1600. options.files = options.files || [];
  1601. options.all = options.all || false; // fetch all?
  1602. if (options.all) options.targetPair = externalTrans.project.files; // if all, doesn't use targetPair
  1603. targetTrans = this.sanitize(targetTrans);
  1604. var targetIsSelf = false;
  1605. if (targetTrans instanceof Trans) targetIsSelf = true;
  1606. console.log("running mergeTrans with args : ", arguments);
  1607. //return;
  1608. for (var id in options.targetPair) {
  1609. var sourceFile = externalTrans.project.files[id];
  1610. var targetFile = targetTrans.project.files[id];
  1611. if (!targetFile) {
  1612. // copy entire sourcefile into targetFile
  1613. targetTrans.project.files[id] = common.clone(sourceFile);
  1614. if (targetIsSelf) this.addFileItem(id, targetTrans.project.files[id]);
  1615. continue;
  1616. }
  1617. console.log("merging data", id);
  1618. // the real deal, merge the data
  1619. if (Array.isArray(sourceFile.data)==false) continue;
  1620. if (sourceFile.data.length == 0) continue;
  1621. this.buildIndexFromData(targetFile);
  1622. targetFile.context = targetFile.context||[];
  1623. sourceFile.context = sourceFile.context||[];
  1624. for (var row=0; row<sourceFile.data.length; row++) {
  1625. var thisSourceRow = sourceFile.data[row];
  1626. if (Boolean(thisSourceRow[key])==false) continue;
  1627. var index = targetFile.indexIds[thisSourceRow[key]];
  1628. if (typeof index == 'undefined') {
  1629. index = targetFile.data.length;
  1630. }
  1631. targetFile.data[index] = common.clone(thisSourceRow);
  1632. targetFile.context[index] = common.clone(sourceFile.context[row]);
  1633. }
  1634. }
  1635. if (targetIsSelf) {
  1636. this.generateHeader(targetTrans);
  1637. this.evalTranslationProgress();
  1638. ui.fileList.reIndex();
  1639. ui.initFileSelectorDragSelect();
  1640. }
  1641. this.refreshGrid();
  1642. return targetTrans;
  1643. }
  1644. /**
  1645. * Load JSON file in synchronous fashion
  1646. * @param {String} filePath - Path to the JSON file
  1647. * @param {Object} options
  1648. * @returns {Object} Loaded JSON object
  1649. */
  1650. Trans.prototype.loadJSONSync = function(filePath, options) {
  1651. if (filePath == "" || filePath == null || typeof filePath == 'undefined') return false;
  1652. options = options||{};
  1653. options.onAfterLoading = options.onAfterLoading||function(responseData, event) {};
  1654. options.onSuccess = options.onSuccess||function(responseData, event) {};
  1655. options.onFailed = options.onFailed||function(responseData, event) {};
  1656. var fs = require('fs');
  1657. var content = fs.readFileSync(filePath);
  1658. var resultStr = content.toString();
  1659. var result = false;
  1660. try {
  1661. result = JSON.parse(resultStr);
  1662. return result;
  1663. } catch(e) {
  1664. return result;
  1665. }
  1666. }
  1667. /**
  1668. * open JSON & Parse it. General purpose function
  1669. * The file must be in UTF-8 encoding
  1670. * @async
  1671. * @param {String} filePath - Path to the JSON file
  1672. * @param {Object} options
  1673. * @param {Function} options.onSuccess - Called when success
  1674. * @param {Function} options.onFailed - Called when failed
  1675. */
  1676. Trans.prototype.loadJSON = async function(filePath, options) {
  1677. // open JSON & Parse it
  1678. // for general purposes
  1679. var trans = this;
  1680. if (filePath == "" || filePath == null || typeof filePath == 'undefined') return false;
  1681. options = options||{};
  1682. options.onAfterLoading = options.onAfterLoading||function(responseData, event) {};
  1683. options.onSuccess = options.onSuccess||function(responseData, event) {};
  1684. options.onFailed = options.onFailed||function(responseData, event) {};
  1685. this.isOpeningFile = true;
  1686. ui.showBusyOverlay();
  1687. var jsonData;
  1688. try {
  1689. let loadedFile = await common.fileGetContents(filePath, "utf8", false);
  1690. jsonData = JSON.parse(loadedFile);
  1691. } catch (e) {
  1692. alert("Error loading file: "+filePath)
  1693. }
  1694. ui.hideBusyOverlay();
  1695. trans.isOpeningFile = false;
  1696. return jsonData;
  1697. // fs.readFile(filePath, function (err, data) {
  1698. // if (err) {
  1699. // console.log("error opening file (loadJSON): "+filePath);
  1700. // data = data.toString();
  1701. // if (typeof options.onFailed =='function') options.onFailed.call(trans, data);
  1702. // ui.hideBusyOverlay();
  1703. // throw err;
  1704. // } else {
  1705. // data = data.toString();
  1706. // try {
  1707. // var jsonData = JSON.parse(data);
  1708. // console.log(jsonData);
  1709. // } catch (e) {
  1710. // alert(t("Can not parse JSON data. Probably the file is corrupted."));
  1711. // options.onFailed.call(trans, jsonData);
  1712. // trans.isOpeningFile = false;
  1713. // ui.hideBusyOverlay();
  1714. // return;
  1715. // }
  1716. // if (typeof options.onSuccess == 'function') options.onSuccess.call(trans, jsonData);
  1717. // trans.isOpeningFile = false;
  1718. // ui.hideBusyOverlay();
  1719. // }
  1720. // });
  1721. }
  1722. /**
  1723. * Import from file and replace or create object
  1724. * @param {String|Trans} file - Trans file to be imported
  1725. * @param {Object} options
  1726. * @param {Boolean} options.overwrite - Will overwrite if the same file object exist
  1727. * @param {Boolean} options.all - Will merge all file object if True
  1728. * @param {Object} options.targetPair - Target files
  1729. * @param {String[]} options.files - List of source files
  1730. * @param {Boolean} options.mergeData
  1731. */
  1732. Trans.prototype.importFromFile = async function(file, options) {
  1733. // import from file and replace or create object
  1734. // options.targetPair = {
  1735. // sourceKey : targetKey
  1736. // }
  1737. // or
  1738. // options.targetPair = {
  1739. // sourceKey : true // same with sourceKey
  1740. // }
  1741. //
  1742. // if targetKey is not exist, then create one.
  1743. options = options||{};
  1744. options.overwrite = options.overwrite || false;
  1745. options.targetPair = options.targetPair||{};
  1746. options.files = options.files || [];
  1747. options.mergeData = options.mergeData || false;
  1748. //if (Array.isArray(file) == false) file = [file];
  1749. var trans = this;
  1750. var data;
  1751. if (!this.isTrans(file)) {
  1752. data = await trans.loadJSON(file);
  1753. data = trans.validateTransData(data);
  1754. } else {
  1755. data = file;
  1756. }
  1757. if (options.mergeData) {
  1758. trans.mergeTrans(data, trans, options);
  1759. return;
  1760. }
  1761. for (let sourceKey in options.targetPair) {
  1762. if (typeof options.targetPair[sourceKey] !== 'string') {
  1763. options.targetPair[sourceKey] = sourceKey;
  1764. }
  1765. try {
  1766. //if (typeof trans.project.files[options.targetPair[sourceKey]] == 'undefined') continue;
  1767. if (data.project.references[sourceKey] !== 'undefined') {
  1768. trans.project.files[options.targetPair[sourceKey]] = data.project.references[sourceKey];
  1769. }
  1770. if (typeof data.project.files[sourceKey] == 'undefined') continue;
  1771. trans.project.files[options.targetPair[sourceKey]] = data.project.files[sourceKey];
  1772. console.log(t("create file list"), options.targetPair[sourceKey], trans.project.files[options.targetPair[sourceKey]]);
  1773. trans.addFileItem(options.targetPair[sourceKey], trans.project.files[options.targetPair[sourceKey]]);
  1774. } catch (e) {
  1775. console.log(e);
  1776. continue;
  1777. }
  1778. }
  1779. ui.initFileSelectorDragSelect();
  1780. trans.evalTranslationProgress();
  1781. ui.fileList.reIndex();
  1782. trans.refreshGrid();
  1783. // trans.loadJSON(file, {
  1784. // onSuccess : function(data) {
  1785. // data = trans.validateTransData(data)
  1786. // if (options.mergeData) {
  1787. // trans.mergeTrans(data, trans, options);
  1788. // return;
  1789. // }
  1790. // for (let sourceKey in options.targetPair) {
  1791. // if (typeof options.targetPair[sourceKey] !== 'string') {
  1792. // options.targetPair[sourceKey] = sourceKey;
  1793. // }
  1794. // try {
  1795. // //if (typeof trans.project.files[options.targetPair[sourceKey]] == 'undefined') continue;
  1796. // if (data.project.references[sourceKey] !== 'undefined') {
  1797. // trans.project.files[options.targetPair[sourceKey]] = data.project.references[sourceKey];
  1798. // }
  1799. // if (typeof data.project.files[sourceKey] == 'undefined') continue;
  1800. // trans.project.files[options.targetPair[sourceKey]] = data.project.files[sourceKey];
  1801. // console.log(t("create file list"), options.targetPair[sourceKey], trans.project.files[options.targetPair[sourceKey]]);
  1802. // trans.addFileItem(options.targetPair[sourceKey], trans.project.files[options.targetPair[sourceKey]]);
  1803. // } catch (e) {
  1804. // console.log(e);
  1805. // continue;
  1806. // }
  1807. // }
  1808. // ui.initFileSelectorDragSelect();
  1809. // trans.evalTranslationProgress();
  1810. // ui.fileList.reIndex();
  1811. // trans.refreshGrid();
  1812. // }
  1813. // });
  1814. }
  1815. /**
  1816. * Select a cell from grid
  1817. * @param {Number} row
  1818. * @param {Number} column
  1819. * @returns {Boolean} True if success
  1820. */
  1821. Trans.prototype.selectCell = function(row, column) {
  1822. return this.grid.selectCell(row, column);
  1823. }
  1824. /**
  1825. * Generate checksum for the original text
  1826. * The checksume is 32bit representation of the original texts
  1827. * So the app can determine whether the game is same or not by their respective original texts
  1828. * @returns {String} 8 Byte of the project's checksum
  1829. */
  1830. Trans.prototype.getProjectChecksum = function() {
  1831. if (this.project.checksum) return this.project.checksum;
  1832. var sums = [];
  1833. var allFiles = this.getAllFiles();
  1834. allFiles.sort();
  1835. for (var f in allFiles) {
  1836. var thisFile = this.project.files[allFiles[f]];
  1837. if (empty(thisFile)) continue;
  1838. if (empty(thisFile.data)) continue;
  1839. // exclude "*" path such as Common Reference
  1840. if (thisFile.dirname == "*") continue;
  1841. var textPool = [];
  1842. for (var r=0; r<thisFile.data.length; r++) {
  1843. if (!thisFile.data[r][this.keyColumn]) continue;
  1844. textPool.push(thisFile.data[r][this.keyColumn]);
  1845. }
  1846. if (textPool.length < 1) continue;
  1847. textPool.sort();
  1848. sums.push(common.crc32String(JSON.stringify(textPool)));
  1849. }
  1850. this.project.checksum = common.crc32String(JSON.stringify(sums));
  1851. return this.project.checksum;
  1852. }
  1853. /**
  1854. * Export project into a TPP file
  1855. * @function
  1856. * @param {String} file - Path to the tpp file
  1857. * @param {*} options
  1858. * @param {Function} options.onDone - Triggered when done
  1859. */
  1860. Trans.prototype.exportTPP = function(file, options) {
  1861. // export translation to TPP
  1862. if (typeof file=="undefined") return false;
  1863. options = options||{};
  1864. options.showDetail = options.showDetail || false;
  1865. options.onDone = options.onDone||function() {};
  1866. var autofillFiles = [];
  1867. var checkbox = $(".fileList .data-selector .fileCheckbox:checked");
  1868. for (var i=0; i<checkbox.length; i++) {
  1869. autofillFiles.push(checkbox.eq(i).attr("value"));
  1870. }
  1871. options.files = options.files||autofillFiles||[];
  1872. ui.saveIndicatorStart();
  1873. trans.autoSave({
  1874. onSuccess:function() {
  1875. //ui.showLoading();
  1876. php.spawn("saveTpp.php", {
  1877. args:{
  1878. path:file,
  1879. password:options.password,
  1880. gameFolder:trans.gameFolder,
  1881. gameTitle:trans.gameTitle,
  1882. projectId:trans.projectId,
  1883. gameEngine:trans.gameEngine,
  1884. files:options.files,
  1885. exportMode:options.mode,
  1886. rpgTransFormat:trans.config.rpgTransFormat
  1887. },
  1888. onData:function(buffer) {
  1889. if (options.showDetail) ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput'});
  1890. },
  1891. onError:function(buffer) {
  1892. if (options.showDetail) ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput', classStr:'stderr'});
  1893. },
  1894. onDone: function(data) {
  1895. //console.log(data);
  1896. //ui.hideLoading(true);
  1897. if (options.showDetail) {
  1898. ui.loadingProgress(t("Finished"), t("All process finished!"), {consoleOnly:false, mode:'consoleOutput'});
  1899. ui.showCloseButton();
  1900. ui.log.addButtons(t("Open Explorer"), function() {
  1901. common.openExplorer(file);
  1902. });
  1903. }
  1904. ui.saveIndicatorEnd();
  1905. options.onDone.call(trans, data);
  1906. }
  1907. })
  1908. }
  1909. });
  1910. }
  1911. /**
  1912. * Load TPP file
  1913. * @param {Trans} file - Path to the .tpp file
  1914. * @param {Object} options
  1915. * @param {Function} options.onDone - Triggered when done
  1916. */
  1917. Trans.prototype.importTpp = async function(file, options) {
  1918. if (typeof file=="undefined") return false;
  1919. options = options||{};
  1920. options.onDone = options.onDone||function() {};
  1921. // ensure staging path is exist
  1922. const staggingPath = sys.getConfig("stagingPath");
  1923. if (!await common.isDir(staggingPath)) {
  1924. await common.mkDir(staggingPath);
  1925. }
  1926. var doLoadTppToStage = function() {
  1927. ui.showLoading();
  1928. php.spawn("loadTpp.php", {
  1929. args:{
  1930. path:file,
  1931. password:options.password
  1932. },
  1933. onData:function(buffer) {
  1934. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput'});
  1935. },
  1936. onError:function(buffer) {
  1937. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput', classStr:'stderr'});
  1938. },
  1939. onDone: function(data) {
  1940. //console.log(data);
  1941. console.log("done")
  1942. //ui.hideLoading(true);
  1943. var saveFile = $(".console").find("output.cachepath").text();
  1944. saveFile = nwPath.join(saveFile,"autosave.json");
  1945. console.log("new cache path : ", saveFile);
  1946. ui.loadingProgress(t("Loading"), t("Opening file!"), {consoleOnly:false, mode:'consoleOutput'});
  1947. trans.open(saveFile, {
  1948. onSuccess: function() {
  1949. // writing new cache path
  1950. trans.project.cache = trans.project.cache || {}
  1951. trans.project.cache.cachePath = nwPath.dirname(saveFile);
  1952. ui.loadingProgress(t("Loading"), t("Assigning new staging path : "+trans.project.cache.cachePath), {consoleOnly:false, mode:'consoleOutput'});
  1953. ui.loadingProgress(t("Loading"), t("Success!"), {consoleOnly:false, mode:'consoleOutput'});
  1954. ui.loadingProgress(t("Finished"), t("All process finished!"), {consoleOnly:false, mode:'consoleOutput'});
  1955. ui.showCloseButton();
  1956. options.onDone.call(trans, data);
  1957. },
  1958. onFailed: function() {
  1959. ui.loadingProgress(t("Loading"), t("Failed!"), {consoleOnly:false, mode:'consoleOutput'});
  1960. ui.loadingProgress(t("Finished"), t("All process finished!"), {consoleOnly:false, mode:'consoleOutput'});
  1961. ui.showCloseButton();
  1962. options.onDone.call(trans, data);
  1963. }
  1964. });
  1965. }
  1966. });
  1967. }
  1968. trans.closeProject();
  1969. trans.autoSave({
  1970. onSuccess:function() {
  1971. doLoadTppToStage();
  1972. }
  1973. });
  1974. }
  1975. /**
  1976. * Export current project
  1977. * @param {String} file - Path to the file/folder
  1978. * @param {Object} options
  1979. * @param {Function} options.onDone - Triggered when done
  1980. * @param {String} options.mode - Export mode (ex. dir)
  1981. * @param {String} options.dataPath - location of data path (data folder). Default is cache path
  1982. * @param {String} options.transPath - location of the trans file. Default is using autosave on cache folder
  1983. * @param {String[]} options.files - List of the file(s) to be exported
  1984. * @param {Object} options.options
  1985. * @param {String[]} options.options.filterTag - Filter of the tag
  1986. * @param {String} options.options.filterTagMode - Mode of the filter (whitelist||blacklist)
  1987. */
  1988. Trans.prototype.export = async function(file, options) {
  1989. // export translation
  1990. if (typeof file=="undefined") return false;
  1991. options = options||{};
  1992. options.options = options.options||{};
  1993. console.log("Exporting with arguments:", arguments);
  1994. //return console.log("Exporting project", arguments);
  1995. options.mode = options.mode||"dir";
  1996. options.onDone = options.onDone||function() {};
  1997. options.dataPath = options.dataPath || ""; // location of data path (data folder). Default is using cache
  1998. options.transPath = options.transPath || ""; // location of .trans path to process. Default is using autosave on cache folder
  1999. options.options.filterTag = options.options.filterTag|| options.filterTag ||[];
  2000. options.options.filterTagMode = options.options.filterTagMode||options.filterTagMode||""; // whitelist or blacklist
  2001. options.custom = options.custom || options.options.custom;
  2002. delete options.options.custom; // delete options.options.custom to avoid confusion
  2003. console.log("exporting project", arguments);
  2004. var autofillFiles = [];
  2005. var checkbox = $(".fileList .data-selector .fileCheckbox:checked");
  2006. for (var i=0; i<checkbox.length; i++) {
  2007. autofillFiles.push(checkbox.eq(i).attr("value"));
  2008. }
  2009. options.files = options.files||autofillFiles||[];
  2010. // custom export handler
  2011. let thisEngine = trans.project.gameEngine;
  2012. if (typeof engines[thisEngine] !== 'undefined') {
  2013. if (typeof engines[thisEngine].exportHandler == 'function') {
  2014. var halt = await engines[thisEngine].exportHandler.apply(this, arguments);
  2015. console.log("Is process halt?", halt);
  2016. if (halt) {
  2017. await this.projectHook.run("afterExport", options);
  2018. return;
  2019. }
  2020. }
  2021. }
  2022. if (["csv", "xlsx", "xls", "ods", "html", "RPGMakerTrans"].includes(options.mode) || thisEngine=="spreadsheet") {
  2023. this.legacyExport(file, options);
  2024. }
  2025. console.log("Export process is finished");
  2026. }
  2027. Trans.prototype.legacyExport = async function(file, options) {
  2028. // below this point is for legacy mode
  2029. const autosavePath = await trans.autoSave();
  2030. ui.log.show();
  2031. await ui.log("Exporting project to "+options.mode+" format with legacy mode");
  2032. trans.project.options = trans.project.options || {}
  2033. trans.project.options.init = trans.project.options.init || {};
  2034. const projectOption = Object.assign(trans.project.options.init, options.options);
  2035. php.spawn("export.php", {
  2036. args:{
  2037. path :file,
  2038. gameFolder :trans.gameFolder,
  2039. gameTitle :trans.gameTitle,
  2040. projectId :trans.projectId,
  2041. gameEngine :trans.gameEngine,
  2042. files :options.files,
  2043. exportMode :options.mode,
  2044. options :projectOption,
  2045. rpgTransFormat:trans.config.rpgTransFormat,
  2046. dataPath :options.dataPath,
  2047. transPath :nwPath.resolve(options.transPath || autosavePath)
  2048. },
  2049. onData:function(buffer) {
  2050. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput'});
  2051. },
  2052. onError:function(buffer) {
  2053. ui.loadingProgress(t("Loading"), buffer, {consoleOnly:true, mode:'consoleOutput', classStr:'stderr'});
  2054. },
  2055. onDone: async (data) => {
  2056. //console.log(data);
  2057. console.log("done")
  2058. //ui.hideLoading(true);
  2059. ui.loadingProgress(t("Finished"), t("All process finished!"), {consoleOnly:false, mode:'consoleOutput'});
  2060. //ui.showCloseButton();
  2061. await this.projectHook.run("afterExport", options);
  2062. ui.loadingEnd();
  2063. options.onDone.call(trans, data);
  2064. }
  2065. });
  2066. }
  2067. /**
  2068. * Revert the original data into a folder
  2069. * Will replace the existing file on the destination directory
  2070. * @param {String} destinationPath
  2071. * @param {Object} options
  2072. */
  2073. Trans.prototype.revertToOriginal = async function(destinationPath, options={}) {
  2074. var bCopy = require('better-copy')
  2075. if (!destinationPath) {
  2076. destinationPath = await ui.openRevertToOriginalDialog();
  2077. }
  2078. options.dataPath = options.dataPath || "data"
  2079. if (!destinationPath) return; // canceled
  2080. ui.showLoading();
  2081. ui.loadingProgress(0, "Reverting original data");
  2082. var objects = this.project.files;
  2083. if (this.getCheckedFiles().length > 0) objects = this.getCheckedObjects();
  2084. var copied = 0;
  2085. var processed = 0;
  2086. var totalLength = Object.keys(objects).length || 1;
  2087. ui.log(`Processing ${totalLength} file(s)`);
  2088. for (var i in objects) {
  2089. processed++;
  2090. var stagingBaseFolder = this.getStagingDataPath();
  2091. var stagingFile = this.getStagingFile(objects[i]);
  2092. var relativePath = common.getRelativePath(stagingFile, stagingBaseFolder)
  2093. await ui.loadingProgress(Math.round((processed/totalLength)*100), `Reverting : ${relativePath}`);
  2094. if (! await common.isFileAsync(stagingFile)) {
  2095. await ui.log(`File not found: ${stagingFile}`);
  2096. continue;
  2097. }
  2098. await ui.log(`${processed}/${totalLength} Copying : ${stagingFile}`);
  2099. await bCopy(stagingFile, nwPath.join(destinationPath, relativePath), {
  2100. overwrite:true
  2101. });
  2102. copied++;
  2103. }
  2104. await ui.log(`Completed! ${copied} file(s) reverted to original!`);
  2105. ui.log.addButtons("Open folder", function() {
  2106. nw.Shell.showItemInFolder(nwPath.join(destinationPath, relativePath));
  2107. },
  2108. {
  2109. class: "icon-folder-open"
  2110. });
  2111. ui.loadingEnd();
  2112. }
  2113. /**
  2114. * Import sheet into the current project
  2115. * @param {String} paths - Path to the sheet file / folder
  2116. * @param {Number} [columns=1] - Index of the destination column to put the translation into
  2117. * @param {Object} options
  2118. * @param {String} [options.sourceColumn=auto] - The source column
  2119. * @param {Boolean} [options.overwrite=false] - When True will overwrite the existing value
  2120. * @param {String[]} options.files - List of targeted files
  2121. * @param {Number} [options.sourceKeyColumn=0] - Column index of the translation's key
  2122. * @param {Number} [options.keyColumn=0] - Key column of the current project
  2123. * @param {Boolean} options.stripCarriageReturn - Whether to strip the carriage retrun character or not
  2124. */
  2125. Trans.prototype.importSheet = async function(paths, columns, options) {
  2126. // import sheets from a folder or file
  2127. columns = columns||1; // target Column
  2128. options = options||{};
  2129. options.sourceColumn = options.sourceColumn||"auto";
  2130. options.overwrite = options.overwrite||false;
  2131. options.files = options.files||trans.getCheckedFiles()||[];
  2132. options.sourceKeyColumn = options.sourceKeyColumn||0;
  2133. options.keyColumn = options.keyColumn||0;
  2134. options.newLine = options.newLine||undefined;
  2135. options.stripCarriageReturn = options.stripCarriageReturn||false;
  2136. options.ignoreNewLine = true; // let's set to true;
  2137. console.log("trans.importSheet");
  2138. console.log(arguments);
  2139. //return console.log("halted");
  2140. if (Array.isArray(paths) == false) paths=[paths];
  2141. ui.showLoading();
  2142. ui.loadingProgress(0, t("Collecting paths"), {consoleOnly:true, mode:'consoleOutput'});
  2143. ui.log("Building indexes")
  2144. if (options.files?.length == 0) {
  2145. options.files = this.getAllFiles();
  2146. }
  2147. options.indexes = this.buildIndexes(options.files, false);
  2148. var allPaths = [];
  2149. for (let i=0; i<paths.length; i++) {
  2150. var path = paths[i];
  2151. if (common.isExist(path) == false) {
  2152. ui.loadingProgress(0, t("Path : '")+path+t("' doesn't exist"), {consoleOnly:true, mode:'consoleOutput'});
  2153. console.log("Error, path not exist");
  2154. continue;
  2155. }
  2156. if (common.isDir(path)) {
  2157. var dirTree = common.dirContentSync(path);
  2158. allPaths = allPaths.concat(dirTree);
  2159. } else {
  2160. allPaths.push(path);
  2161. }
  2162. }
  2163. ui.loadingProgress(0, allPaths.length+t(" file(s) collected!"), {consoleOnly:true, mode:'consoleOutput'});
  2164. ui.loadingProgress(0, t("Start importing data!"), {consoleOnly:true, mode:'consoleOutput'});
  2165. var processFile;
  2166. if (common.parseSheet) {
  2167. ui.log("Import using sheet parser add-on")
  2168. processFile = async function(filePath) {
  2169. var data = await common.parseSheet(filePath);
  2170. var merged = [];
  2171. for (var i in data) {
  2172. console.log("Merging data", data[i]);
  2173. if (!data[i]) continue;
  2174. if (!data[i].length) continue;
  2175. merged = merged.concat(data[i]);
  2176. }
  2177. console.log("output data :");
  2178. console.log(merged);
  2179. trans.translateFromArray(merged, columns, options);
  2180. }
  2181. } else {
  2182. ui.log("Import using legacy sheet importer")
  2183. processFile = function(filePath) {
  2184. filePath = filePath||path;
  2185. php.spawnSync("import.php", {
  2186. args:{
  2187. //'path':'F:\\test\\export',
  2188. 'path':filePath,
  2189. output:null,
  2190. mergeSheet:true,
  2191. prettyPrint:true
  2192. },
  2193. onDone : function(data) {
  2194. console.log("output data :");
  2195. console.log(data);
  2196. trans.translateFromArray(data, columns, options);
  2197. }
  2198. });
  2199. }
  2200. }
  2201. for (let i=0; i<allPaths.length; i++) {
  2202. var thisFile = allPaths[i];
  2203. ui.loadingProgress(Math.round(i/allPaths.length*100), t("Importing : ")+thisFile, {consoleOnly:true, mode:'consoleOutput'});
  2204. await processFile(thisFile);
  2205. ui.loadingProgress(Math.round((i+1)/allPaths.length*100), t("Done!"), {consoleOnly:true, mode:'consoleOutput'});
  2206. }
  2207. trans.refreshGrid();
  2208. trans.evalTranslationProgress();
  2209. ui.loadingProgress(t("Done!"), t("All Done!"), {consoleOnly:true, mode:'consoleOutput'});
  2210. ui.loadingEnd();
  2211. }
  2212. /**
  2213. * Import translation from RPGMTransPatch
  2214. * @param {String} paths - Path to the sheet file / folder
  2215. * @param {Number} [columns=1] - Index of the destination column to put the translation into
  2216. * @param {Object} options
  2217. * @param {String} [options.sourceColumn=auto] - The source column
  2218. * @param {Boolean} [options.overwrite=false] - When True will overwrite the existing value
  2219. * @param {String[]} options.files - List of targeted files
  2220. * @param {Number} [options.keyColumn=0] - Key column of the current project
  2221. * @param {Boolean} options.stripCarriageReturn - Whether to strip the carriage retrun character or not
  2222. */
  2223. Trans.prototype.importRPGMTrans = function(paths, columns, options) {
  2224. // Import translation from RPGMTransPatch
  2225. columns = columns||1; // target Column
  2226. options = options||{};
  2227. options.sourceColumn = options.sourceColumn||"auto";
  2228. options.overwrite = options.overwrite||false;
  2229. options.files = options.files||trans.getCheckedFiles()||[];
  2230. options.sourceKeyColumn = options.sourceKeyColumn||0;
  2231. options.keyColumn = options.keyColumn||0;
  2232. options.newLine = options.newLine||undefined;
  2233. options.stripCarriageReturn = options.stripCarriageReturn||false;
  2234. options.ignoreNewLine = true; // let's set to true;
  2235. console.log("trans.importRPGMTrans");
  2236. console.log(arguments);
  2237. //return console.log("halted");
  2238. if (Array.isArray(paths) == false) paths=[paths];
  2239. ui.showLoading();
  2240. ui.loadingProgress(0, t("Collecting paths"), {consoleOnly:true, mode:'consoleOutput'});
  2241. var allPaths = [];
  2242. for (var i=0; i<paths.length; i++) {
  2243. var path = paths[i];
  2244. if (common.isExist(path) == false) {
  2245. ui.loadingProgress(0, t("Path : '")+path+t("' doesn't exist"), {consoleOnly:true, mode:'consoleOutput'});
  2246. console.log("Error, path not exist");
  2247. continue;
  2248. }
  2249. if (common.isDir(path)) {
  2250. var dirTree = common.dirContentSync(path);
  2251. allPaths = allPaths.concat(dirTree);
  2252. } else {
  2253. allPaths.push(path);
  2254. }
  2255. }
  2256. ui.loadingProgress(0, allPaths.length+t(" file(s) collected!"), {consoleOnly:true, mode:'consoleOutput'});
  2257. ui.loadingProgress(0, t("Start importing data!"), {consoleOnly:true, mode:'consoleOutput'});
  2258. var processFile = function(filePath) {
  2259. filePath = filePath||path;
  2260. php.spawnSync("parseTrans.php", {
  2261. args:{
  2262. 'path':filePath,
  2263. prettyPrint:true
  2264. },
  2265. onDone : function(data) {
  2266. console.log("output data :");
  2267. console.log(data);
  2268. if (Array.isArray(data.data)) {
  2269. trans.translateFromArray(data.data, columns, options);
  2270. }
  2271. }
  2272. });
  2273. }
  2274. for (let i=0; i<allPaths.length; i++) {
  2275. var thisFile = allPaths[i];
  2276. ui.loadingProgress(Math.round(i/allPaths.length*100), t("Importing : ")+thisFile, {consoleOnly:true, mode:'consoleOutput'});
  2277. processFile(thisFile);
  2278. ui.loadingProgress(Math.round((i+1)/allPaths.length*100), t("Done!"), {consoleOnly:true, mode:'consoleOutput'});
  2279. }
  2280. trans.refreshGrid();
  2281. trans.evalTranslationProgress();
  2282. ui.loadingProgress(t("Done!"), t("All Done!"), {consoleOnly:true, mode:'consoleOutput'});
  2283. ui.loadingEnd();
  2284. }
  2285. // ===============================================================
  2286. // STATUS BAR
  2287. //================================================================
  2288. /**
  2289. * Clear the status bar
  2290. */
  2291. Trans.prototype.clearFooter = function() {
  2292. $(".footer .footer1 span").html("")
  2293. $(".footer .footer2 span").html("")
  2294. $(".footer .footer3 span").html("")
  2295. $(".footer .footer4 span").html("")
  2296. $(".footer .footer5 span").html("")
  2297. }
  2298. /**
  2299. * Set the value of the current context into the status menu
  2300. * @param {Number} row - Selected row
  2301. */
  2302. Trans.prototype.setStatusBarContext = function(row) {
  2303. if (typeof row== 'undefined') {
  2304. if (Array.isArray(trans.grid.getSelected())) row = trans.grid.getSelected()[0][0];
  2305. }
  2306. //if (typeof row == 'undefined') return false;
  2307. //if (typeof trans.project == 'undefined') return false;
  2308. //console.log(trans.project.files[trans.getSelectedId()].context[row]);
  2309. var currentId = trans.getSelectedId();
  2310. try {
  2311. if (trans.project.files[currentId].originalFormat == '> ANTI TES PATCH FILE VERSION 0.2' && this.project.parser !== "rmrgss") {
  2312. //$(".footer .footer1>span").html(currentId+"/"+trans.buildContextFromParameter(trans.project.files[currentId].parameters[row]));
  2313. $(".footer .footer1>span").html(trans.buildContextFromParameter(trans.project.files[currentId].parameters[row]));
  2314. } else {
  2315. //$(".footer .footer1>span").html(currentId+"/"+trans.project.files[currentId].context[row]);
  2316. $(".footer .footer1>span").html(trans.project.files[currentId].context[row].join("; "));
  2317. }
  2318. $(".footer .footer1>span").addClass("icon-th-2")
  2319. }
  2320. catch(err) {
  2321. $(".footer .footer1>span").html("");
  2322. $(".footer .footer1>span").removeClass("icon-th-2")
  2323. }
  2324. }
  2325. /**
  2326. * Set the Number of row section of the status bar
  2327. * @returns {Boolean} False on fail
  2328. */
  2329. Trans.prototype.setStatusBarNumData = function() {
  2330. if (typeof trans.project == 'undefined') return false;
  2331. try {
  2332. $(".footer .footer3 span").html("rows : "+trans.project.files[trans.getSelectedId()].data.length);
  2333. }
  2334. catch(err) {
  2335. $(".footer .footer3 span").html("");
  2336. }
  2337. }
  2338. /**
  2339. * Set the engine information section of the status bar
  2340. */
  2341. Trans.prototype.setStatusBarEngine= function() {
  2342. if (typeof trans.project == 'undefined') return false;
  2343. try {
  2344. var parser = "";
  2345. if (trans.project.parser) parser = `/<span title='parser'>${trans.project.parser}</span>`
  2346. $(".footer .footer4 span").html(trans.project.gameEngine+parser);
  2347. }
  2348. catch(err) {
  2349. $(".footer .footer4 span").html("");
  2350. }
  2351. }
  2352. /**
  2353. *
  2354. * @param {String} type - Type of the icon (notice, warning, notice, translatorPlusPlus)
  2355. */
  2356. Trans.prototype.setTrayIcon = function(type) {
  2357. // type : notice, warning, notice, translatorPlusPlus
  2358. type = type || "translatorPlusPlus";
  2359. var $icon = $('<i class="icon trayIcon"></i>');
  2360. $icon.addClass(type);
  2361. $(".footer .footer5 span").html($icon);
  2362. }
  2363. //================================================================
  2364. //
  2365. // EDITOR SECTION PART
  2366. //
  2367. //================================================================
  2368. /**
  2369. * Go to the botom most part of the grid to the new key section
  2370. */
  2371. Trans.prototype.goToNewKey = function() {
  2372. if (Array.isArray(this.data) == false) return false;
  2373. this.grid.scrollViewportTo(this.data.length-1);
  2374. this.grid.selectCell(this.data.length-1,0);
  2375. //if ($(document.activeElement).is("#currentCellText"));
  2376. }
  2377. /**
  2378. * Clear text editor. Bottom right editor.
  2379. * @returns {Boolean} True if success
  2380. */
  2381. Trans.prototype.clearEditor = function() {
  2382. const $cellText = $("#currentCellText");
  2383. $cellText.val("");
  2384. $cellText.prop("readonly", true);
  2385. $cellText.data("column", null);
  2386. $cellText.data("row", null);
  2387. return true;
  2388. }
  2389. /**
  2390. * Clear the Current Cell info section
  2391. * @returns {Boolean} True if success
  2392. */
  2393. Trans.prototype.clearCellInfo = function() {
  2394. const $cellInfo = $("#currentCoordinate");
  2395. $cellInfo.val("");
  2396. return true;
  2397. }
  2398. /**
  2399. * Set value of the Current Cell info section
  2400. * @param {Number} row
  2401. * @param {Number} column
  2402. */
  2403. Trans.prototype.setCellInfo = function(row, column) {
  2404. const $cellInfo = $("#currentCoordinate");
  2405. var drawedRow = row+1;
  2406. var drawedCol = column+1;
  2407. $cellInfo.val(drawedRow+","+drawedCol);
  2408. trans.lastSelectedCell = [row, column];
  2409. }
  2410. Trans.prototype.drawCellEmblem = function() {
  2411. const row = this.lastSelectedCell[0]
  2412. const col = this.lastSelectedCell[1]
  2413. $(".cellEmblems > i").addClass("hidden");
  2414. if (col == this.keyColumn) return;
  2415. $(".cellEmblems > .emblemComment").attr("title", "");
  2416. if (this.isOrganicCell(row, col)) $(".cellEmblems > .emblemOrganic").removeClass("hidden")
  2417. if (this.isVisitedCell(row, col)) {
  2418. $(".cellEmblems > .emblemFootprint").removeClass("hidden")
  2419. } else {
  2420. $(".cellEmblems > .emblemFirstVisit").removeClass("hidden")
  2421. }
  2422. let comment = this.getCellComment(row, col);
  2423. if (comment) {
  2424. $(".cellEmblems > .emblemComment").removeClass("hidden")
  2425. $(".cellEmblems > .emblemComment").attr("title", "<b>Cell comment:</b><br />"+comment);
  2426. }
  2427. }
  2428. /**
  2429. * connect this.data to trans.project.files[trans.getSelectedId()].data
  2430. */
  2431. Trans.prototype.connectData = function() {
  2432. // connect this.data to trans.project.files[trans.getSelectedId()].data
  2433. if (!this.getSelectedId()) return console.warn("unable to connect data with selected id");
  2434. if (!this.project.files[this.getSelectedId()].data) return console.warn("unable to connect data with selected id");
  2435. this.project.files[this.getSelectedId()].data = trans.data;
  2436. }
  2437. /**
  2438. * Check whether row is the last row
  2439. * @param {Number} row - Row index to be checked
  2440. * @returns {Boolean} True if row is the last row
  2441. */
  2442. Trans.prototype.isLastRow = function(row) {
  2443. //trans.data = trans.data || [];
  2444. if (Boolean(trans.data) == false) {
  2445. trans.data = [];
  2446. trans.connectData();
  2447. }
  2448. row = row || 0;
  2449. if (row == trans.data.length-1) return true;
  2450. return false;
  2451. }
  2452. /**
  2453. * Get the currently active Table
  2454. * @returns {String[][]} Two dimensional array of the data
  2455. */
  2456. Trans.prototype.getCurrentData = function() {
  2457. return this.data;
  2458. }
  2459. /**
  2460. * Get text from the last selected cell
  2461. * @returns {String} Text of the last selected cell
  2462. */
  2463. Trans.prototype.getTextFromLastSelected = function() {
  2464. var data = this.getCurrentData();
  2465. if (empty(this.lastSelectedCell)) return "";
  2466. return data[this.lastSelectedCell[0]][this.lastSelectedCell[1]];
  2467. }
  2468. /**
  2469. * Get the value of the Text Editor field
  2470. * @param {String} text Value of the Text Editor field
  2471. * @param {Boolean} [triggerEvent=false] - Trigger change event
  2472. */
  2473. Trans.prototype.textEditorSetValue = function(text, triggerEvent=false) {
  2474. $("#currentCellText").val(text);
  2475. ui.generateBackgroundNumber();
  2476. if (triggerEvent) $("#currentCellText").trigger("change")
  2477. }
  2478. /**
  2479. * Standard procedure executed after selecting cells
  2480. * @param {Number} row - Row from
  2481. * @param {Number} column - Column from
  2482. * @param {Number} row2 - Row to
  2483. * @param {Number} column2 - Column to
  2484. */
  2485. Trans.prototype.doAfterSelection = function(row, column, row2, column2) {
  2486. const $editor = $("#currentCellText");
  2487. //$editor.val(this.getValue());
  2488. //$editor.val(trans.grid.getCellMeta(row,column).instance.getValue());
  2489. $editor.val(trans.data[row][column]);
  2490. $editor.prop("readonly", false);
  2491. var isLastRow = trans.isLastRow(row)
  2492. if (column == 0) {
  2493. if ( isLastRow == false) {
  2494. $editor.prop("readonly", true);
  2495. }
  2496. }
  2497. $editor.data("column", column);
  2498. $editor.data("row", row);
  2499. trans.setCellInfo(row, column);
  2500. trans.setStatusBarContext(row);
  2501. trans.translateSelectedRow(row);
  2502. ui.generateBackgroundNumber($editor);
  2503. if (typeof romaji !== 'undefined') {
  2504. if (trans.config.loadRomaji == false ) return true;
  2505. romaji.resolve(trans.data[row][0], $("#currentRomaji .text"));
  2506. }
  2507. // romaji header
  2508. $("#currentRomaji .header").text(this.getRowInfoText(row, true) || "");
  2509. this.drawCellEmblem();
  2510. // leave trail with debounce
  2511. if (this.getOption("gridInfo")?.isRuleActive && this.getOption("gridInfo")?.enableTrail) {
  2512. if (this._cellInfoTrack) clearTimeout(this._cellInfoTrack);
  2513. if (column != this.keyColumn && this.getText(row, column)) {
  2514. this._cellInfoTrack = setTimeout(()=> {
  2515. clearTimeout(this._cellInfoTrack);
  2516. this._cellInfoTrack = undefined;
  2517. console.log("Setting cellInfo", "v", 1, this.getSelectedId(), row, column);
  2518. this.cellInfo.set("v", 1, this.getSelectedId(), row, column);
  2519. $(`table tbody td[data-coord="${row}-${column}"]`).addClass("viewed")
  2520. }, 1000)
  2521. }
  2522. }
  2523. const thisObj = this.getSelectedObject();
  2524. thisObj.lastSelectedCell = [row, column];
  2525. /**
  2526. * Trigger event right after a cell(s) is selected
  2527. * @event Trans#onAfterSelectCell
  2528. * @param {Object} Options
  2529. * @param {Number} Options.fromRow
  2530. * @param {Number} Options.fromCol
  2531. * @param {Number} Options.toRow
  2532. * @param {Number} Options.toCol
  2533. * @param {Boolean} Options.isLastRow
  2534. */
  2535. this.trigger("onAfterSelectCell",
  2536. {
  2537. fromRow:row, fromCol:column, toRow:row2, toCol:column2, isLastRow:isLastRow
  2538. }
  2539. );
  2540. }
  2541. //================================================================
  2542. //
  2543. // HANDLING FILE NAVIGATION
  2544. //
  2545. //================================================================
  2546. /**
  2547. * Resets current cell editor
  2548. */
  2549. Trans.prototype.resetCurentCellEditor = function() {
  2550. var $currentCellText = $("#currentCellText");
  2551. $currentCellText.val("");
  2552. $currentCellText.data("row", 0)
  2553. $currentCellText.data("column", 0)
  2554. trans.setCellInfo(0, 0);
  2555. trans.setStatusBarContext(0);
  2556. $("#currentRomaji .text").text("");
  2557. $("#currentRomaji .header").text("");
  2558. }
  2559. /**
  2560. * Creates a new file(new object), register it into the left panel
  2561. * @param {String} filename - Name of the file
  2562. * @param {String} dirname - Directory location
  2563. * @param {Object} options
  2564. * @param {String} options.originalFormat - Original format of the file
  2565. * @param {String} options.type - File type
  2566. * @returns {Object}
  2567. */
  2568. Trans.prototype.createFile = function(filename, dirname, options) {
  2569. // Create a new file
  2570. // register it into the left panel
  2571. options = options || {};
  2572. options.originalFormat = options.originalFormat || ""
  2573. options.type = options.type || null
  2574. var isValid = require('is-valid-path');
  2575. dirname = dirname || "/"
  2576. if (!isValid(filename)) {
  2577. return {
  2578. error:true,
  2579. msg : filename+ t(" is not a valid object name")
  2580. }
  2581. }
  2582. if (!isValid(dirname) && dirname !== "*") {
  2583. return {
  2584. error:true,
  2585. msg : dirname+ t(" is not a valid directory name")
  2586. }
  2587. }
  2588. var fullPath = nwPath.join("/", dirname, filename);
  2589. var fileObj;
  2590. if (this.getObjectById(fullPath)) {
  2591. return {
  2592. error:true,
  2593. msg : fullPath+ t(" is already exist")
  2594. }
  2595. }
  2596. if (dirname == "*") {
  2597. // create a reference
  2598. fullPath = filename;
  2599. options.type = options.type || "reference"
  2600. fileObj = this.createFileData(fullPath, {
  2601. originalFormat : options.originalFormat || "TRANSLATOR++ GENERATED TABLE",
  2602. type : options.type,
  2603. dirname : "*"
  2604. });
  2605. } else {
  2606. fullPath = fullPath.replace(/\\/g, "/");
  2607. fileObj = this.createFileData(fullPath, {
  2608. originalFormat : options.originalFormat,
  2609. type : options.type
  2610. });
  2611. }
  2612. trans.project.files[fullPath] = fileObj;
  2613. trans.addFileItem(fullPath, fileObj);
  2614. this.evalTranslationProgress();
  2615. ui.fileList.reIndex();
  2616. ui.initFileSelectorDragSelect();
  2617. return {}
  2618. }
  2619. /**
  2620. * Select of
  2621. * @param {JQuery} $element - Selected element
  2622. * @param {Object} options
  2623. * @param {Function} options.onDone - When selected done
  2624. * @returns {JQuery} - Instance of jquery of the selected element
  2625. */
  2626. Trans.prototype.selectFile = function($element, options) {
  2627. options = options||{};
  2628. options.onDone = options.onDone||undefined;
  2629. this.grid.deselectCell()
  2630. if (typeof $element == "string") $element = $(".fileList [data-id="+common.escapeSelector($element)+"]");
  2631. const thisID = $element.closest("li").data("id");
  2632. this.trigger("beforeSelectFile", [trans?.project?.selectedId, thisID])
  2633. //console.log("switching to other file");
  2634. $element.closest(".tree").find("li").removeClass("selected");
  2635. $element.closest("li").addClass("selected");
  2636. trans.project.selectedId = thisID;
  2637. trans.data = trans.project.files[thisID].data;
  2638. //trans.indexIds = trans.project.files[thisID].indexIds;
  2639. trans.selectedData = trans.project.files[thisID];
  2640. // force reindexig each build
  2641. trans.buildIndex();
  2642. trans.clearCellInfo();
  2643. trans.clearEditor();
  2644. trans.setStatusBarNumData();
  2645. trans.resetCurentCellEditor();
  2646. if ($(".menu-button.addNote").hasClass("checked")) {
  2647. ui.openFileNote();
  2648. }
  2649. $(".fileId").val(thisID);
  2650. ui.disableGrid(false);
  2651. ui.evalFileNoteIcon();
  2652. this.trigger("objectSelected", thisID);
  2653. this.grid.loadData(trans.data);
  2654. //trans.loadComments();
  2655. //trans.refreshGrid({onDone:options.onDone});
  2656. //trans.grid.render();
  2657. trans.loadComments();
  2658. trans.renderGridInfo();
  2659. trans.grid.setFixedTableHeightByData(trans.data)
  2660. trans.grid.scrollViewportTo(0, 0);
  2661. // const thisObjLastSelectedCell = trans.project?.files?.[thisID]?.lastSelectedCell;
  2662. // if (Array.isArray(thisObjLastSelectedCell)) {
  2663. // trans.grid.scrollViewportTo(thisObjLastSelectedCell[0], thisObjLastSelectedCell[1]);
  2664. // trans.grid.selectCell(thisObjLastSelectedCell[0], thisObjLastSelectedCell[1]);
  2665. // }
  2666. return $element;
  2667. }
  2668. Trans.prototype.renderGridInfo = function() {
  2669. // render options in trans.project.options.gridInfo
  2670. let gridInfo = this.getOption("gridInfo") || {};
  2671. if (gridInfo?.isRuleActive && gridInfo?.rowHeaderInfo) {
  2672. let rowHeaderWidth = gridInfo.rowHeaderWidth||130
  2673. trans.grid.updateSettings({
  2674. rowHeaderWidth: rowHeaderWidth
  2675. });
  2676. $("#table").css("--row-header-width", rowHeaderWidth+"px")
  2677. } else {
  2678. trans.grid.updateSettings({
  2679. rowHeaderWidth: null
  2680. })
  2681. const getWidth = $(`#table [data-role="tablecorner"]`).outerWidth();
  2682. $("#table").css("--row-header-width", getWidth+"px")
  2683. }
  2684. }
  2685. /**
  2686. * Add a new filegroup
  2687. * @param {String} dirname - name of the group
  2688. * @returns {Boolean} True if success
  2689. */
  2690. Trans.prototype.addFileGroup = function(dirname, fileObj) {
  2691. var $group = $("#fileList [data-group='"+CSS.escape(dirname)+"']");
  2692. //console.log("Group : ", dirname , $group.length);
  2693. if ($group.length < 1) {
  2694. //console.log("creating new header");
  2695. var hTemplate = $("<li class='group-header' data-group='"+dirname+"'>"+dirname+"</li>");
  2696. if ($("#fileList .fileListUl .group-header[data-group='*']").length > 0) {
  2697. $("#fileList .fileListUl .group-header[data-group='*']").before(hTemplate);
  2698. } else {
  2699. $("#fileList .fileListUl").append(hTemplate);
  2700. }
  2701. return true;
  2702. }
  2703. return false;
  2704. }
  2705. /**
  2706. * Check whether the ui element of the file is exist or not
  2707. * @param {String} file - File id
  2708. * @param {Object} fileObj - File object
  2709. * @returns {Boolean} True if exist
  2710. */
  2711. Trans.prototype.fileItemExist = function(file, fileObj) {
  2712. if ($("#fileList [data-group='"+CSS.escape(fileObj.dirname)+"'][data-id='"+CSS.escape(file)+"']").length>0) {
  2713. return true;
  2714. }
  2715. return false;
  2716. }
  2717. /**
  2718. * Draw file status
  2719. * @param {String[]} files - list of file ID
  2720. */
  2721. Trans.prototype.drawFileStatus = function(files) {
  2722. if (typeof files == "string") files = [files];
  2723. var $container = $("#fileList");
  2724. for (var i=0; i<files.length; i++) {
  2725. (()=> {
  2726. var thisFile = files[i];
  2727. var thisObj = this.getObjectById(thisFile);
  2728. var $li = $container.find(`[data-id="${CSS.escape(files[i])}"]`);
  2729. if ($li.length == 0) return;
  2730. $li.removeClass("isCompleted");
  2731. $li.removeClass("isRequireAttention");
  2732. if (thisObj.isCompleted) $li.addClass("isCompleted");
  2733. if (thisObj.isRequireAttention) $li.addClass("isRequireAttention");
  2734. // handling note
  2735. //$markersWrapper.empty();
  2736. if ($li.data("noteTooltipIsActive")) {
  2737. $li.tooltip("destroy");
  2738. $li.data("noteTooltipIsActive", false);
  2739. }
  2740. var $markersWrapper = $li.find(".markers");
  2741. $markersWrapper.empty();
  2742. if (thisObj.note) {
  2743. // add keyword
  2744. $markersWrapper.append($(`<span class="hidden"></span>`).text(thisObj.note))
  2745. var $noteIcon = $(`<i class="icon-commenting"></i>`);
  2746. $markersWrapper.append($noteIcon);
  2747. if (thisObj.noteColor) $noteIcon.css("color", thisObj.noteColor);
  2748. // for some reason I can not hook the mouse events on $noteIcon
  2749. // so I hook it into $li instead. This behavior is acceptable for now.
  2750. $li.tooltip({
  2751. content: function() {
  2752. var $tooltip = $("<div class='fileObjTooltipWindow'></div>");
  2753. if (thisObj.noteColor) {
  2754. $tooltip.css("border-left-color", thisObj.noteColor);
  2755. $tooltip.addClass("hasColor")
  2756. }
  2757. $tooltip.text(thisObj.note);
  2758. $tooltip.on("mouseenter", function() {
  2759. ui.fileObjectTooltip.open($tooltip.clone(), $li)
  2760. })
  2761. return $tooltip;
  2762. },
  2763. tooltipClass: "fileObjTooltipWrapper",
  2764. show: {
  2765. effect: "fade",
  2766. duration: 100
  2767. },
  2768. hide: {
  2769. effect: "none",
  2770. delay: 100
  2771. },
  2772. position: {
  2773. my: "left top",
  2774. at: "right+6 top-16",
  2775. of: $li
  2776. },
  2777. open: function( event, ui ) {
  2778. }
  2779. });
  2780. $li.data("noteTooltipIsActive", true);
  2781. }
  2782. })()
  2783. }
  2784. }
  2785. /**
  2786. * Add file item into the left panel
  2787. * @param {String} file - File ID
  2788. * @param {fileObj} fileObj - File Object
  2789. * @returns {Boolean}
  2790. */
  2791. Trans.prototype.addFileItem = function(file, fileObj) {
  2792. // skip if exist
  2793. if (this.fileItemExist(file, fileObj)) return false;
  2794. // draw header if exist
  2795. this.addFileGroup(fileObj.dirname);
  2796. var $li = $("<li></li>");
  2797. $li.append("<input type='checkbox' class='fileCheckbox' title='hold shift for bulk selection' />"+
  2798. "<a href='#' class='filterable'><span class='filename'></span>"+
  2799. "<span class='markers'></span>"+
  2800. "<span class='percent' title='progress'></span>"+
  2801. "<div class='progress' title='progress'></div>"+
  2802. "</a>");
  2803. $li.attr("title", file);
  2804. $li.attr("data-group", fileObj.dirname);
  2805. $li.find(".fileCheckbox").attr("value", file);
  2806. $li.find(".filename").text(fileObj.filename);
  2807. $li.addClass("data-selector");
  2808. $li.data("id", file);
  2809. $li.attr("data-id", file);
  2810. //$li.data("data", fileObj);
  2811. $li.find("a").on("mousedown", function(e) {
  2812. //console.log("middle click clicked");
  2813. //console.log(e);
  2814. if( e.which == 2 ) {
  2815. e.preventDefault();
  2816. trans.clearSelection();
  2817. return false;
  2818. }
  2819. });
  2820. $li.find("a").on("dblclick", function(e) {
  2821. // select that item
  2822. var $thisCheckbox = $(this).closest("li").find(".fileCheckbox");
  2823. $thisCheckbox.prop("checked", !$thisCheckbox.prop("checked")).trigger("change")
  2824. });
  2825. $li.find("a").on("click", function(e) {
  2826. //console.log("clicked");
  2827. e.preventDefault();
  2828. trans.selectFile($(this).closest("li"));
  2829. });
  2830. $li.find(".fileCheckbox").on("change", function() {
  2831. if ($(this).prop("checked") == true) {
  2832. trans.$lastCheckedFile = $(this);
  2833. $(this).closest(".data-selector").addClass("hasCheck");
  2834. } else {
  2835. trans.$lastCheckedFile = undefined;
  2836. $(this).closest(".data-selector").removeClass("hasCheck");
  2837. }
  2838. });
  2839. $li.find(".fileCheckbox").on("mousedown", function(e) {
  2840. console.log("mouse down", console.log($(this).closest("li")));
  2841. (async ()=> {
  2842. // work around ds-hover bug
  2843. await common.wait(200);
  2844. $(this).closest("li").removeClass("ds-hover");
  2845. })();
  2846. if (!trans.$lastCheckedFile) return false;
  2847. if (e.shiftKey) {
  2848. console.log("The SHIFT key was pressed!");
  2849. var $checkBoxes = $(".fileList .fileCheckbox");
  2850. var lastIndex = $checkBoxes.index(trans.$lastCheckedFile);
  2851. var thisIndex = $checkBoxes.index(this);
  2852. var chckFrom;
  2853. var chckTo;
  2854. if (lastIndex < thisIndex) {
  2855. chckFrom = lastIndex;
  2856. chckTo = thisIndex;
  2857. } else {
  2858. chckFrom = thisIndex;
  2859. chckTo = lastIndex;
  2860. }
  2861. console.log("check from index "+chckFrom+" to "+chckTo);
  2862. for (var i=chckFrom; i<chckTo; i++) {
  2863. $checkBoxes.eq(i).prop("checked", true).trigger("change");
  2864. }
  2865. }
  2866. });
  2867. $("#fileList [data-group='"+CSS.escape(fileObj.dirname)+"']").last().after($li);
  2868. }
  2869. /**
  2870. * Draw the left panel
  2871. * @fires Trans#onLoadTrans
  2872. */
  2873. Trans.prototype.drawFileSelector = function() {
  2874. if (typeof this.project.files == 'undefined') return false;
  2875. $("#fileList .fileListUl").empty();
  2876. this.generateNewDictionaryTable();
  2877. for (var file in this.project.files) {
  2878. this.addFileItem(file, this.project.files[file]);
  2879. }
  2880. this.drawFileStatus(this.getAllFiles());
  2881. this.setStatusBarEngine();
  2882. this.evalTranslationProgress();
  2883. ui.fileList.reIndex();
  2884. ui.initFileSelectorDragSelect();
  2885. ui.enableButtons();
  2886. this.renderGridInfo();
  2887. var TranslationByContext = require("www/js/TranslationByContext.js");
  2888. ui.translationByContext = new TranslationByContext();
  2889. //engines.handler('onLoadTrans').apply(this, arguments);
  2890. this.inProject = true;
  2891. engines.current().triggerHandler('onLoadTrans', this, arguments);
  2892. this.initLocalStorage();
  2893. /**
  2894. * Trigger event after trans file is loaded
  2895. * @event Trans#onLoadTrans
  2896. */
  2897. this.trigger('onLoadTrans');
  2898. }
  2899. Trans.prototype.initLocalStorage = async function() {
  2900. let thisProjectDB = trans?.project?.projectId || "global"
  2901. this.localStorage = new (require("better-localstorage"))("tp"+thisProjectDB);
  2902. }
  2903. Trans.prototype.unInitLocalStorage = async function() {
  2904. if (typeof this.localStorage?.db?.close == "function") await this.localStorage.db.close();
  2905. this.localStorage = undefined;
  2906. }
  2907. /**
  2908. * Mark a file as complete
  2909. * @param {Boolean} mark - True if complete
  2910. * @param {String[]} [files=this.getAllFiles()] - List of the file IDs
  2911. * @returns {Boolean}
  2912. */
  2913. Trans.prototype.setMarkAsComplete = function(mark, files) {
  2914. files = files || trans.getCheckedFiles();
  2915. if (files.length < 1) files = trans.getAllFiles();
  2916. for (var i=0; i<files.length; i++) {
  2917. var thisFile = files[i];
  2918. this.getObjectById(thisFile).isCompleted = mark;
  2919. }
  2920. this.drawFileStatus(files);
  2921. return true;
  2922. }
  2923. /**
  2924. * select all with matching filter
  2925. * @param {(String|String[])} [filter=All] - List of the selected file ID. When empty then all will be selected
  2926. * @param {Boolean} append - If true, then add into the previous selection
  2927. */
  2928. Trans.prototype.selectAll = function(filter, append) {
  2929. filter = filter||[];
  2930. append = append||false;
  2931. if (typeof filter == 'string') filter = [filter];
  2932. var $checkBoxes = $("#fileList .fileCheckbox");
  2933. if (filter.length == 0) {
  2934. $checkBoxes.each(function() {
  2935. $(this).prop("checked", true).trigger("change");
  2936. });
  2937. } else {
  2938. if (!append) $checkBoxes.prop("checked", false).trigger("change");
  2939. $checkBoxes.each(function() {
  2940. var $this = $(this);
  2941. if (filter.includes($this.closest("li").data("id"))) $this.prop("checked", true).trigger("change");
  2942. });
  2943. }
  2944. }
  2945. /**
  2946. * Select file by given function
  2947. * @param {Function} filter - Filter function
  2948. */
  2949. Trans.prototype.selectObjectsByFilter = function(filter) {
  2950. const $checkBoxes = $("#fileList .fileCheckbox");
  2951. if (typeof filter !== "function") return;
  2952. $checkBoxes.each(function() {
  2953. const $this = $(this);
  2954. if (filter($this.closest("li").data("id"), $this)) $this.prop("checked", true).trigger("change");
  2955. });
  2956. }
  2957. /**
  2958. * Inverts current selection
  2959. */
  2960. Trans.prototype.invertSelection = function() {
  2961. var $checkBoxes = $("#fileList .fileCheckbox");
  2962. $checkBoxes.each(function() {
  2963. $(this).prop("checked", !$(this).prop("checked")).trigger("change");
  2964. });
  2965. }
  2966. /**
  2967. * Clear current selection
  2968. */
  2969. Trans.prototype.clearSelection = function() {
  2970. var $checkBoxes = $("#fileList .fileCheckbox");
  2971. $checkBoxes.each(function() {
  2972. $(this).prop("checked", false).trigger("change");
  2973. });
  2974. }
  2975. /**
  2976. * Initialize file navigator
  2977. */
  2978. Trans.prototype.initFileNav = function() {
  2979. //console.log(trans.fileListLoaded);
  2980. //this function will be executed whenever initializing a new trans file
  2981. //this function is suitable to hook all initialization event of trans
  2982. console.log("running trans.initFileNav");
  2983. //console.log("current trans : ", trans);
  2984. // reevaluating trans.fileListLoaded based on existance of trans.project.files
  2985. try {
  2986. if (typeof trans.project.files !=='undefined') {
  2987. trans.fileListLoaded = true;
  2988. } else {
  2989. trans.fileListLoaded = false;
  2990. }
  2991. } catch (e) {
  2992. trans.fileListLoaded = false;
  2993. }
  2994. if (trans.fileListLoaded == false) {
  2995. trans.createProject({
  2996. onAfterLoading:function() {
  2997. trans.drawFileSelector();
  2998. }
  2999. });
  3000. return false;
  3001. } else {
  3002. this.unInitFileNav();
  3003. trans.drawFileSelector();
  3004. this.onFileNavLoaded.call(this);
  3005. //engines.handler('onLoadTrans').apply(this, arguments);
  3006. /**
  3007. * Triggers after trans loaded
  3008. * @event Trans#transLoaded
  3009. * @param {Trans} this - Instance of trans
  3010. */
  3011. this.trigger("transLoaded", this);
  3012. }
  3013. }
  3014. /**
  3015. * Un-initialize file navigator
  3016. * @fires Trans#onUnloadTrans
  3017. * @fires Engines#onUnloadTrans
  3018. */
  3019. Trans.prototype.unInitFileNav = function() {
  3020. $("#fileList .fileListUl").empty();
  3021. ui.fileList.reIndex();
  3022. this.onFileNavUnloaded.call(this);
  3023. engines.handler('onUnloadTrans').apply(this, arguments);
  3024. ui.ribbonMenu.clear();
  3025. ui.disableButtons();
  3026. /**
  3027. * Triggers after a project is closed.
  3028. * @event Trans#onUnloadTrans
  3029. */
  3030. this.trigger('onUnloadTrans')
  3031. }
  3032. /**
  3033. * Evaluate translation progress
  3034. * @param {(String|String[])} [file=All] - List of file IDs to be evaluated
  3035. * @param {Object} [progressData] - Progress data
  3036. */
  3037. Trans.prototype.evalTranslationProgress = function(file, progressData) {
  3038. file = file||[];
  3039. var dataResult = progressData||trans.countTranslated(file)||{};
  3040. for (var id in dataResult) {
  3041. var fileSelector = $(".fileList [data-id="+common.escapeSelector(id)+"]");
  3042. fileSelector.find(".percent").text(Math.round(dataResult[id].percent));
  3043. fileSelector.find(".progress").css("background", "linear-gradient(to right, #3159f9 0%,#3159f9 "+dataResult[id].percent+"%,#ff0004 "+dataResult[id].percent+"%,#ff0004 100%)");
  3044. }
  3045. }
  3046. /**
  3047. * Get information of the current progress
  3048. * @param {Boolean} reset - If True, will reset the stats
  3049. * @returns {Object} Stats of the project
  3050. */
  3051. Trans.prototype.getStats = function(reset) {
  3052. function countWords(str) {
  3053. return str.trim().split(/\s+/).length;
  3054. }
  3055. var stats = {
  3056. files : 0,
  3057. folders: 0,
  3058. progress: 0,
  3059. words:0,
  3060. characters:0,
  3061. rows:0,
  3062. rowTranslated:0,
  3063. percent:0,
  3064. organic:0
  3065. }
  3066. var fromCache = false;
  3067. if (!this.project) return stats;
  3068. if (!this.project.files) return stats;
  3069. if (!reset) {
  3070. if (this.project.stats) {
  3071. fromCache = true;
  3072. stats = this.project.stats;
  3073. }
  3074. }
  3075. for (var i in this.project.files) {
  3076. var thisObj = this.project.files[i];
  3077. if (thisObj.originalFormat == "TRANSLATOR++ GENERATED TABLE") continue;
  3078. stats.files++;
  3079. if (thisObj.progress) {
  3080. stats.rows += thisObj.progress.length;
  3081. stats.rowTranslated += thisObj.progress.translated;
  3082. }
  3083. if (fromCache) continue;
  3084. if (empty(thisObj.data)) continue;
  3085. for (var row=0; row<thisObj.data.length; row++) {
  3086. var thisRow = thisObj.data[row];
  3087. if (empty(thisRow)) continue;
  3088. if (!thisRow[this.keyColumn]) continue;
  3089. stats.characters += thisRow[this.keyColumn].length;
  3090. stats.words += countWords(thisRow[this.keyColumn]);
  3091. // calculating organic
  3092. var translator = this.cellInfo.getBestCellInfo(i, row, "t");
  3093. if (translator == "HU") stats.organic++
  3094. }
  3095. }
  3096. if (stats.rows > 0) stats.percent = (stats.rowTranslated/stats.rows) * 100;
  3097. stats.folders = $(".fileList .group-header").length - 1;
  3098. stats.organicPercent = (stats.organic/stats.rowTranslated) *100;
  3099. this.stats = stats;
  3100. return stats;
  3101. }
  3102. Trans.prototype.setFileNoteColor = function(color, files) {
  3103. files ||= this.getSelectedId();
  3104. if (Array.isArray(files) == false) files = [files];
  3105. for (let i in files) {
  3106. let obj = this.getObjectById(files[i]);
  3107. if (!color) {
  3108. if (obj.noteColor) delete obj.noteColor;
  3109. continue;
  3110. }
  3111. obj.noteColor = color;
  3112. }
  3113. this.drawFileStatus(files);
  3114. ui.evalFileNoteIcon();
  3115. }
  3116. Trans.prototype.setFileNote = function(note, files) {
  3117. files ||= this.getSelectedId();
  3118. if (Array.isArray(files) == false) files = [files];
  3119. for (let i in files) {
  3120. let obj = this.getObjectById(files[i]);
  3121. obj.note = note;
  3122. }
  3123. this.drawFileStatus(files);
  3124. ui.evalFileNoteIcon();
  3125. ui.fileList.reIndex();
  3126. }
  3127. /**
  3128. * Load comments into the grid
  3129. */
  3130. Trans.prototype.loadComments = function() {
  3131. trans.grid.comment = trans.grid.comment||trans.grid.getPlugin('comments');
  3132. var selectedObj = trans.getSelectedObject();
  3133. if (!selectedObj) return false;
  3134. if (typeof selectedObj.comments == 'undefined') return false;
  3135. for (var row in selectedObj.comments) {
  3136. for (var col in selectedObj.comments[row]) {
  3137. //console.log("set comment on", row, col, selectedObj.comments[row][col]);
  3138. trans.grid.comment.setCommentAtCell(parseInt(row), parseInt(col), selectedObj.comments[row][col]);
  3139. }
  3140. }
  3141. }
  3142. // ===============================================================
  3143. // CONTEXT MENU
  3144. // ===============================================================
  3145. Trans.prototype.runCustomScript = async function(workspace, scriptPath, options) {
  3146. console.log("Running custom script with arguments:", arguments);
  3147. options = options || {};
  3148. var CodeRunner = require("www/js/CodeRunner.js")
  3149. var codeRunner = new CodeRunner();
  3150. var code = await common.fileGetContents(scriptPath);
  3151. if (!code) return alert(t("Error opening file :"+scriptPath))
  3152. await ui.showBusyOverlay();
  3153. await common.wait(200);
  3154. try {
  3155. var result = await codeRunner.run(code, workspace, options);
  3156. if (result) alert(result);
  3157. } catch (e) {
  3158. alert(t("Error executing :")+nwPath.basename(scriptPath)+"\n"+e.toString());
  3159. }
  3160. await ui.hideBusyOverlay();
  3161. }
  3162. Trans.prototype.updateRunScriptMenu = function() {
  3163. console.log("Updating run script menu");
  3164. this.fileSelectorMenu = this.fileSelectorMenu || {};
  3165. // rowByrow
  3166. // resets menu
  3167. this.fileSelectorMenu.withSelected.items.runScript.items.forEachRowRun.items = {};
  3168. var forEachRowRunItems = this.fileSelectorMenu.withSelected.items.runScript.items.forEachRowRun.items;
  3169. var rowIteratorConfig = sys.getConfig("codeEditor/rowIterator");
  3170. if (!rowIteratorConfig) {
  3171. sys.setConfig("codeEditor/rowIterator", {quickLaunch:[]});
  3172. //sys.getConfig("codeEditor/rowIterator");
  3173. }
  3174. rowIteratorConfig ||= {}
  3175. rowIteratorConfig.quickLaunch ||= [];
  3176. for (let i=0; i<rowIteratorConfig["quickLaunch"].length; i++) {
  3177. (()=>{
  3178. var filePath = rowIteratorConfig["quickLaunch"][i];
  3179. var filename = common.getFilename(filePath);
  3180. var thisId = common.generateId()
  3181. forEachRowRunItems[thisId] = {
  3182. name: filename,
  3183. callback: (key, opt) => {
  3184. var conf = confirm(t("Are you sure want to execute the following script?")+"\n"+filename);
  3185. if (!conf) return;
  3186. this.runCustomScript("rowIterator", filePath);
  3187. }
  3188. }
  3189. })()
  3190. }
  3191. if (Object.keys(forEachRowRunItems).length > 0) {
  3192. forEachRowRunItems["sep0"] = "---------";
  3193. forEachRowRunItems["clearQuickLaunch"] = {
  3194. name: t("Clear quick launch"),
  3195. icon: 'context-menu-icon icon-trash',
  3196. callback: (key, opt) => {
  3197. var conf = confirm(t("Are you sure want to clear quick launch?"));
  3198. if (!conf) return;
  3199. sys.setConfig("codeEditor/rowIterator", {quickLaunch:[]});
  3200. sys.saveConfig();
  3201. this.updateRunScriptMenu();
  3202. }
  3203. }
  3204. } else {
  3205. forEachRowRunItems["howToAdd"] = {
  3206. name: t("How to add Automation here"),
  3207. icon: 'context-menu-icon icon-help',
  3208. callback: (key, opt) => {
  3209. nw.Shell.openExternal("https://dreamsavior.net/docs/translator/execute-script/pin-your-automation-to-quickly-launch-from-translator/");
  3210. }
  3211. }
  3212. }
  3213. // object by object
  3214. // resets menu
  3215. this.fileSelectorMenu.withSelected.items.runScript.items.forEachObjectRun.items = {};
  3216. var forEachObjectRunItems = this.fileSelectorMenu.withSelected.items.runScript.items.forEachObjectRun.items;
  3217. var objectIteratorConfig = sys.getConfig("codeEditor/objectIterator");
  3218. if (!objectIteratorConfig) {
  3219. sys.setConfig("codeEditor/objectIterator", {quickLaunch:[]});
  3220. objectIteratorConfig = sys.getConfig("codeEditor/objectIterator");
  3221. }
  3222. objectIteratorConfig["quickLaunch"] = objectIteratorConfig["quickLaunch"] || [];
  3223. for (let i=0; i<objectIteratorConfig["quickLaunch"].length; i++) {
  3224. (()=>{
  3225. var filePath = objectIteratorConfig["quickLaunch"][i];
  3226. var filename = common.getFilename(filePath);
  3227. var thisId = common.generateId()
  3228. forEachObjectRunItems[thisId] = {
  3229. name: filename,
  3230. callback: (key, opt) => {
  3231. var conf = confirm(t("Are you sure want to execute the following script?")+"\n"+filename);
  3232. if (!conf) return;
  3233. this.runCustomScript("objectIterator", filePath);
  3234. }
  3235. }
  3236. })()
  3237. }
  3238. if (Object.keys(forEachObjectRunItems).length > 0) {
  3239. forEachObjectRunItems["sep0"] = "---------";
  3240. forEachObjectRunItems["clearQuickLaunch"] = {
  3241. name: t("Clear quick launch"),
  3242. icon: 'context-menu-icon icon-trash',
  3243. callback: (key, opt) => {
  3244. var conf = confirm(t("Are you sure want to clear quick launch?"));
  3245. if (!conf) return;
  3246. sys.setConfig("codeEditor/objectIterator", {quickLaunch:[]});
  3247. sys.saveConfig();
  3248. this.updateRunScriptMenu();
  3249. }
  3250. }
  3251. } else {
  3252. forEachObjectRunItems["howToAdd"] = {
  3253. name: t("How to add Automation here"),
  3254. icon: 'context-menu-icon icon-help',
  3255. callback: (key, opt) => {
  3256. nw.Shell.openExternal("https://dreamsavior.net/docs/translator/execute-script/pin-your-automation-to-quickly-launch-from-translator/");
  3257. }
  3258. }
  3259. }
  3260. }
  3261. Trans.prototype.updateRunScriptGridMenu = function() {
  3262. // cell level
  3263. this.gridContextMenu.runAutomation.submenu = {
  3264. items: []
  3265. }
  3266. var forEachCellRunItems = this.gridContextMenu.runAutomation.submenu.items;
  3267. var cellSelectionConfig = sys.getConfig("codeEditor/gridSelection");
  3268. if (!cellSelectionConfig) {
  3269. sys.setConfig("codeEditor/gridSelection", {quickLaunch:[]});
  3270. cellSelectionConfig = sys.getConfig("codeEditor/gridSelection");
  3271. }
  3272. cellSelectionConfig["quickLaunch"] = cellSelectionConfig["quickLaunch"] || [];
  3273. for (var i=0; i<cellSelectionConfig["quickLaunch"].length; i++) {
  3274. (()=>{
  3275. var filePath = cellSelectionConfig["quickLaunch"][i];
  3276. console.log("Adding context menu", filePath);
  3277. var filename = common.getFilename(filePath);
  3278. var thisId = common.generateId()
  3279. forEachCellRunItems.push({
  3280. name: filename,
  3281. key:"runAutomation:"+thisId,
  3282. callback: (key, opt) => {
  3283. var conf = confirm(t("Are you sure want to execute the following script?")+"\n"+filename);
  3284. if (!conf) return;
  3285. this.runCustomScript("gridSelection", filePath);
  3286. }
  3287. })
  3288. })()
  3289. }
  3290. }
  3291. /**
  3292. * Initialize grid's context menu
  3293. *
  3294. */
  3295. Trans.prototype.fileSelectorContextMenuInit = function() {
  3296. console.log("trans.fileSelectorContextMenuInit");
  3297. var trans = this;
  3298. this.fileSelectorMenu = {
  3299. "selectAll" : {"name" : t("Select all"), icon:"context-menu-icon icon-check2-all"},
  3300. "clearSelection" : {"name" : t("Clear selection")},
  3301. "selectCompleted" : {"name" : t("Select 100%")},
  3302. "selectIncompleted" : {"name" : t("Select <100%")},
  3303. "selectProgressGT" : {"name" : t("Select progress ≥ ...")},
  3304. "selectMarkedAsCompleted" : {"name" : t("Select completed")},
  3305. "invertSelection" : {"name" : t("Invert selection")},
  3306. "sep0": "---------",
  3307. "markCompleteCurrent":{
  3308. "name" : t("Toggle mark as complete"),
  3309. icon: function() {
  3310. return 'context-menu-icon icon-ok';
  3311. }
  3312. },
  3313. "sep1": "---------",
  3314. "withSelected": {
  3315. name: () => {
  3316. var checkedLength = $(".fileCheckbox:checked").length;
  3317. if (checkedLength == 0) {
  3318. trans.fileSelectorMenu.withSelected.icon = 'context-menu-icon icon-docs-1';
  3319. trans.fileSelectorMenu.withSelected.items.deleteFiles.visible = false;
  3320. return t("With all");
  3321. } else {
  3322. return t("With ") + checkedLength + t(" selected")
  3323. }
  3324. },
  3325. icon: function() {
  3326. return 'context-menu-icon icon-check';
  3327. },
  3328. items: {
  3329. "markComplete": {
  3330. name : t("Mark as complete"),
  3331. icon: 'context-menu-icon icon-ok'
  3332. },
  3333. "unsetMarkComplete": {
  3334. name : t("Un-mark as complete")
  3335. },
  3336. "sep0-0":"---------",
  3337. "batchTranslation": {
  3338. name : t("Batch translation"),
  3339. icon: 'context-menu-icon icon-language'
  3340. },
  3341. "sendTo": {
  3342. name : t("Send to..."),
  3343. icon: 'context-menu-icon icon-share-ios-line',
  3344. items: {
  3345. }
  3346. },
  3347. "sep0-1":"---------",
  3348. "wrapText": {"name" : t("Wrap texts"), "icon": "context-menu-icon icon-wordwrap"},
  3349. "trim": {"name" : t("Trim"), "icon": "context-menu-icon icon-article"},
  3350. "padding": {"name" : t("Auto padding"), "icon": "context-menu-icon icon-list-nested"},
  3351. "createScript": {
  3352. name : t("Create Automation"),
  3353. icon: 'context-menu-icon icon-code',
  3354. items: {
  3355. "forEachObject" : {"name": t("For each object"), icon: 'context-menu-icon icon-doc'},
  3356. "forEachRow" : {"name": t("For each row"),icon: 'context-menu-icon icon-menu-1'},
  3357. }
  3358. },
  3359. "runScript": {
  3360. name : t("Run Automation"),
  3361. icon: 'context-menu-icon icon-play',
  3362. items: {
  3363. "forEachObjectRun" : {
  3364. name: t("For each object"),
  3365. icon: 'context-menu-icon icon-doc',
  3366. items: {
  3367. }
  3368. },
  3369. "forEachRowRun" : {
  3370. name: ()=> {
  3371. console.log("rendering for each row");
  3372. return t("For each row")
  3373. },
  3374. icon: 'context-menu-icon icon-menu-1',
  3375. items: {
  3376. }
  3377. },
  3378. }
  3379. },
  3380. "sep0-2":"---------",
  3381. "import": {
  3382. name:t("Import from..."),
  3383. icon:"context-menu-icon icon-login",
  3384. items: {
  3385. "importFromTrans" : {"name": t("Trans File"),icon: 'context-menu-icon icon-tpp'},
  3386. "importFromSheet" : {"name": t("Spreadsheets"),icon: 'context-menu-icon icon-file-excel'},
  3387. "importFromRPGMTransPatch" : {"name": t("RPGMTransPatch Files"),icon: 'context-menu-icon icon-doc-text'}
  3388. }
  3389. },
  3390. "export": {
  3391. name:t("Export into..."),
  3392. icon:"context-menu-icon icon-export",
  3393. items: {
  3394. "exportToGamePatch" : {"name": t("A folder"), icon:() => 'context-menu-icon icon-folder-add'},
  3395. "exportToGamePatchZip" : {"name": t("Zipped Game Patch"),icon:() => 'context-menu-icon icon-file-archive'},
  3396. "exportToCsv" : {"name": t("Comma Separated Value (csv)"),icon:() => 'context-menu-icon icon-file-excel'},
  3397. "exportToXlsx" : {"name": t("Excel 2007 Spreadsheets (xlsx)"),icon:() => 'context-menu-icon icon-file-excel'},
  3398. "exportToXls" : {"name": t("Excel Spreadsheets (xls)"),icon:() => 'context-menu-icon icon-file-excel'},
  3399. "exportToOds" : {"name": t("ODS Spreadsheets"),icon:() => 'context-menu-icon icon-file-excel'},
  3400. "exportToHtml" : {"name": t("Html Spreadsheets"),icon:() => 'context-menu-icon icon-file-code'},
  3401. "exportToTransPatch" : {"name": t("RMTrans Patch"),icon:() => 'context-menu-icon icon-doc-text'}
  3402. }
  3403. },
  3404. "inject" : {
  3405. name: t("Inject Translation"),
  3406. icon: "context-menu-icon icon-download"
  3407. },
  3408. "revert" : {
  3409. name: t("Revert to original"),
  3410. icon: "context-menu-icon icon-ccw"
  3411. },
  3412. "sep0-3":"---------",
  3413. "clearTranslationSel": {"name" : t("Clear translation"), "icon":"context-menu-icon icon-eraser"},
  3414. "deleteFiles": {"name" : t("Delete files"), "icon":"context-menu-icon icon-trash-empty"},
  3415. }
  3416. },
  3417. "sep2": "---------",
  3418. "properties": {
  3419. name: t("Properties"),
  3420. icon:'context-menu-icon icon-cog'
  3421. }
  3422. }
  3423. if (trans.fileSelectorContextMenuIsInitialized) return false;
  3424. $.contextMenu({
  3425. selector: '.fileList .data-selector',
  3426. events: {
  3427. preShow : function($target, e) {
  3428. //$(".context-menu-root").trigger("contextmenu:hide")
  3429. /*
  3430. console.log(arguments);
  3431. var $cTarget = $target;
  3432. $cTarget.closest("ul").find(".contextMenuOpened").removeClass("contextMenuOpened");
  3433. $cTarget.addClass("contextMenuOpened");
  3434. */
  3435. //console.log(arguments);
  3436. },
  3437. hide : function($target, e){
  3438. //$(".fileList .data-selector.contextMenuOpened").removeClass("contextMenuOpened");
  3439. }
  3440. },
  3441. build: function($triggerElement, e) {
  3442. var thisCallback = function(key, options) {
  3443. switch (key) {
  3444. case "selectAll" :
  3445. trans.selectAll();
  3446. break;
  3447. case "clearSelection" :
  3448. trans.clearSelection();
  3449. break;
  3450. case "invertSelection" :
  3451. trans.invertSelection();
  3452. break;
  3453. case "selectCompleted" :
  3454. trans.selectAll(trans.getAllCompletedFiles())
  3455. break;
  3456. case "selectIncompleted" :
  3457. trans.selectAll(trans.getAllIncompletedFiles())
  3458. break;
  3459. case "selectProgressGT" :
  3460. const progress = prompt(t("Select progress greater than"), "0");
  3461. // check if the input is a number
  3462. if (isNaN(progress)) {
  3463. alert(t("Please input a number"));
  3464. return;
  3465. }
  3466. trans.selectObjectsByFilter((id, $this) => {
  3467. const thisObj = trans.getObjectById(id);
  3468. if (!thisObj.progress) return false;
  3469. const thisProgress = thisObj.progress.translated / thisObj.progress.length * 100;
  3470. return thisProgress >= parseInt(progress);
  3471. });
  3472. break;
  3473. case "selectMarkedAsCompleted" :
  3474. trans.selectAll(trans.getAllMarkedAsCompleted());
  3475. break;
  3476. case "markCompleteCurrent" :
  3477. var $elm = $("#fileList .context-menu-active");
  3478. var action = !$elm.hasClass("isCompleted");
  3479. var currentFile = $elm.data("id");
  3480. trans.setMarkAsComplete(action, [currentFile]);
  3481. break;
  3482. case "markComplete" :
  3483. trans.setMarkAsComplete(true);
  3484. break;
  3485. case "unsetMarkComplete" :
  3486. trans.setMarkAsComplete(false);
  3487. break;
  3488. case "batchTranslation" :
  3489. ui.translateAllDialog();
  3490. break;
  3491. case "forEachObject" :
  3492. ui.openAutomationEditor("codeEditor_objectIterator", {
  3493. workspace: "objectIterator"
  3494. });
  3495. break;
  3496. case "forEachRow" :
  3497. ui.openAutomationEditor("codeEditor_rowIterator", {
  3498. workspace: "rowIterator"
  3499. });
  3500. break;
  3501. case "clearTranslationSel" :
  3502. var confirmation = confirm(t("Do you want to clear translation?"));
  3503. var selection = trans.getCheckedFiles();
  3504. if (confirmation) trans.removeAllTranslation(trans.getCheckedFiles(), {refreshGrid:true});
  3505. trans.evalTranslationProgress(selection);
  3506. break;
  3507. case "clearTranslationAll" :
  3508. var confirmation2 = confirm(t("Do you want to clear translation?"));
  3509. var selection2 = trans.getAllFiles();
  3510. if (confirmation2) trans.removeAllTranslation(trans.getAllFiles(), {refreshGrid:true});
  3511. trans.evalTranslationProgress(selection2);
  3512. break;
  3513. case "deleteFiles" :
  3514. ui.deleteFiles();
  3515. break;
  3516. case "wrapText" :
  3517. ui.batchWrapingDialog();
  3518. break;
  3519. case "trim" :
  3520. ui.openTrimWindow();
  3521. break;
  3522. case "padding" :
  3523. ui.openPaddingWindow();
  3524. break;
  3525. case "properties" :
  3526. ui.openFileProperties();
  3527. break;
  3528. // imports
  3529. case "importFromSheet":
  3530. ui.openImportSpreadsheetDialog();
  3531. break;
  3532. case "importFromTrans":
  3533. $("#importTrans").trigger("click");
  3534. break;
  3535. case "importFromRPGMTransPatch":
  3536. ui.openImportRPGMTransDialog();
  3537. break;
  3538. // exports
  3539. case "exportToGamePatch":
  3540. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3541. $("#exportDir").trigger("click");
  3542. break;
  3543. case "exportToGamePatchZip":
  3544. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3545. $("#export").trigger("click");
  3546. break;
  3547. case "exportToCsv":
  3548. $("#exportCSV").trigger("click");
  3549. break;
  3550. case "exportToXlsx":
  3551. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3552. $("#exportXLSX").trigger("click");
  3553. break;
  3554. case "exportToXls":
  3555. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3556. $("#exportXLS").trigger("click");
  3557. break;
  3558. case "exportToOds":
  3559. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3560. $("#exportODS").trigger("click");
  3561. break;
  3562. case "exportToHtml":
  3563. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3564. $("#exportHTML").trigger("click");
  3565. break;
  3566. case "exportToTransPatch":
  3567. $("#dialogExport").data("options", {files:trans.getCheckedFiles()});
  3568. $("#exportTrans").trigger("click");
  3569. break;
  3570. case "inject":
  3571. ui.openInjectDialog();
  3572. break;
  3573. case "revert":
  3574. trans.revertToOriginal();
  3575. break;
  3576. default :
  3577. }
  3578. }
  3579. trans.updateRunScriptMenu()
  3580. return {
  3581. zIndex :1000,
  3582. callback: thisCallback,
  3583. items : trans.fileSelectorMenu
  3584. }
  3585. }
  3586. });
  3587. trans.fileSelectorContextMenuIsInitialized = true;
  3588. }
  3589. /**
  3590. * Initialize grid's body context menu
  3591. */
  3592. Trans.prototype.gridBodyContextMenu = function() {
  3593. $.contextMenu({
  3594. selector: '.ht_master .htCore tbody, .ht_clone_left .htCore tbody',
  3595. events: {
  3596. preShow : function($target, e) {
  3597. //$(".context-menu-root").trigger("contextmenu:hide")
  3598. var cTarget = $(e.target);
  3599. console.log(cTarget);
  3600. if (cTarget.hasClass("highlight")) {
  3601. console.log("previously hightlighted");
  3602. }
  3603. console.log(arguments);
  3604. },
  3605. show : function($target, e){
  3606. console.log("selection on show : ");
  3607. trans.grid.lastContextMenuCellRange = trans.grid.getSelectedRange();
  3608. },
  3609. hide : function($target, e){
  3610. console.log("reload selection : ");
  3611. if (typeof trans.grid.lastContextMenuCellRange == "undefined") return false;
  3612. trans.grid.selectCells(trans.grid.lastContextMenuCellRange);
  3613. console.log(trans.grid.getSelectedRange());
  3614. }
  3615. },
  3616. build: function($triggerElement, e) {
  3617. var thisCallback = function(key, options) {
  3618. switch (key) {
  3619. case "addComment" :
  3620. var thisCoord= undefined;
  3621. try {
  3622. thisCoord = trans.grid.lastContextMenuCellRange[0]['highlight']
  3623. } catch (error) {
  3624. // do nothing
  3625. }
  3626. trans.editNoteAtCell(thisCoord);
  3627. break;
  3628. case "removeComment" :
  3629. trans.removeNoteAtSelected(trans.grid.lastContextMenuCellRange);
  3630. break;
  3631. default :
  3632. }
  3633. }
  3634. return {
  3635. zIndex:1000,
  3636. callback: thisCallback,
  3637. items: {
  3638. "addComment": {name: t("Add comment"), icon: function(){
  3639. return 'context-menu-icon icon-commenting-o';
  3640. }},
  3641. "removeComment": {name: t("Remove comment"), icon: function(){
  3642. return 'context-menu-icon icon-comment-empty';
  3643. }},
  3644. "selectAll" : {"name" : t("Select all")},
  3645. "invertSelection" : {"name" : t("Invert selection")},
  3646. "sep0": "---------",
  3647. "withSelected": {
  3648. name: "With all",
  3649. items: {
  3650. "batchTranslation": {"name" : t("Batch translation")},
  3651. "wordWrap": {"name" : t("Wrap texts")}
  3652. }
  3653. }
  3654. }
  3655. }
  3656. }
  3657. });
  3658. }
  3659. //================================================================
  3660. //
  3661. // CONTEXT RELATED
  3662. //
  3663. //================================================================
  3664. /**
  3665. * Sanitize query for contexts
  3666. * @param {...String|...Array} - Context
  3667. * @returns {String[]}
  3668. */
  3669. Trans.prototype.evalContextsQuery = function() {
  3670. if (arguments.length == 0) return false;
  3671. var result = [];
  3672. for (var i=0; i<arguments.length; i++) {
  3673. if (typeof arguments[i] == "string") {
  3674. if (arguments[i].length == 0) continue;
  3675. var thisA = arguments[i].split("\n").map(function(input) {
  3676. return common.stripCarriageReturn(input);
  3677. });
  3678. result = result.concat(thisA);
  3679. } else if (Array.isArray(arguments[i])) {
  3680. if (arguments[i].length == 0) continue;
  3681. result = result.concat(arguments[i]);
  3682. }
  3683. }
  3684. return result;
  3685. }
  3686. /**
  3687. * Check whether the a row has the context or not
  3688. * @param {String} file - The file ID
  3689. * @param {Number} row - The row to look for
  3690. * @param {String[]} context - The context to check for
  3691. * @returns {Boolean}
  3692. */
  3693. Trans.prototype.isInContext = function(file, row, context) {
  3694. context = context||[];
  3695. if (context.length == 0) return true;
  3696. if (typeof context == 'string') context = [context];
  3697. if (typeof trans.project.files[file] == 'undefined') return false;
  3698. if (typeof trans.project.files[file].context[row] == 'undefined') return false;
  3699. var thisContextS = trans.project.files[file].context[row];
  3700. if (Array.isArray(thisContextS) == false) thisContextS = [thisContextS];
  3701. if (thisContextS.length < 1) {
  3702. // try to findout on parameters
  3703. if (typeof trans.project.files[file].parameters[row] != 'undefined') {
  3704. thisContextS = [trans.buildContextFromParameter(trans.project.files[file].parameters[row])];
  3705. }
  3706. //continue;
  3707. }
  3708. var contextStr = thisContextS.join("\n");
  3709. for (var i=0; i<context.length; i++) {
  3710. contextStr = contextStr.toLowerCase();
  3711. if (contextStr.indexOf(context[i].toLowerCase()) != -1) return true;
  3712. }
  3713. return false;
  3714. }
  3715. /**
  3716. * Deletes rows by context
  3717. * @param {String} files
  3718. * @param {String[]} contexts
  3719. * @param {Object} options
  3720. * @param {Boolean} whitelist
  3721. */
  3722. Trans.prototype.removeRowByContext = function(files, contexts, options, whitelist) {
  3723. /*
  3724. improved by. Vellithe
  3725. */
  3726. options=options||{};
  3727. options.matchAll = options.matchAll||false;
  3728. var collection = trans.travelContext(files, contexts, {
  3729. onMatch:function(file, row) {
  3730. //trans.removeRow(file, row);
  3731. //console.log("removing "+files+" row "+row);
  3732. },
  3733. matchAll:options.matchAll
  3734. });
  3735. for (var file in collection) {
  3736. for (var row=collection[file].length-1; row>=0; row--) {
  3737. if ((collection[file][row] == true && whitelist !== true) || (collection[file][row] != true && whitelist === true)) {
  3738. console.log("removing "+file+" row "+row + (whitelist === true ? " (Not on whitelist)" : ""));
  3739. trans.removeRow(file, row);
  3740. //trans.project.files[file].data.splice(row, 1);
  3741. }
  3742. }
  3743. }
  3744. trans.refreshGrid();
  3745. }
  3746. /**
  3747. * Generates context's keywords
  3748. * @param {Object} [obj=trans.project] - Trans.project object
  3749. * @param {String[]} [files] - List of the files
  3750. * @param {Object} [options] - Options
  3751. * @returns {Object} Collection of the keywords
  3752. */
  3753. Trans.prototype.collectContextKeyword = function(obj, files, options) {
  3754. files = files||[];
  3755. obj = obj||trans.project;
  3756. if (typeof obj == 'undefined') return false;
  3757. if (typeof files == "string") files = [files];
  3758. if (files.length < 1) { // select all
  3759. for (let file in trans.project.files) {
  3760. files.push(file);
  3761. }
  3762. }
  3763. //console.log(files);
  3764. var collection = {};
  3765. for (let i=0; i<files.length; i++) {
  3766. let file = files[i];
  3767. var thisData = obj.files[file].context;
  3768. for (var contextId=0; contextId<thisData.length; contextId++) {
  3769. if (Array.isArray(thisData[contextId]) == false) continue;
  3770. for (var y=0; y<thisData[contextId].length; y++) {
  3771. var contextString = thisData[contextId][y]||"";
  3772. var contextPart = contextString.split("/");
  3773. for (var x=0; x<contextPart.length; x++) {
  3774. if (isNaN(contextPart[x])) {
  3775. collection[contextPart[x]] = collection[contextPart[x]]||0;
  3776. collection[contextPart[x]] += 1;
  3777. }
  3778. }
  3779. }
  3780. }
  3781. }
  3782. return collection;
  3783. }
  3784. /**
  3785. * Iterate through contexts
  3786. * @param {(String|String[])} files - Selected files
  3787. * @param {(String|String[])} contexts - Context to search for
  3788. * @param {Object} options
  3789. * @param {Function} options.onMatch
  3790. * @param {Function} options.onNotMatch
  3791. * @param {Boolean} options.matchAll
  3792. */
  3793. Trans.prototype.travelContext = function(files, contexts, options) {
  3794. //remove related context
  3795. files = files||[];
  3796. contexts = contexts||[]; // keywords
  3797. options = options||{};
  3798. options.onMatch = options.onMatch||function(){};
  3799. options.onNotMatch = options.onNotMatch||function(){};
  3800. options.matchAll = options.matchAll||false;
  3801. if (typeof files == "string") files = [files];
  3802. if (Array.isArray(contexts) == false) contexts = [contexts];
  3803. if (files.length < 1) { // select all
  3804. for (let file in trans.project.files) {
  3805. files.push(file);
  3806. }
  3807. }
  3808. //console.log(files);
  3809. var collection = {};
  3810. for (let i=0; i<files.length; i++) {
  3811. let file = files[i];
  3812. collection[file] = [];
  3813. for (let rowId=0; rowId<trans.project.files[file].context.length; rowId++) {
  3814. var thisContextS = trans.project.files[file].context[rowId];
  3815. if (Array.isArray(thisContextS) == false) thisContextS = [thisContextS];
  3816. collection[file][rowId] = false;
  3817. if (thisContextS.length < 1) {
  3818. // try to findout on parameters
  3819. if (!trans.project.files[file].parameters[rowId]) continue;
  3820. thisContextS = [trans.buildContextFromParameter(trans.project.files[file].parameters[rowId])];
  3821. //continue;
  3822. }
  3823. for (var y=0; y<thisContextS.length; y++) {
  3824. var thisContext = thisContextS[y];
  3825. //console.log(thisContext);
  3826. for (var x=0; x<contexts.length; x++) {
  3827. //try {
  3828. if (options.matchAll) {
  3829. if (common.matchAllWords(thisContext, contexts[x])) {
  3830. collection[file][rowId] = true;
  3831. }
  3832. } else {
  3833. //console.log("comparing "+thisContext+" with "+contexts[x]);
  3834. if (thisContext.toLowerCase().indexOf(contexts[x].toLowerCase()) >= 0) {
  3835. //console.log("match");
  3836. //matchFound = true;
  3837. //if (options.onMatch.call(trans.project.files[file], file, rowId) === false) return false;
  3838. collection[file][rowId] = true;
  3839. //break;
  3840. } else {
  3841. //if (options.onNotMatch.call(trans.project.files[file], file, rowId) === false) return false;
  3842. }
  3843. }
  3844. //} catch(err) {
  3845. //}
  3846. }
  3847. }
  3848. }
  3849. for (let rowId=0; rowId<collection[file].length; rowId++) {
  3850. if (collection[file][rowId] == true) {
  3851. options.onMatch.call(trans.project.files[file], file, rowId);
  3852. } else {
  3853. options.onNotMatch.call(trans.project.files[file], file, rowId);
  3854. }
  3855. }
  3856. }
  3857. return collection;
  3858. }
  3859. //================================================================
  3860. //
  3861. // UTILITY
  3862. //
  3863. //================================================================
  3864. Trans.prototype.isOrganicCell = function(row, col, file) {
  3865. if (!this.project) return false;
  3866. file ||= this.getSelectedId();
  3867. var cellInfo = this.cellInfo.getCell(file, row, col);
  3868. if (cellInfo?.t == "HU") return true;
  3869. return false;
  3870. }
  3871. Trans.prototype.isVisitedCell = function(row, col, file) {
  3872. if (!this.project) return false;
  3873. file ||= this.getSelectedId();
  3874. return Boolean(this.cellInfo.get("v", file, row, col));
  3875. }
  3876. /**
  3877. * Get data from the file object
  3878. * @param {(Object|String|undefined)} file - File ID or File Object or undefined
  3879. * @returns {String[][]} The array representation of the table
  3880. */
  3881. Trans.prototype.getData = function(file) {
  3882. if (typeof file == 'undefined') return this.getCurrentData();
  3883. if (typeof file == "string") return this.getObjectById(file).data;
  3884. if (typeof file == 'object') {
  3885. if (Array.isArray(file.data)) return file.data;
  3886. }
  3887. console.warn("invalid id or object ", file);
  3888. return [];
  3889. }
  3890. /**
  3891. * Add a new key into a data
  3892. * @param {Any} file - File ID or File Object or undefined
  3893. * @param {String} keyString - keyString
  3894. * @param {String} defaultTranslation - Default translation
  3895. * @returns {Integer} the index of the new inserted data
  3896. */
  3897. Trans.prototype.addRow = function(file, keyString, defaultTranslation) {
  3898. var thisObj
  3899. if (typeof file == "object") {
  3900. thisObj = file;
  3901. } else {
  3902. file = file || this.getSelectedId();
  3903. thisObj = this.getObjectById(file);
  3904. }
  3905. thisObj.indexIds ||= {};
  3906. if (typeof keyString !== "string") return -1;
  3907. if (!keyString) return -1;
  3908. const existingIndex = this.getIndexByKey(thisObj, keyString);
  3909. console.log("Existing index is", existingIndex);
  3910. if (typeof existingIndex !== "undefined") return existingIndex;
  3911. var newRow = Array(trans.colHeaders.length).fill(null);
  3912. newRow[this.keyColumn] = keyString;
  3913. if (defaultTranslation) newRow[1] = defaultTranslation;
  3914. console.log("inserting row:", newRow);
  3915. var theData = trans.getData(thisObj);
  3916. console.log("theData", theData)
  3917. if (empty(theData[theData.length - 1][0])) {
  3918. // overwrite the last empty cell
  3919. let thisIndex = theData.length - 1
  3920. theData[thisIndex] = newRow;
  3921. thisObj.indexIds[keyString] = thisIndex;
  3922. return thisIndex;
  3923. } else {
  3924. var newKey = theData.push(newRow);
  3925. thisObj.indexIds[keyString] = newKey -1;
  3926. return newKey;
  3927. }
  3928. }
  3929. /**
  3930. * Add a new array of data into a file
  3931. * @param {Any} file - File ID or File Object or undefined
  3932. * @param {String[]} data - Array of data to be inserted
  3933. * @returns {Integer} the index of the new inserted data
  3934. */
  3935. Trans.prototype.appendRow = function(file, column=[]) {
  3936. var thisObj
  3937. if (typeof file == "object") {
  3938. thisObj = file;
  3939. } else {
  3940. file = file || this.getSelectedId();
  3941. thisObj = this.getObjectById(file);
  3942. }
  3943. thisObj.indexIds ||= {};
  3944. if (Array.isArray(column) == false) return -1;
  3945. if (column.length < 1) return -1;
  3946. const keyString = column[this.keyColumn];
  3947. if (typeof keyString !== "string") return -1;
  3948. if (!keyString) return -1;
  3949. const existingIndex = this.getIndexByKey(thisObj, keyString);
  3950. console.log("Existing index is", existingIndex);
  3951. if (typeof existingIndex !== "undefined") return existingIndex;
  3952. // ensure the column length is the same
  3953. // trim column to the same length of trans.colHeaders.length
  3954. column.length = trans.colHeaders.length;
  3955. const newRow = common.clone(column);
  3956. var theData = trans.getData(thisObj);
  3957. console.log("theData", theData)
  3958. if (empty(theData[theData.length - 1][0])) {
  3959. // overwrite the last empty cell
  3960. let thisIndex = theData.length - 1
  3961. theData[thisIndex] = newRow;
  3962. thisObj.indexIds[keyString] = thisIndex;
  3963. return thisIndex;
  3964. } else {
  3965. var newKey = theData.push(newRow);
  3966. thisObj.indexIds[keyString] = newKey -1;
  3967. return newKey;
  3968. }
  3969. }
  3970. /**
  3971. * Get indexes of a fileId
  3972. * @param {String|Object} [file=this.getSelectedId()] - File id or file object to be indexed
  3973. * @returns {Object} Key-Value pair of the key text and its row index
  3974. */
  3975. Trans.prototype.getIndexIds = function(file) {
  3976. if (typeof file == 'undefined') file = this.getSelectedId();
  3977. var theObject;
  3978. if (typeof file == "string") {
  3979. theObject = this.getObjectById(file);
  3980. if (!theObject) return {}
  3981. if (!theObject.indexIsBuilt) this.buildIndex(file);
  3982. return theObject.indexIds;
  3983. } else if (typeof file == 'object') {
  3984. theObject = file;
  3985. if (!theObject.indexIsBuilt) theObject = this.buildIndexFromData(theObject);
  3986. return theObject.indexIds;
  3987. }
  3988. console.warn("Error getting Index ID for file:", file);
  3989. return {};
  3990. }
  3991. /**
  3992. * Get row index based on the key string
  3993. * @param {String|Object} file - File ID or File Object to be searched
  3994. * @param {String} keyString - Key string to look for
  3995. * @returns {Number|undefined} - Row id of the keyString if exist. Undefined if not exist.
  3996. */
  3997. Trans.prototype.getIndexByKey = function(file, keyString) {
  3998. return this.getIndexIds(file)[keyString];
  3999. }
  4000. /**
  4001. * Check whether all available files are checked
  4002. * @returns {Boolean} True if all files are checked
  4003. */
  4004. Trans.prototype.isAllSelected = function() {
  4005. if (trans.getCheckedFiles().length == Object.keys(trans.project.files).length) return true;
  4006. return false;
  4007. }
  4008. /**
  4009. * Get the current active translator engine's ID
  4010. * @returns {String} Active translator ID
  4011. */
  4012. Trans.prototype.getActiveTranslator = function() {
  4013. if (!trans.project) return sys.config?.translator;
  4014. trans.project.options = trans?.project.options || {};
  4015. return trans.project?.options?.translator || sys.config.translator;
  4016. }
  4017. /**
  4018. * Append text to the common reference
  4019. * @param {String} text - Key text to append
  4020. * @returns {Boolean} Return false if failed
  4021. */
  4022. Trans.prototype.appendTextToReference = function(text) {
  4023. if (!this.isInProject()) return false;
  4024. if (typeof text !== 'string') return false;
  4025. if (!text.trim()) return trans.alert("Cannot add empty text to reference. Please try again with a text selected, or use <b>CTRL+SHIFT+D</b> to add the selected row into reference.");
  4026. if (trans.isKeyExistOn(text, "Common Reference")) return trans.alert("Unable to add <b>"+text+"</b>. That value already exist on Common Reference!");
  4027. var ref= trans.project.files["Common Reference"];
  4028. var lastKey = ref.data.length-1;
  4029. if (Boolean(ref.data[lastKey][0]) == false) {
  4030. console.log("inserting to ref.data[lastKey][0]");
  4031. ref.data[lastKey][0] = text;
  4032. ref.indexIds[text] = lastKey;
  4033. } else {
  4034. console.log("append new data");
  4035. var newData = new Array(trans.colHeaders.length);
  4036. newData = newData.fill(null);
  4037. newData[0] = text;
  4038. ref.data.push(newData);
  4039. ref.indexIds[text] = ref.data.length-1;
  4040. }
  4041. trans.alert("<b>"+text+"</b> "+t("added to reference table!"));
  4042. return true;
  4043. }
  4044. Trans.prototype.appendSelectedRowToReference = function() {
  4045. const selectedRow = common.gridSelectedRows();
  4046. if (!this.isInProject()) return;
  4047. if (!selectedRow?.length) return this.alert("No row selected.");
  4048. if (!this.getObjectById("Common Reference")) return this.alert("This project don't have <b>Common Reference</b> file. Please create one first.");
  4049. let insertedRow = 0;
  4050. for (let i=0; i<selectedRow.length; i++) {
  4051. if (this.appendRow("Common Reference", this.getData()[i]) > -1) {
  4052. insertedRow++;
  4053. };
  4054. }
  4055. this.alert(insertedRow + " row(s) added to Common Reference.");
  4056. return true;
  4057. }
  4058. /**
  4059. * Word wrap a file object
  4060. * @param {String[]} [files=this.getAllFiles()] - List of files to be processed
  4061. * @param {Number} [col=1] - Column ID to be processed
  4062. * @param {Number} [targetCol=col+1] - Column of the processed text will put into
  4063. * @param {Object} [options]
  4064. * @param {Number} [options.maxLength=41] - Maximum length of the line
  4065. * @param {String[]} [options.context] - Context filter. Only the rows that has this context will be processed
  4066. * @param {Function} [options.onDone] - Triggered when the process is completed
  4067. */
  4068. Trans.prototype.wordWrapFiles = function(files, col, targetCol, options) {
  4069. files = files||[];
  4070. if (typeof files == 'string') files = [files];
  4071. if (files.length == 0 ) files = this.getAllFiles();
  4072. //console.log(arguments);
  4073. //return true;
  4074. col = col||1;
  4075. targetCol = targetCol||col+1;
  4076. if (targetCol == 0) return trans.alert(t("Can not modify Column 0"));
  4077. options = options||{};
  4078. options.maxLength = options.maxLength||41; // default with picture, without picture is 50
  4079. options.onDone = options.onDone||function() {};
  4080. options.context = options.context||[] // context filter
  4081. for (var id=0; id<files.length; id++) {
  4082. var file = files[id];
  4083. console.log("Wordwrapping file : "+file);
  4084. if (typeof trans.project.files[file] == 'undefined') continue;
  4085. options.lineBreak = options.lineBreak||trans.project.files[file].lineBreak||"\n";
  4086. var thisData = trans.project.files[file].data;
  4087. //console.log(thisData);
  4088. for (var row=0; row<thisData.length; row++) {
  4089. if (!trans.isInContext(file, row, options.context)) continue;
  4090. if (typeof thisData[row][col] !== 'string') {
  4091. thisData[row][targetCol] = thisData[row][col];
  4092. }
  4093. thisData[row][targetCol] = common.wordwrapLocale(thisData[row][col], options.maxLength, this.getTl(), options.lineBreak);
  4094. }
  4095. }
  4096. options.onDone.call(trans);
  4097. }
  4098. /**
  4099. * Fill empty lines from other column
  4100. * @param {String|String[]} files - File ID or list of file ID
  4101. * @param {Number[]} rows - Row ID or list of row ID
  4102. * @param {Number} targetCol - Target column
  4103. * @param {Number} sourceCol
  4104. * @param {Object} options
  4105. * @param {Object} [options.project=trans.project]
  4106. * @param {Object} [options.keyColumn=0]
  4107. * @param {Function} [options.lineFilter]
  4108. * @param {Boolean} [options.fromKeyOnly=false]
  4109. * @param {String[]} [options.filterTag]
  4110. * @param {Boolean} [options.overwrite=false]
  4111. */
  4112. Trans.prototype.fillEmptyLine = function(files, rows, targetCol, sourceCol, options) {
  4113. /*
  4114. Integer targetCol
  4115. Integer sourceCol
  4116. */
  4117. // if targetCol is undefined, than the right most row with existed translation will be picked
  4118. files = files||[];
  4119. if (typeof files == 'string') files = [files];
  4120. options = options||{};
  4121. options.project = options.project||trans.project;
  4122. options.keyColumn = options.keyColumn||0;
  4123. options.lineFilter = options.lineFilter|| function() {return true};
  4124. options.fromKeyOnly = options.fromKeyOnly || false; // fill from key column only
  4125. options.filterTag = options.filterTag || [];
  4126. options.overwrite = options.overwrite || false;
  4127. if (options.fromKeyOnly) {
  4128. console.warn("collecting data from key only");
  4129. options.sourceCol = sourceCol||options.keyColumn;
  4130. }
  4131. rows = rows||[];
  4132. if (typeof rows == 'number') rows = [rows];
  4133. if (files.length == 0) files = trans.getAllFiles();
  4134. console.log(files);
  4135. for (var index=0; index<files.length; index++) {
  4136. let file = files[index];
  4137. //console.log(file);
  4138. //var thisLineBreak = options.project.files[file].thisLineBreak||"\n";
  4139. if (rows.length > 0) {
  4140. // do nothing
  4141. } else { // all row
  4142. var thisData = options.project.files[file].data;
  4143. for (var row=0; row<thisData.length; row++) {
  4144. if (options.filterTagMode == "blacklist") {
  4145. if (this.hasTags(options.filterTag, row, file)) continue;
  4146. } else if (options.filterTagMode == "whitelist") {
  4147. if (!this.hasTags(options.filterTag, row, file)) continue;
  4148. }
  4149. if (typeof targetCol == 'undefined') {
  4150. targetCol = trans.getTranslationColFromRow(thisData[row]);
  4151. if (targetCol == null) continue; // no translation exist
  4152. }
  4153. if (options.overwrite == false) {
  4154. if (thisData[row][targetCol]) continue;
  4155. }
  4156. /*
  4157. if (typeof sourceCol == 'undefined') {
  4158. sourceCol = trans.getTranslationColFromRow(thisData[row], targetCol); // get translation except targetCol
  4159. if (sourceCol == null) continue; // no source found
  4160. }
  4161. */
  4162. options.project.files[file].data[row][targetCol] = trans.getTranslationByLine(thisData[row], options.keyColumn, {
  4163. includeIndex :true,
  4164. priorityCol :targetCol,
  4165. onBeforeLineAdd :options.lineFilter,
  4166. sourceCol :options.sourceCol//column to check, undefined means all
  4167. });
  4168. }
  4169. }
  4170. }
  4171. }
  4172. /**
  4173. * remove whitespace from translation
  4174. * @param {(String|String[])} files - File id(s) to process
  4175. * @param {(Number|Number[])} columns - column to process
  4176. * @param {Object} options
  4177. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4178. */
  4179. Trans.prototype.trimTranslation = function(files, columns, options) {
  4180. // remove whitespace from translation
  4181. if (!trans.project) return false;
  4182. files = files||trans.getSelectedId();
  4183. options = options||{};
  4184. options.refreshGrid = options.refreshGrid||false;
  4185. if (Array.isArray(files) == false) files = [files];
  4186. if (Array.isArray(columns) == false) columns = [columns];
  4187. for (var i=0; i<files.length; i++) {
  4188. var file = files[i];
  4189. //console.log("handling "+file);
  4190. var thisData = trans.project.files[file].data;
  4191. //var thisLineBreak = trans.project.files[file].lineBreak||"\n";
  4192. var originalLineBreak = trans.project.files[file].lineBreak||"\n";
  4193. var thisLineBreak = "\n";
  4194. for (var row=0; row<thisData.length; row++) {
  4195. //console.log("handling row "+row);
  4196. for (var colID in columns) {
  4197. var col = columns[colID];
  4198. //console.log("handling col "+col);
  4199. //console.log(trans.project.files[file].data[row][col]);
  4200. if (col < 1) continue;
  4201. if (typeof trans.project.files[file].data[row][col] !== 'string') continue;
  4202. var lines = trans.project.files[file].data[row][col].split(thisLineBreak);
  4203. var newLines = lines.map(function(thisVal) {
  4204. //console.log(thisVal.trim());
  4205. return thisVal.trim();
  4206. });
  4207. trans.project.files[file].data[row][col] = newLines.join(originalLineBreak);
  4208. }
  4209. }
  4210. }
  4211. //if (options.refreshGrid) {
  4212. trans.refreshGrid();
  4213. //}
  4214. }
  4215. /**
  4216. * Copy left padding of the key texts into translations
  4217. * @param {(String|String[])} files - File id(s) to process
  4218. * @param {(Number|Number[])} columns - column to process
  4219. * @param {Object} options
  4220. * @param {Number} [options.keyId=0] - The index of the key column
  4221. * @param {Boolean} options.includeInitialWhitespace
  4222. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4223. */
  4224. Trans.prototype.paddingTranslation = function(files, columns, options) {
  4225. // Copy left padding from keys to translations
  4226. if (!trans.project) return false;
  4227. files = files||trans.getSelectedId();
  4228. options = options||{};
  4229. options.keyId = options.keyId||0;
  4230. options.includeInitialWhitespace = options.includeInitialWhitespace||false;
  4231. options.refreshGrid = options.refreshGrid||false;
  4232. if (Array.isArray(files) == false) files = [files];
  4233. if (Array.isArray(columns) == false) columns = [columns];
  4234. //var whiteSpaces = /^[ \s\u00A0\f\n\r\t\v\u00A0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u2028\u2029\u202f\u205f\u3000]+/g
  4235. //var whiteSpaces = /^[\r\n\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff\u0009\u200b\u180e\u2060]+/g;
  4236. var whiteSpaces = /^[\s\u0009\u200b\u180e\u2060]+/g
  4237. for (var i=0; i<files.length; i++) {
  4238. var file = files[i];
  4239. var thisData = trans.project.files[file].data;
  4240. var thisLineBreak = trans.project.files[file].lineBreak||"\n";
  4241. for (var row=0; row<thisData.length; row++) {
  4242. if (typeof trans.project.files[file].data[row][options.keyId] !== 'string') continue;
  4243. var keys = trans.project.files[file].data[row][options.keyId].split(thisLineBreak);
  4244. var leftWhiteSpaces = [];
  4245. for (var keysID=0; keysID<keys.length; keysID++) {
  4246. var thisLeftWS = keys[keysID].match(whiteSpaces);
  4247. if (Boolean(thisLeftWS) == false) thisLeftWS = "";
  4248. leftWhiteSpaces.push(thisLeftWS);
  4249. }
  4250. for (var colID in columns) {
  4251. var col = columns[colID];
  4252. if (col < 1) continue;
  4253. if (typeof trans.project.files[file].data[row][col] !== 'string') continue;
  4254. var lines = trans.project.files[file].data[row][col].split(thisLineBreak);
  4255. var newLines = [];
  4256. for (var linePartId=0; linePartId<lines.length; linePartId++) {
  4257. var thisWhitespace = leftWhiteSpaces[linePartId]||"";
  4258. if (options.includeInitialWhitespace) {
  4259. newLines.push(thisWhitespace+lines[linePartId]);
  4260. } else {
  4261. newLines.push(thisWhitespace+lines[linePartId].trim());
  4262. }
  4263. }
  4264. trans.project.files[file].data[row][col] = newLines.join(thisLineBreak);
  4265. }
  4266. }
  4267. }
  4268. //if (options.refreshGrid) {
  4269. trans.refreshGrid();
  4270. //}
  4271. }
  4272. /**
  4273. * Clear translations from selected files
  4274. * @param {(String|String[])} files - File id(s)
  4275. * @param {Object} options
  4276. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4277. */
  4278. Trans.prototype.removeAllTranslation = function(files, options) {
  4279. if (!trans.project) return false;
  4280. files = files||trans.getSelectedId();
  4281. options = options||{};
  4282. options.refreshGrid = options.refreshGrid||false;
  4283. if (Array.isArray(files) == false) files = [files];
  4284. for (var i=0; i<files.length; i++) {
  4285. var file = files[i];
  4286. var thisData = trans.project.files[file].data;
  4287. for (var row=0; row<thisData.length; row++) {
  4288. for (var col=1; col<thisData[row].length; col++) {
  4289. trans.project.files[file].data[row][col] = null;
  4290. }
  4291. }
  4292. }
  4293. /**
  4294. * Triggered when all all translation are removed
  4295. * @event Trans#removeAllTranslation
  4296. * @param {Object} Options
  4297. * @param {String[]} Options.files - List of the file ids
  4298. * @param {Object} Options.options - Options
  4299. */
  4300. this.trigger("removeAllTranslation", {files:files, options:options});
  4301. if (options.refreshGrid) {
  4302. trans.refreshGrid();
  4303. }
  4304. }
  4305. /**
  4306. * Delete files
  4307. * @param {(String|String[])} files - Files to be deleted
  4308. * @param {Object} options
  4309. * @returns {Boolean} True on success
  4310. */
  4311. Trans.prototype.deleteFile = function(files, options) {
  4312. if (!trans.project) return false;
  4313. files = files||trans.getSelectedId();
  4314. options = options||{};
  4315. if (Array.isArray(files) == false) files = [files];
  4316. if (files.length < 1) return true;
  4317. for (var i=0; i<files.length; i++) {
  4318. // unselect if selected
  4319. var file = files[i];
  4320. if (trans.project.files[file].type == 'reference') {
  4321. alert(t("Unable to delete table : ")+file);
  4322. continue;
  4323. }
  4324. if (file == trans.getSelectedId()) {
  4325. ui.disableGrid(true);
  4326. }
  4327. var bak = JSON.parse(JSON.stringify(trans.project.files[file]));
  4328. trans.project.trash = trans.project.trash||{};
  4329. trans.project.trash[file] = bak;
  4330. $(".panel-left .fileList [data-id="+common.escapeSelector(file)+"]").remove();
  4331. delete trans.project.files[file];
  4332. }
  4333. ui.fileList.reIndex();
  4334. this.trigger("afterDeleteFile", [files]);
  4335. }
  4336. /**
  4337. * Remove one or more files from staging directory
  4338. * This function is useful for cleaning up staging files for example after removing the project's object
  4339. * @async
  4340. * @param {String[]} files - List of files to be removed
  4341. * @since 4.4.4
  4342. */
  4343. Trans.prototype.stagingFilesRemove = async function(files) {
  4344. if (!Array.isArray(files)) files = [files];
  4345. var stagingPath = this.getStagingPath();
  4346. if (!stagingPath) return [];
  4347. var result = []
  4348. for (var i in files) {
  4349. var fileToRemove = nwPath.join(stagingPath, "data", files[i]);
  4350. console.log("Removing", fileToRemove);
  4351. if (!await common.isFileAsync(fileToRemove)) console.log("Not found:", fileToRemove);
  4352. result.push(await common.unlink(files[i]));
  4353. }
  4354. return result;
  4355. }
  4356. /**
  4357. * Removes row
  4358. * @param {String} file - File to be processed
  4359. * @param {(Number|Number[])} rows - Rows to be removed
  4360. * @param {Object} options
  4361. * @param {Boolean} options.permanent - will put into the temporary bucket when false
  4362. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4363. */
  4364. Trans.prototype.removeRow = function(file, rows, options) {
  4365. console.log("removing row : ", arguments);
  4366. if (typeof file == 'undefined') return false;
  4367. if (typeof rows == 'undefined') return false;
  4368. if (rows === 0) rows = [0];
  4369. rows = rows||[];
  4370. options = options||{};
  4371. if (Array.isArray(rows) == false) rows = [rows];
  4372. options.permanent = options.permanent||false;
  4373. options.refreshGrid = options.refreshGrid||false;
  4374. // make the array unique, so one row can be only removed once
  4375. rows = common.arrayUnique(rows);
  4376. // sort array descending! this is important!
  4377. rows.sort(function(a, b) {
  4378. return b - a;
  4379. });
  4380. console.log("Removing rows > should be ordered descendingly:", rows);
  4381. for (var i=0; i<rows.length; i++) {
  4382. var thisRow = rows[i];
  4383. if (typeof trans.project.files[file].data[thisRow] == 'undefined') continue;
  4384. trans.project.files[file].data.splice(thisRow, 1);
  4385. if (trans.project.files[file].parameters) trans.project.files[file].parameters.splice(thisRow, 1);
  4386. if (trans.project.files[file].context) trans.project.files[file].context.splice(thisRow, 1);
  4387. if (trans.project.files[file].tags) trans.project.files[file].tags.splice(thisRow, 1);
  4388. // adjust cellInfo
  4389. this.cellInfo.deleteRow(file, thisRow);
  4390. // adjust comment
  4391. var comments = this.getObjectById(file).comments;
  4392. if (empty(comments)) continue;
  4393. if (Array.isArray(comments)) {
  4394. comments.splice(thisRow, 1);
  4395. } else {
  4396. delete comments[thisRow];
  4397. }
  4398. }
  4399. if (rows.length > 0) trans.project.files[file].indexIsBuilt = false;
  4400. /**
  4401. * Triggered after removing rows
  4402. * @event Trans#afterRemoveRow
  4403. * @param {Object} options
  4404. * @param {String} options.file - file id
  4405. * @param {Number[]} options.rows - List of rows
  4406. * @param {Object} options.options
  4407. */
  4408. this.trigger("afterRemoveRow", {file:file, rows:rows, options:options});
  4409. if (options.refreshGrid) {
  4410. trans.refreshGrid();
  4411. }
  4412. }
  4413. /**
  4414. * Clear translations from rows
  4415. * @since 4.11.30
  4416. * @param {Object|String} file - File ID or file object
  4417. * @param {Number|Number[]} rows - A row or array of rows.
  4418. * @param {Object} [options] - Options
  4419. * @returns {Number} - Affected row[s]
  4420. */
  4421. Trans.prototype.clearRow = function(file, rows, options={}) {
  4422. if (typeof file == "string") file = trans.getObjectById(file);
  4423. if (!file) return;
  4424. if (!(typeof file == "object" && Array.isArray(file.data))) return console.warn("Invalid argument 1");
  4425. if (!Array.isArray(rows)) rows = [rows];
  4426. options ||= {};
  4427. var affectedRows = 0;
  4428. for (var rowId=0; rowId<rows.length; rowId++) {
  4429. var row = file.data[rows[rowId]];
  4430. for (var colId=0; colId<row.length; colId++) {
  4431. if (colId == this.keyColumn) continue;
  4432. row[colId] = "";
  4433. affectedRows++;
  4434. }
  4435. }
  4436. return affectedRows;
  4437. }
  4438. /**
  4439. * Removes a column
  4440. * This will affect the entire files
  4441. * @param {Number} column - Column to remove
  4442. * @param {Object} options
  4443. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4444. */
  4445. Trans.prototype.removeColumn = function(column, options) {
  4446. if (column === 0) return trans.alert(t("Can not remove key column!"));
  4447. options = options||{};
  4448. options.permanent = options.permanent||false;
  4449. options.refreshGrid = options.refreshGrid||false;
  4450. if(typeof trans.project == "undefined") return trans.alert(t("Please open or create a project first"));
  4451. for (var file in trans.project.files) {
  4452. if(Array.isArray(trans.project.files[file].data) == false) continue;
  4453. if(trans.project.files[file].data.length == 0) continue;
  4454. for (var row=0; row< trans.project.files[file].data.length; row++) {
  4455. trans.project.files[file].data[row].splice(column, 1);
  4456. // adjust cellInfo
  4457. this.cellInfo.deleteCell(file, row, column);
  4458. }
  4459. }
  4460. trans.colHeaders.splice(column, 1);
  4461. trans.columns.splice(column, 1);
  4462. if (options.refreshGrid) {
  4463. trans.refreshGrid();
  4464. }
  4465. }
  4466. /**
  4467. * Rename a column
  4468. * @param {Number} column
  4469. * @param {String} newName
  4470. * @param {Object} options
  4471. * @param {Boolean} options.refreshGrid - Refresh the current grid after process is completed
  4472. */
  4473. Trans.prototype.renameColumn = function(column, newName, options) {
  4474. if (column === 0) return trans.alert(t("Can not set column name to blank!"));
  4475. options = options||{};
  4476. options.refreshGrid = options.refreshGrid||false;
  4477. if (typeof trans.colHeaders[column] == 'undefined') return false;
  4478. trans.colHeaders[column] = newName;
  4479. if (options.refreshGrid) {
  4480. trans.refreshGrid();
  4481. }
  4482. }
  4483. /**
  4484. * Check whether a row has multiple context
  4485. * @param {Number} row - Row to check
  4486. * @param {Object} [obj=trans.getSelectedObject()] - Active object
  4487. * @returns {Boolean} True if the row has more than one context
  4488. * @since 4.10.18
  4489. */
  4490. Trans.prototype.rowHasMultipleContext = function(row, obj) {
  4491. obj = obj || this.getSelectedObject();
  4492. if (!row) false;
  4493. if (!obj.context) return false;
  4494. if (!obj.context[row]) return false;
  4495. if (obj.context[row].length <= 1) return false;
  4496. return true;
  4497. }
  4498. /**
  4499. * Check whether the row is translated or not
  4500. * @param {Number} row - Index of the row
  4501. * @param {String[][]} data - Two dimensional array represents the table
  4502. * @returns {Boolean} True if the row has translation
  4503. */
  4504. Trans.prototype.isTranslatedRow = function(row, data) {
  4505. data = data||trans.data;
  4506. for (var col=1; col < data[row].length; col++) {
  4507. var thisCell = data[row][col]||"";
  4508. if (thisCell.length > 0) return true;
  4509. }
  4510. return false;
  4511. }
  4512. /**
  4513. * Count how many cells are translated on the selected row
  4514. * Row index are not counted
  4515. * @param {Number} row - Row index
  4516. * @param {String[][]} data - Two dimensional array represents the table
  4517. * @returns {Number} The number of the translated cells
  4518. */
  4519. Trans.prototype.countFilledCol = function(row, data) {
  4520. // exclude col index 0
  4521. data = data||trans.data;
  4522. var result = 0;
  4523. for (var col=1; col < data[row].length; col++) {
  4524. var thisCell = data[row][col]||"";
  4525. if (thisCell.length > 0) result++;
  4526. }
  4527. return result;
  4528. }
  4529. /**
  4530. * Retrieve the best translation in an array with Translator++'s rule
  4531. * The rightmost cell got the priority
  4532. * @param {String[]} row - Array of text
  4533. * @param {Number} [keyColumn=0] - Index of the key column
  4534. * @returns {String}
  4535. */
  4536. Trans.prototype.getTranslationFromRow = function(row, keyColumn, skipRows=[]) {
  4537. // retrieve best translation in an array
  4538. //console.log("Get translation from row", arguments);
  4539. skipRows ||= []
  4540. if (Array.isArray(row) == false) return false;
  4541. keyColumn = keyColumn||0;
  4542. if (keyColumn == 0) {
  4543. for (let n=row.length; n>0; n--) {
  4544. if (skipRows.includes(n)) continue;
  4545. if (row[n]) {
  4546. return row[n];
  4547. }
  4548. }
  4549. } else {
  4550. for (let n=row.length; n>=0; n--) {
  4551. if (n == keyColumn) continue;
  4552. if (skipRows.includes(n)) continue;
  4553. if (row[n]) {
  4554. return row[n];
  4555. }
  4556. }
  4557. }
  4558. return null;
  4559. }
  4560. /**
  4561. * Retrieve the best translation in an array with Translator++'s rule
  4562. * The rightmost cell got the priority
  4563. * @param {String[]} row - Array of text
  4564. * @param {Number} [keyColumn=0] - Index of the key column
  4565. * @returns {Number} Cell index of the translation
  4566. */
  4567. Trans.prototype.getTranslationColFromRow = function(row, keyColumn) {
  4568. if (Array.isArray(row) == false) return false;
  4569. keyColumn = keyColumn||0;
  4570. if (keyColumn == 0) {
  4571. for (let n=row.length; n>keyColumn; n--) {
  4572. if (row[n]) {
  4573. return n;
  4574. }
  4575. }
  4576. } else {
  4577. for (let n=row.length; n>=0; n--) {
  4578. if (n == keyColumn) continue;
  4579. if (row[n]) {
  4580. return n;
  4581. }
  4582. }
  4583. }
  4584. return null;
  4585. }
  4586. /**
  4587. * Retrieve the best translation in an array with Translator++'s rule
  4588. * The rightmost cell got the priority
  4589. * Used in line-by-line translation
  4590. * @param {String[]} row - Array of text
  4591. * @param {Number} [keyColumn=0] - Index of the key column
  4592. * @param {Object} [options]
  4593. * @param {Object} [options.includeIndex]
  4594. * @param {String} [options.lineBreak=\n] - Line break character
  4595. * @param {Function} [options.onBeforeLineAdd]
  4596. * @returns {String} The best translation
  4597. */
  4598. Trans.prototype.getTranslationByLine = function(row, keyColumn, options) {
  4599. // get line by line best translation
  4600. if (Array.isArray(row) == false) return false;
  4601. //console.log(arguments);
  4602. keyColumn = 0;
  4603. options = options||{};
  4604. options.includeIndex = options.includeIndex||false;
  4605. options.lineBreak = options.lineBreak||"\n";
  4606. options.onBeforeLineAdd = options.onBeforeLineAdd||function() {return true};
  4607. //options.priorityCol = options.priorityCol||undefined;
  4608. //options.sourceCol = options.sourceCol||undefined;
  4609. var resultArray = [];
  4610. if (typeof options.sourceCol != 'undefined') {
  4611. let thisCell = row[options.sourceCol]||"";
  4612. let thisCellPart = thisCell.split("\n").map(function(input){
  4613. return common.stripCarriageReturn(input);
  4614. });
  4615. for (let part=0; part<thisCellPart.length; part++) {
  4616. if (Boolean(thisCellPart[part]) == false) continue;
  4617. if (!options.onBeforeLineAdd(thisCellPart[part])) continue;
  4618. resultArray[part] = thisCellPart[part];
  4619. }
  4620. } else {
  4621. for (let col=0; col<row.length; col++) {
  4622. if (col == keyColumn) continue;
  4623. if (typeof options.priorityCol !=='undefined') {
  4624. if (col == options.priorityCol) continue;
  4625. }
  4626. let thisCell = row[col]||"";
  4627. let thisCellPart = thisCell.split("\n").map(function(input){
  4628. return common.stripCarriageReturn(input);
  4629. });
  4630. for (let part=0; part<thisCellPart.length; part++) {
  4631. if (Boolean(thisCellPart[part]) == false) continue;
  4632. if (!options.onBeforeLineAdd(thisCellPart[part])) continue;
  4633. resultArray[part] = thisCellPart[part];
  4634. }
  4635. }
  4636. }
  4637. if (options.includeIndex) {
  4638. let thisCell = row[keyColumn]||"";
  4639. let thisCellPart = thisCell.split("\n").map(function(input){
  4640. return common.stripCarriageReturn(input);
  4641. });
  4642. for (let part=0; part<thisCellPart.length; part++) {
  4643. if (Boolean(thisCellPart[part]) == false) continue;
  4644. if (!options.onBeforeLineAdd(thisCellPart[part])) continue;
  4645. resultArray[part] = thisCellPart[part];
  4646. }
  4647. }
  4648. if (typeof options.priorityCol !== 'undefined') {
  4649. var thisCell = row[options.priorityCol]||"";
  4650. var thisCellPart = thisCell.split("\n").map(function(input){
  4651. return common.stripCarriageReturn(input);
  4652. });
  4653. for (var part=0; part<thisCellPart.length; part++) {
  4654. if (Boolean(thisCellPart[part]) == false) continue;
  4655. //if (!options.onBeforeLineAdd(thisCellPart[part])) continue;
  4656. resultArray[part] = thisCellPart[part];
  4657. }
  4658. }
  4659. return resultArray.join(options.lineBreak);
  4660. }
  4661. /**
  4662. * Generates translation pair
  4663. * @param {String[][]} data - Two dimensional array represents the table
  4664. * @param {Number} translationCol - Column index of the preferred translation
  4665. * @returns {Object} - Key-value pair of translation
  4666. */
  4667. Trans.prototype.generateTranslationPair = function(data, translationCol) {
  4668. translationCol = translationCol || 0;
  4669. if (Array.isArray(data) == false) return {};
  4670. var result = {};
  4671. for (var rowId=0; rowId<data.length; rowId++) {
  4672. if (Boolean(data[rowId][0]) == false) continue;
  4673. var translation = trans.getTranslationFromRow(data[rowId], translationCol);
  4674. if (translation == null) continue;
  4675. result[data[rowId][0]] = translation;
  4676. }
  4677. return result;
  4678. }
  4679. Trans.prototype.getProgressColumnIndices = function() {
  4680. const setting = sys.getConfig("progressColumnIndices");
  4681. if (!setting) return;
  4682. let rowList = setting.replaceAll(" ", "").split(",");
  4683. // ensure rowList is an array of number
  4684. rowList = rowList.map(function(row) {
  4685. return parseInt(row);
  4686. });
  4687. // make the array unique
  4688. return common.arrayUnique(rowList);
  4689. }
  4690. /**
  4691. * Count how many rows are translated
  4692. * @param {(String|String[])} file - The file ID(s) to process
  4693. * @returns {TranslationStats}
  4694. */
  4695. Trans.prototype.countTranslated = function(file) {
  4696. file = file||[];
  4697. if (typeof file == 'string') {
  4698. file=[file];
  4699. }
  4700. if (file.length == 0) file = this.getAllFiles()
  4701. const progressColumnIndices = this.getProgressColumnIndices();
  4702. console.log("Progress column indices", progressColumnIndices);
  4703. var result = {};
  4704. for (var i=0; i<file.length; i++) {
  4705. var thisData = this.project.files[file[i]].data;
  4706. /**
  4707. * @typedef {Object} TranslationStats
  4708. * @property {number} translated - How many rows are translated
  4709. * @property {number} length - The number rows in total
  4710. * @property {number} percent - How many rows are translated
  4711. */
  4712. result[file[i]] = {
  4713. translated :0,
  4714. length :0,
  4715. percent :100
  4716. };
  4717. for (var row=0; row<thisData.length; row++) {
  4718. if (Boolean(thisData[row][this.keyColumn]) == false) continue;
  4719. thisData[row][this.keyColumn] = thisData[row][this.keyColumn]||"";
  4720. // stringify
  4721. thisData[row][this.keyColumn] = thisData[row][this.keyColumn]+""
  4722. if (this.lineByLineMode) {
  4723. // DO NOT USE, evaluating by lines instead of rows
  4724. try {
  4725. var thisKeyCount = thisData[row][0].split("\n").length;
  4726. } catch (e) {
  4727. console.error("Error when trying to split key string ", thisData[row][0]);
  4728. throw(e)
  4729. }
  4730. for (var col=1; col<thisData[row].length; col++) {
  4731. if (Boolean(thisData[row][col]) == false) continue;
  4732. // converts non string cell into string
  4733. if (typeof(thisData[row][col]) !== 'string') thisData[row][col] = thisData[row][col]+'';
  4734. thisData[row][col] = thisData[row][col]||"";
  4735. var thisColCount = thisData[row][col].split("\n").length;
  4736. if (thisColCount>=thisKeyCount) {
  4737. result[file[i]].translated ++;
  4738. break;
  4739. }
  4740. }
  4741. } else {
  4742. if (this.rowHasTranslation(thisData[row], this.keyColumn, progressColumnIndices)) result[file[i]].translated++;
  4743. }
  4744. result[file[i]].length++;
  4745. }
  4746. if (result[file[i]].length > 0) result[file[i]].percent = result[file[i]].translated/result[file[i]].length*100;
  4747. if (result[file[i]].percent > 100) result[file[i]].percent = 100;
  4748. if (result[file[i]].percent < 0) result[file[i]].percent = 0;
  4749. this.project.files[file[i]].progress = result[file[i]];
  4750. }
  4751. return result;
  4752. }
  4753. /**
  4754. * Resets the index of all files
  4755. */
  4756. Trans.prototype.resetIndex = function(hardReset) {
  4757. hardReset = hardReset || false;
  4758. for (var id in this.project.files) {
  4759. this.project.files[id].indexIsBuilt = false;
  4760. }
  4761. }
  4762. /**
  4763. * building indexes from trans data for faster search KEY by ID
  4764. * This function will cache the result in default index's cache location which is: `trans.project.files[fileId].indexID`
  4765. * @param {String} fileId - The file ID to process
  4766. * @param {Boolean} [rebuild=false] - Force to rebuld index if index is already exist
  4767. * @param {Number} [keyColumn=0] - Key column of the table
  4768. * @returns {Object} Key-value pair of the index
  4769. */
  4770. Trans.prototype.buildIndex = function(fileId, rebuild, keyColumn) {
  4771. fileId = fileId||trans.getSelectedId();
  4772. keyColumn = keyColumn || trans.keyColumn || 0;
  4773. if (fileId) {
  4774. var currentObject = trans.project.files[fileId];
  4775. if (currentObject.indexIsBuilt && rebuild !== true) return currentObject.indexIds;
  4776. var result = {};
  4777. for (let i=0; i<currentObject.data.length; i++) {
  4778. //console.log("registering : "+currentObject.data[i][0]);
  4779. if (typeof currentObject.data[i] == 'undefined') continue;
  4780. if (currentObject.data[i][keyColumn] == null || currentObject.data[i][keyColumn] == '' || typeof currentObject.data[i][keyColumn] == 'undefined') continue;
  4781. result[currentObject.data[i][keyColumn]] = i;
  4782. }
  4783. currentObject.indexIds = result;
  4784. currentObject.indexIsBuilt = true;
  4785. if (fileId == trans.getSelectedId()) {
  4786. trans.indexIds = currentObject.indexIds;
  4787. trans.indexIsBuilt = currentObject.indexIsBuilt;
  4788. }
  4789. return result;
  4790. } else {
  4791. if (trans.indexIsBuilt && rebuild !== true) return trans.indexIds;
  4792. for (let i=0; i<trans.data.length; i++) {
  4793. if (typeof trans.data[i] == 'undefined') continue;
  4794. if (trans.data[i][keyColumn] == null || trans.data[i][keyColumn] == '' || typeof trans.data[i][keyColumn] == 'undefined') continue;
  4795. trans.indexIds[trans.data[i][keyColumn]] = i;
  4796. }
  4797. trans.indexIsBuilt = true;
  4798. return trans.indexIds;
  4799. }
  4800. }
  4801. /**
  4802. * Build indexes from multiple files
  4803. * @param {String[]} files - The file ID to process
  4804. * @param {Boolean} lineByLine - Whether the index processed with line-by-line algorithm or no. Default row-by-row algorithm
  4805. * @param {Object} options
  4806. * @returns {Object} Key-Object of the value pair of the index
  4807. * @since 4.7.15
  4808. */
  4809. Trans.prototype.buildIndexes = function(files, lineByLine=false, options={}) {
  4810. options ||= {};
  4811. options.customFilter;
  4812. options.indexId ||= "";
  4813. //todo : custom index
  4814. this.customIndexes ||= {};
  4815. if (typeof options.customFilter == "function") {
  4816. console.log("Generating custom index mode");
  4817. try {
  4818. if (typeof options.customFilter("test") !== "string") return console.error("Invalid customFilter. Custom filter should return string")
  4819. } catch (e) {
  4820. return console.error("Invalid customFilter. Custom filter should return string")
  4821. }
  4822. options.indexId = "#auto.fn."+common.crc32String(options.customFilter.toString());
  4823. }
  4824. if (options.indexId) {
  4825. this.customIndexes[options.indexId] = {}
  4826. }
  4827. if (typeof files == "string") files = [files];
  4828. files = files || [];
  4829. if (files.length == 0) { // that means ALL!
  4830. files = this.getAllFiles();
  4831. }
  4832. var result = {};
  4833. if (lineByLine) {
  4834. for (let i=0; i<files.length; i++) {
  4835. let thisObj = this.getObjectById(files[i]);
  4836. if (!thisObj) continue;
  4837. if (!thisObj.indexIsBuilt) this.buildIndex(files[i]);
  4838. let thisIndexIds = this.getObjectById(files[i]).indexIds;
  4839. for (var keyText in thisIndexIds) {
  4840. var keys = keyText.replaceAll("\r", "").split("\n");
  4841. for (var line=0; line<keys.length;line++) {
  4842. let key = keys[line];
  4843. if (typeof options.customFilter == "function") key = options.customFilter(key);
  4844. result[key] = result[key] || [];
  4845. result[key].push({
  4846. file :files[i],
  4847. row :thisIndexIds[keyText],
  4848. line :line
  4849. })
  4850. }
  4851. }
  4852. }
  4853. if (options.indexId) {
  4854. this.customIndexes[options.indexId] = result;
  4855. } else {
  4856. this._tempIndexes = result;
  4857. }
  4858. return result;
  4859. }
  4860. // row by row algorithm
  4861. console.log("Files is", files);
  4862. for (let i=0; i<files.length; i++) {
  4863. console.log("handling file:", files[i]);
  4864. let thisObj = this.getObjectById(files[i]);
  4865. console.log("ThisObject:", thisObj);
  4866. if (!thisObj) continue;
  4867. if (!thisObj.indexIsBuilt) this.buildIndex(files[i]);
  4868. let thisIndexIds = this.getObjectById(files[i]).indexIds;
  4869. for (let key in thisIndexIds) {
  4870. if (typeof options.customFilter == "function") key = options.customFilter(key);
  4871. result[key] = result[key] || [];
  4872. result[key].push({
  4873. file:files[i],
  4874. row:thisIndexIds[key]
  4875. })
  4876. }
  4877. }
  4878. if (options.indexId) {
  4879. this.customIndexes[options.indexId] = result;
  4880. } else {
  4881. this._tempIndexes = result;
  4882. }
  4883. console.log("Indexes is", result);
  4884. return result;
  4885. }
  4886. /**
  4887. * Get data from index
  4888. * @param {String} keyword - Keyword to search for
  4889. * @param {Object} [indexes] - Key value pair of indexes
  4890. * @param {Function} [customFilter] - Function custom filter used when building the index
  4891. * @returns {String|undefined}
  4892. */
  4893. Trans.prototype.getFromIndexes = function(keyword, indexes, customFilter) {
  4894. if (typeof customFilter == "function") {
  4895. var target = "#auto.fn."+common.crc32String(customFilter.toString())
  4896. if (this.customIndexes[target]) {
  4897. this.customIndexes[target][keyword];
  4898. }
  4899. }
  4900. indexes = indexes || this._tempIndexes || {};
  4901. return indexes[keyword];
  4902. }
  4903. /**
  4904. * Clear temporary index
  4905. * @param {Function|String} [target] - Target custom index. If empty this function will remove all indexes.
  4906. */
  4907. Trans.prototype.clearTemporaryIndexes = function(target) {
  4908. if (target) {
  4909. if (typeof target == "string") {
  4910. if (this.customIndexes[target]) delete this.customIndexes[target];
  4911. } else if (typeof target == "function") {
  4912. target = "#auto.fn."+common.crc32String(target.toString())
  4913. if (this.customIndexes[target]) delete this.customIndexes[target];
  4914. }
  4915. } else {
  4916. delete this.customIndexes
  4917. }
  4918. this._tempIndexes = undefined;
  4919. }
  4920. /**
  4921. * Find the row index by text
  4922. * @param {String} index - Index to look for
  4923. * @param {String} fileId - The file ID to process
  4924. * @returns {Number} The row index of the key string
  4925. */
  4926. Trans.prototype.findIdByIndex = function(index, fileId) {
  4927. if (trans.data == null || trans.data == '' || typeof trans.data == 'undefined') return false;
  4928. if (typeof fileId == 'undefined') {
  4929. if (typeof trans.indexIds == 'undefined') trans.buildIndex();
  4930. if (typeof trans.indexIds[index] == "undefined") return false;
  4931. return trans.indexIds[index];
  4932. } else {
  4933. if (trans.project.files[fileId].indexIsBuilt == false) trans.buildIndex(fileId);
  4934. if (typeof trans.project.files[fileId].indexIds == 'undefined') trans.buildIndex(fileId);
  4935. //console.log(trans.project.files[fileId].indexIds);
  4936. if (typeof trans.project.files[fileId].indexIds[index] == 'undefined') return false;
  4937. return trans.project.files[fileId].indexIds[index];
  4938. }
  4939. }
  4940. Trans.prototype.getClearOnNextHumanInteract = function(key) {
  4941. this._clearOnNextHumanInteract = this._clearOnNextHumanInteract || {};
  4942. if (!key) return this._clearOnNextHumanInteract;
  4943. this._clearOnNextHumanInteract[key] = this._clearOnNextHumanInteract[key] || {};
  4944. return this._clearOnNextHumanInteract[key];
  4945. }
  4946. /**
  4947. * Get the row ID by text. Case insensitive.
  4948. * @param {String} str - text to look for
  4949. * @param {String} fileId - File to look for
  4950. * @returns {Number} Row index
  4951. */
  4952. Trans.prototype.getRowIdByTextInsensitive = function(str, fileId) {
  4953. if (this.data == null || this.data == '' || typeof this.data == 'undefined') return false;
  4954. if (!fileId) throw "second argument fileId is required!"
  4955. var thisIndex = this.getClearOnNextHumanInteract(`insensitiveIndex_${fileId}`);
  4956. var data = this.getData(fileId)
  4957. var makeInsensitive = (txt) => {
  4958. if (!txt) return "";
  4959. return common.trimRightParagraph(txt).toLowerCase();
  4960. }
  4961. if (empty(thisIndex)) {
  4962. // building index
  4963. for (var rowId=0; rowId<data.length; rowId++) {
  4964. var thisKey = makeInsensitive(data[rowId][this.keyColumn]);
  4965. thisIndex[thisKey] = rowId;
  4966. }
  4967. }
  4968. return thisIndex[makeInsensitive(str)]
  4969. }
  4970. /**
  4971. * Copy imported translation into the current objects with the same id and same row index
  4972. * @param {trans.project|trans.project.files} obj
  4973. * @param {Number} [targetColumn=1] - Target column
  4974. * @param {Object} options
  4975. * @param {String[]} options.files - File IDs to process
  4976. * @param {'lineByLine'|'rowByRow'} [options.mode=lineByLine] - Translation mode
  4977. * @param {'translated'|'untranslated'|'both'} [options.fetch=translated] - Fetch translated only, or untranslated only, or both
  4978. * @param {String[]} [options.filterTag] - Tags filter
  4979. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  4980. * @param {Boolean} [options.overwrite=false] - Whether to overwrite or not if the destination cell is not empty
  4981. * @param {Number} options.targetColumn
  4982. */
  4983. Trans.prototype.copyTranslationToRow = function(obj, targetColumn, options) {
  4984. console.log("copyTranslationToRow", arguments);
  4985. if (typeof obj == 'undefined') return false;
  4986. if (typeof obj.files !== 'undefined') obj = obj.files;
  4987. targetColumn = targetColumn || options.targetColumn || 1;
  4988. options = options||{};
  4989. options.files = options.files||[];
  4990. options.mode = options.mode||"";
  4991. options.fetch = options.fetch||"";
  4992. options.filterTag = options.filterTag || [];
  4993. options.filterTagMode = options.filterTagMode || "";
  4994. options.overwrite = options.overwrite || false;
  4995. if (Array.isArray(options.files) == false) options.files = [options.files];
  4996. if (options.files.length == 0) {
  4997. for (let file in obj) {
  4998. options.files.push(file);
  4999. }
  5000. }
  5001. for (var i=0; i<options.files.length; i++) {
  5002. let file = options.files[i];
  5003. console.log("Handling", file);
  5004. if (Boolean(obj[file]) == false) continue;
  5005. var objWithSameId = trans.getObjectById(file);
  5006. for (var row=0; row<obj[file].data.length; row++) {
  5007. var thisRow = obj[file].data[row]
  5008. if (Boolean(thisRow[0]) == false) continue;
  5009. if (empty(objWithSameId.data[row])) continue;
  5010. if (options.overwrite == false && Boolean(objWithSameId.data[row][targetColumn])) continue;
  5011. var thisTranslation = trans.getTranslationFromRow(thisRow);
  5012. if (Boolean(thisTranslation) == false) thisTranslation = thisRow[0];
  5013. objWithSameId.data[row][targetColumn] = thisTranslation;
  5014. }
  5015. }
  5016. }
  5017. /**
  5018. * Generates context translation pair
  5019. * @param {trans.project|trans.project.files} obj - trans.project or trans.project.files format
  5020. * @param {Object} options
  5021. * @param {String[]} options.files - File IDs to process
  5022. * @param {'lineByLine'|'rowByRow'} [options.mode=lineByLine] - Translation mode
  5023. * @param {'translated'|'untranslated'|'both'} [options.fetch=translated] - Fetch translated only, or untranslated only, or both
  5024. * @param {String[]} [options.filterTag] - Tags filter
  5025. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  5026. * @returns {Object} translation table object {key: "translation strings"}
  5027. */
  5028. Trans.prototype.generateContextTranslationPair = function(obj, options) {
  5029. // return translation table object
  5030. // Normal mode :
  5031. // {key: "translation strings"}
  5032. //
  5033. // only on lineByLine mode :
  5034. // options.fetch
  5035. // translated, untranslated, both
  5036. // default: translated
  5037. console.log("Entering trans.generateTranslationTable");
  5038. if (typeof obj == 'undefined') return false;
  5039. if (typeof obj.files !== 'undefined') obj = obj.files;
  5040. console.log("obj files inside trans.generateTranslationTable :");
  5041. console.log(obj);
  5042. var result = {};
  5043. options = options||{};
  5044. options.files = options.files||[];
  5045. options.mode = options.mode||"";
  5046. options.fetch = options.fetch||"";
  5047. options.filterTag = options.filterTag || [];
  5048. options.filterTagMode = options.filterTagMode || "";
  5049. if (Array.isArray(options.files) == false) options.files = [options.files];
  5050. if (options.files.length == 0) {
  5051. for (let file in obj) {
  5052. options.files.push(file);
  5053. }
  5054. }
  5055. console.log("Worked option files : ");
  5056. console.log(options.files);
  5057. for (let i=0; i<options.files.length; i++) {
  5058. let file = options.files[i];
  5059. if (Boolean(obj[file]) == false) continue;
  5060. for (var row=0; row<obj[file].context.length; row++) {
  5061. if (Boolean(obj[file].context[row]) == false) continue;
  5062. if (Boolean(obj[file].data[row]) == false) continue;
  5063. var thisTranslation = trans.getTranslationFromRow(obj[file].data[row]);
  5064. if (Boolean(thisTranslation) == false) thisTranslation = obj[file].data[row][trans.keyColumn];
  5065. if (Boolean(thisTranslation) == false) continue;
  5066. for (var contextId=0; contextId<obj[file].context[row].length; contextId++) {
  5067. var thisContextKey = obj[file].context[row][contextId];
  5068. result[thisContextKey] = thisTranslation;
  5069. }
  5070. }
  5071. }
  5072. console.log("translation table collection is : ");
  5073. console.log(result);
  5074. return result;
  5075. }
  5076. /**
  5077. * Generates context translation table row by row mode
  5078. * @param {trans.project|trans.project.files} obj - trans.project or trans.project.files format
  5079. * @param {Object} options
  5080. * @param {String[]} options.files - File IDs to process
  5081. * @param {'lineByLine'|'rowByRow'} [options.mode=lineByLine] - Translation mode
  5082. * @param {'translated'|'untranslated'|'both'} [options.fetch=translated] - Fetch translated only, or untranslated only, or both
  5083. * @param {String[]} [options.filterTag] - Tags filter
  5084. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  5085. * @param {Boolean} [options.caseSensitive=false] - Whether case sensitive or not
  5086. * @returns {Object} translation table object {key: "translation strings"}
  5087. */
  5088. Trans.prototype.generateTranslationTable = function(obj, options) {
  5089. // return translation table object
  5090. // Normal mode :
  5091. // {key: "translation strings"}
  5092. // Line by Line mode :
  5093. // {keyLine1: "translation line1"}
  5094. // options.mode = default||lineByLine
  5095. //
  5096. // only on lineByLine mode :
  5097. // options.fetch
  5098. // translated, untranslated, both
  5099. // default: translated
  5100. console.log("Entering trans.generateTranslationTable");
  5101. if (typeof obj == 'undefined') return false;
  5102. if (typeof obj.files !== 'undefined') obj = obj.files;
  5103. console.log("obj files inside trans.generateTranslationTable :");
  5104. console.log(obj);
  5105. var result = {};
  5106. options = options||{};
  5107. options.files = options.files||[];
  5108. options.caseSensitive = options.caseSensitive||false; // aware of extension
  5109. options.mode = options.mode||"";
  5110. options.fetch = options.fetch||"";
  5111. options.filterTag = options.filterTag || [];
  5112. options.filterTagMode = options.filterTagMode || "";
  5113. if (Array.isArray(options.files) == false) options.files = [options.files];
  5114. if (options.files.length == 0) {
  5115. for (let file in obj) {
  5116. options.files.push(file);
  5117. }
  5118. }
  5119. console.log("Worked option files : ");
  5120. console.log(options.files);
  5121. // LINE BY LINE MODE
  5122. if (options.mode.toLowerCase() == "linebyline") {
  5123. for (let i=0; i<options.files.length; i++) {
  5124. let file = options.files[i];
  5125. console.log(file);
  5126. for (var row=0; row<obj[file].data.length; row++) {
  5127. if (Boolean(obj[file].data[row][0]) == false) continue;
  5128. if (options.filterTagMode == "blacklist") {
  5129. if (this.hasTags(options.filterTag, row, file)) continue;
  5130. } else if (options.filterTagMode == "whitelist") {
  5131. if (!this.hasTags(options.filterTag, row, file)) continue;
  5132. }
  5133. let thisTranslation = trans.getTranslationFromRow(obj[file].data[row]);
  5134. if (options.fetch == "untranslated") {
  5135. if (Boolean(thisTranslation) == true) continue;
  5136. } else if (options.fetch == "both") {
  5137. // do nothing
  5138. } else {
  5139. if (Boolean(thisTranslation) == false) continue;
  5140. }
  5141. /*
  5142. var splitedIndex = obj[file].data[row][0].split("\n").
  5143. map(function(input) {
  5144. input = input||"";
  5145. return input.replace(/\r/g, "")
  5146. });;
  5147. */
  5148. // I thin'k no need to strip \r from key element
  5149. var splitedIndex = obj[file].data[row][0].split("\n");
  5150. thisTranslation = thisTranslation||"";
  5151. var splitedResult = thisTranslation.split("\n").
  5152. map(function(input) {
  5153. input = input||"";
  5154. return input.replaceAll(/\r/g, "")
  5155. });
  5156. for (var x=0; x<splitedIndex.length; x++) {
  5157. if (options.fetch == "untranslated") {
  5158. if (Boolean(splitedResult[x]) == true) continue;
  5159. } else if (options.fetch == "both") {
  5160. // do nothing
  5161. } else {
  5162. if (Boolean(splitedResult[x]) == false) continue;
  5163. }
  5164. result[splitedIndex[x]] = splitedResult[x]||"";
  5165. }
  5166. }
  5167. }
  5168. console.log("translation table collection is : ");
  5169. console.log(result);
  5170. return result;
  5171. }
  5172. // DEFAULT MODE!
  5173. for (let i=0; i<options.files.length; i++) {
  5174. let file = options.files[i];
  5175. //console.log("Handling obj file : ", file, obj[file]);
  5176. if (Boolean(obj[file]) == false) continue;
  5177. for (let row=0; row<obj[file].data.length; row++) {
  5178. if (Boolean(obj[file].data[row][0]) == false) continue;
  5179. let thisTranslation = trans.getTranslationFromRow(obj[file].data[row]);
  5180. if (Boolean(thisTranslation) == false) continue;
  5181. result[obj[file].data[row][0]] = thisTranslation;
  5182. }
  5183. }
  5184. console.log("translation table collection is : ");
  5185. console.log(result);
  5186. return result;
  5187. }
  5188. /**
  5189. * Generate translation table line by line mode
  5190. * @param {trans.project|trans.project.files} obj
  5191. * @param {Number} [targetColumn=1] - Target column
  5192. * @param {Object} options
  5193. * @param {String[]} options.files - File IDs to process
  5194. * @param {'lineByLine'|'rowByRow'} [options.mode=lineByLine] - Translation mode
  5195. * @param {'translated'|'untranslated'|'both'} [options.fetch=translated] - Fetch translated only, or untranslated only, or both
  5196. * @param {String[]} [options.filterTag] - Tags filter
  5197. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  5198. * @param {Boolean} [options.overwrite=false] - Whether to overwrite or not if the destination cell is not empty
  5199. * @param {Boolean} [options.ignoreTranslated=false] - Whether to skip processing or not if the row already has translation
  5200. * @param {Number} options.targetColumn
  5201. * @returns {Object} translation table object {key: "translation strings"}
  5202. */
  5203. Trans.prototype.generateTranslationTableLine = function(obj, options) {
  5204. // return translation table object
  5205. // Normal mode :
  5206. // {key: "translation strings"}
  5207. // Line by Line mode :
  5208. // {keyLine1: "translation line1"}
  5209. // options.mode = default||lineByLine
  5210. //
  5211. // only on lineByLine mode :
  5212. // options.fetch
  5213. // translated, untranslated, both
  5214. // default: translated
  5215. console.log("Entering trans.generateTranslationTableLine", obj, options);
  5216. if (typeof obj == 'undefined') return false;
  5217. if (typeof obj.files !== 'undefined') obj = obj.files;
  5218. console.log("obj files inside trans.generateTranslationTable :");
  5219. console.log(obj);
  5220. var result = {};
  5221. options = options||{};
  5222. options.files = options.files||[];
  5223. options.caseSensitive = options.caseSensitive||false; // aware of extension
  5224. options.mode = options.mode||"";
  5225. options.fetch = options.fetch||"";
  5226. options.keyColumn = options.keyColumn||0;
  5227. options.filterTag = options.filterTag || [];
  5228. options.filterTagMode = options.filterTagMode || "";
  5229. options.ignoreTranslated = options.ignoreTranslated || false;
  5230. options.overwrite = options.overwrite || false;
  5231. options.collectAddress = options.collectAddress || false;
  5232. options.targetColumn;
  5233. try {
  5234. options.filterLanguage = options.filterLanguage||this.getSl()||"ja"; // japanese
  5235. } catch(e) {
  5236. options.filterLanguage = "ja"; // japanese
  5237. }
  5238. options.ignoreLangCheck = options.ignoreLangCheck||false;
  5239. console.log("ignore language check?");
  5240. console.log(options.ignoreLangCheck);
  5241. if (Array.isArray(options.files) == false) options.files = [options.files];
  5242. if (options.files.length == 0) {
  5243. for (let file in obj) {
  5244. options.files.push(file);
  5245. }
  5246. }
  5247. console.log("Worked option files : ");
  5248. console.log(options.files);
  5249. const addresses = {}
  5250. for (let i=0; i<options.files.length; i++) {
  5251. let file = options.files[i];
  5252. console.log("fetching translatable data from:", file);
  5253. for (let row=0; row<obj[file].data.length; row++) {
  5254. if (Boolean(obj[file].data[row][options.keyColumn]) == false) continue;
  5255. if (options.filterTagMode == "blacklist") {
  5256. if (this.hasTags(options.filterTag, row, file)) continue;
  5257. } else if (options.filterTagMode == "whitelist") {
  5258. if (!this.hasTags(options.filterTag, row, file)) continue;
  5259. }
  5260. if (options.ignoreTranslated) {
  5261. if (this.rowHasTranslation(obj[file].data[row], options.keyColumn)) continue;
  5262. }
  5263. if (options.overwrite == false && options.targetColumn) {
  5264. if (obj[file].data[row][options.targetColumn]) continue;
  5265. }
  5266. console.log("Reached here!");
  5267. var thisTranslation = trans.getTranslationFromRow(obj[file].data[row], options.keyColumn, [0]);
  5268. console.log("current translation", thisTranslation);
  5269. // I think no need to strip \r from key element
  5270. var splitedIndex = obj[file].data[row][options.keyColumn].split("\n");
  5271. thisTranslation = thisTranslation||"";
  5272. var splitedResult = thisTranslation.split("\n").
  5273. map(function(input) {
  5274. input = input||"";
  5275. return input.replaceAll(/\r/g, "")
  5276. });
  5277. for (var x=0; x<splitedIndex.length; x++) {
  5278. // if (options.ignoreWhitespace) {
  5279. // if (!splitedResult[x]) continue;
  5280. // if (!splitedResult[x].trim()) continue;
  5281. // }
  5282. if (options.fetch == "untranslated") {
  5283. if (Boolean(splitedResult[x]) == true) continue;
  5284. } else if (options.fetch == "both") {
  5285. // do nothing
  5286. } else {
  5287. if (Boolean(splitedResult[x]) == false) continue;
  5288. }
  5289. if (options.ignoreLangCheck == false) {
  5290. // skip collecting data if language doesn't match options.filterLanguage
  5291. if (common.isInLanguage(splitedIndex[x], options.filterLanguage) == false) continue;
  5292. }
  5293. result[splitedIndex[x]] = splitedResult[x]||"";
  5294. if (options.collectAddress) {
  5295. addresses[splitedIndex[x]] ||= [];
  5296. addresses[splitedIndex[x]].push({
  5297. line:x,
  5298. file:file,
  5299. row:row,
  5300. rowObj:obj[file].data[row]
  5301. })
  5302. }
  5303. }
  5304. }
  5305. }
  5306. console.log("result is : ");
  5307. console.log(result);
  5308. console.log("addresses:", addresses);
  5309. if (options.collectAddress) {
  5310. return {
  5311. pairs: result,
  5312. addresses: addresses
  5313. }
  5314. }
  5315. return result;
  5316. }
  5317. /**
  5318. * generate translation pair from strings
  5319. * @param {String|String[]} input - input can be string or array of string
  5320. * @param {TranslatorEngine} transEngine - Translator engine
  5321. * @param {Object} options
  5322. * @param {String} [options.filterLanguage=this.getSl()]
  5323. * @param {Boolean} [options.ignoreLangCheck=boolean]
  5324. * @param {Boolean} [options.ignoreLangCheck=boolean]
  5325. * @returns {Object} - include{'source text':'translation'},
  5326. * exclude{'filtered text':''}
  5327. */
  5328. Trans.prototype.generateTranslationTableFromStrings = function(input, transEngine, options) {
  5329. /*
  5330. input can be string or array of string
  5331. generate translation pair from strings
  5332. return : include{'source text':'translation'},
  5333. exclude{'filtered text':''}
  5334. */
  5335. options = options||{};
  5336. try {
  5337. options.filterLanguage = options.filterLanguage||this.getSl()||"ja"; // japanese
  5338. } catch(e) {
  5339. options.filterLanguage = "ja"; // japanese
  5340. }
  5341. options.ignoreLangCheck = options.ignoreLangCheck||false;
  5342. var ignoreLangCheck
  5343. try {
  5344. ignoreLangCheck = options.ignoreLangCheck || transEngine.getOptions("ignoreLangCheck");
  5345. } catch (e) {
  5346. ignoreLangCheck = false;
  5347. }
  5348. if (typeof input == 'string') input = [input];
  5349. var result = {
  5350. include:{},
  5351. exclude:{}
  5352. };
  5353. if (options.mode == "rowByRow") {
  5354. for (let i=0; i<input.length; i++) {
  5355. if (typeof input[i] != 'string') continue;
  5356. if (input[i].length < 1) continue;
  5357. if (!ignoreLangCheck) {
  5358. // skip collecting data if language doesn't match options.filterLanguage
  5359. if (common.isInLanguage(input[i], options.filterLanguage) == false) {
  5360. result.exclude[input[i]] = input[i];
  5361. continue;
  5362. }
  5363. }
  5364. result.include[input[i]] = "";
  5365. }
  5366. } else {
  5367. for (let i=0; i<input.length; i++) {
  5368. if (typeof input[i] != 'string') continue;
  5369. if (input[i].length < 1) continue;
  5370. var splitedIndex = input[i].replaceAll("\r", "").split("\n");
  5371. for (var x=0; x<splitedIndex.length; x++) {
  5372. if (options.ignoreWhitespace) {
  5373. if (!splitedIndex[x]) continue;
  5374. if (!splitedIndex[x].trim()) continue;
  5375. }
  5376. if (ignoreLangCheck) {
  5377. // skip collecting data if language doesn't match options.filterLanguage
  5378. if (common.isInLanguage(splitedIndex[x], options.filterLanguage) == false) {
  5379. result.exclude[splitedIndex[x]] = splitedIndex[x];
  5380. continue;
  5381. }
  5382. }
  5383. result.include[splitedIndex[x]] = "";
  5384. }
  5385. }
  5386. }
  5387. return result;
  5388. }
  5389. /**
  5390. * generate translation table from translation result
  5391. * @param {String[]} keywordPool - ["keyword1", "keyword2", ... ]
  5392. * @param {String[]} translationPool - ["translationOfKeyword1", "translationOfKeyword2", ...]
  5393. * @param {Object} defaultTrans - Default object
  5394. * @returns {Object} {"keyword1":"translationOfKeyword1", "keyword2":"translationOfKeyword2", ...}
  5395. */
  5396. Trans.prototype.generateTranslationTableFromResult = function(keywordPool, translationPool, defaultTrans) {
  5397. /*
  5398. generate translation table from translation result
  5399. keywordPool = ["keyword1", "keyword2", ... ]
  5400. translationPool = ["translationOfKeyword1", "translationOfKeyword2", ...]
  5401. result :
  5402. translationTable
  5403. {"keyword1":"translationOfKeyword1", "keyword2":"translationOfKeyword2", ...};
  5404. */
  5405. //console.log("generateTranslationTableFromResult Default translation:", arguments);
  5406. var result = defaultTrans || {};
  5407. for (var i=0; i<keywordPool.length; i++) {
  5408. if (typeof translationPool[i] == 'undefined') continue;
  5409. result[keywordPool[i]] = translationPool[i];
  5410. }
  5411. //console.log(JSON.stringify(result, undefined, 2))
  5412. return result;
  5413. }
  5414. /**
  5415. * Generates a translation table for the selected cells based on the provided parameters.
  5416. * @param {Array} [currentSelection] - The current selection of cells. If not provided, it defaults to the selected range in the grid.
  5417. * @param {string} [fileId] - The file ID. If not provided, it defaults to the currently selected file ID.
  5418. * @param {Object} [options] - Additional options for generating the translation table.
  5419. * @returns {Object} - The generated translation table.
  5420. */
  5421. Trans.prototype.generateSelectedTranslationTable = function(currentSelection, fileId, options) {
  5422. currentSelection = currentSelection||this.grid.getSelectedRange()||[[]];
  5423. fileId = fileId || this.getSelectedId();
  5424. options = options || {};
  5425. var selectedCells = common.gridSelectedCells(currentSelection);
  5426. var thisData = this.getData(fileId)
  5427. var transTable = {};
  5428. for (var i=0; i<selectedCells.length; i++) {
  5429. var row = selectedCells[i].row
  5430. var col = selectedCells[i].col
  5431. var origText = thisData[row][this.keyColumn];
  5432. transTable[origText] = transTable[origText] || [];
  5433. transTable[origText].push({
  5434. col:col,
  5435. row:row,
  5436. value:thisData[row][col],
  5437. file:fileId
  5438. })
  5439. }
  5440. return transTable;
  5441. }
  5442. /**
  5443. * Word wrap a text
  5444. * @param {String} str
  5445. * @param {String[]} [rowTags=[]] - List of tags of the current row
  5446. * @param {String[]} [wordWrapByTags=[]] - List of tags to filter
  5447. * @param {String} [lineBreak="\n"] - Line break character
  5448. * @returns {String} Word wrapped text
  5449. */
  5450. Trans.prototype.wordWrapText = function(str, rowTags=[], wordWrapByTags=[], lineBreak="\n") {
  5451. //console.log("wordWrap", arguments);
  5452. if (empty(wordWrapByTags)) return str;
  5453. if (empty(rowTags)) return str;
  5454. if (window.langTools?.isCJK(this.getTl())) {
  5455. for (let i=0; i<wordWrapByTags.length; i++) {
  5456. let intersect = common.arrayIntersect(rowTags, wordWrapByTags[i].tags);
  5457. if (intersect.length>0) return common.wordwrapLocale(str, wordWrapByTags[i].maxLength, this.getTl(), lineBreak);
  5458. }
  5459. }
  5460. for (let i=0; i<wordWrapByTags.length; i++) {
  5461. let intersect = common.arrayIntersect(rowTags, wordWrapByTags[i].tags);
  5462. if (intersect.length>0) return common.wordwrap(str, wordWrapByTags[i].maxLength, lineBreak);
  5463. }
  5464. return str;
  5465. }
  5466. /**
  5467. * Translation Data object generated by trans.getTranslationData
  5468. * @typedef {Object} TranslationData
  5469. * @property {Object} TranslationData.info - Information header of the translation pairs
  5470. * @property {Object} TranslationData.translationData - Translation data
  5471. * @property {Object} TranslationData.translationData[file] - list of translation pairs grouped by the file id
  5472. * @property {Object} TranslationData.translationData[file].info - Information of the current file
  5473. * @property {Object} TranslationData.translationData[file].translationPair - Key value pair of original text and translation
  5474. * @example
  5475. * {
  5476. "info": {
  5477. "filterTag": [],
  5478. "filterTagMode": ""
  5479. },
  5480. "translationData": {
  5481. "data/Actors.json": {
  5482. "info": {},
  5483. "translationPair": {
  5484. "key text": "translation",
  5485. "key text2": "translation2",
  5486. }
  5487. },
  5488. "data/Animations.json": {
  5489. "info": {},
  5490. "translationPair": {
  5491. "key text": "translation",
  5492. "key text2": "translation2",
  5493. }
  5494. }
  5495. }
  5496. }
  5497. */
  5498. /**
  5499. * Generate Translation Data object
  5500. * @param {Trans} [transData=trans.getSaveData()] - instance of Trans object
  5501. * @param {Object} [options]
  5502. * @param {Object} [options.keyCol=0] - Key column of the table
  5503. * @param {Object} [options.groupIndex] - index added for the translation pair prefixes
  5504. * @param {String} [options.groupBy=path] - Group by what key. Default is path. use "id" to group by the key instead.
  5505. * @param {Object} [options.options]
  5506. * @param {String[]} [options.filterTag] - Tags filter
  5507. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  5508. * @param {Object} [options.wordWrapByTags]
  5509. * @returns {TranslationData} Translation information
  5510. * @fires onGenerateTranslationData
  5511. */
  5512. Trans.prototype.getTranslationData = function(transData, options) {
  5513. /*
  5514. Generate Translation Pair Advanced
  5515. Generate translation pair from project file
  5516. It will use relPath for group key
  5517. result :
  5518. {
  5519. info : {
  5520. groupLevel : 0 // integer
  5521. },
  5522. translationData: {
  5523. [groupName] : {
  5524. info: {
  5525. },
  5526. translationPair : {
  5527. "key" : "translation"
  5528. "group[separator]key" : "translation"
  5529. }
  5530. }
  5531. }
  5532. }
  5533. */
  5534. options = options || {}
  5535. options.keyCol = options.keyCol|| 0;
  5536. options.groupIndex = options.groupIndex||undefined; // index added for the translation pair prefixes
  5537. options.groupBy = options.groupBy || "path";
  5538. options.objectGrouping = options.objectGrouping || false // if true child translation pair will be under a sub-object inside translationPair object
  5539. options.includeTagsInfo = options.includeTagsInfo || false;
  5540. transData = transData||trans.getSaveData()
  5541. transData = JSON.parse(JSON.stringify(transData));
  5542. transData.project = transData.project||{}
  5543. transData.project.files = transData.project.files||{};
  5544. // fix for filtertag mode inside options.options
  5545. // this happens in export mode
  5546. options.options = options.options || {};
  5547. options.filterTag = options.filterTag||options.options.filterTag||[];
  5548. options.filterTagMode = options.filterTagMode||options.options.filterTagMode||""; // whitelist or blacklist
  5549. options.wordWrapByTags = options.wordWrapByTags || options.options.wordWrapByTags || transData.project.options.wordWrapByTags;
  5550. options.useSelectedFiles ??= true;
  5551. options.disableEvent ||= false;
  5552. options.collectUntranslated ||= false;
  5553. var contextSeparator = options.contextSeparator || "\n"
  5554. var autofillFiles = [];
  5555. if (options.useSelectedFiles) {
  5556. var checkbox = $(".fileList .data-selector .fileCheckbox:checked");
  5557. for (var i=0; i<checkbox.length; i++) {
  5558. autofillFiles.push(checkbox.eq(i).attr("value"));
  5559. }
  5560. }
  5561. options.files = options.files||autofillFiles||[];
  5562. if (options.groupBy == "id") {
  5563. // generating id based on key index
  5564. for (let fileId in transData.project.files) {
  5565. if (!transData.project.files[fileId]) continue;
  5566. transData.project.files[fileId].id = fileId;
  5567. }
  5568. }
  5569. var transGroup = {};
  5570. var info = {
  5571. filterTag : options.filterTag,
  5572. filterTagMode : options.filterTagMode
  5573. };
  5574. if (!empty(options.wordWrapByTags)) {
  5575. info.wordWrapByTags = options.wordWrapByTags
  5576. }
  5577. for (let fileId in transData.project.files) {
  5578. var thisFiles = transData.project.files[fileId];
  5579. thisFiles.data = thisFiles.data||[[]];
  5580. thisFiles.tags = thisFiles.tags||[];
  5581. if (options.files.length > 0) {
  5582. if (options.files.includes(fileId) == false) continue;
  5583. }
  5584. var thisData = {
  5585. info:{
  5586. groupLevel : thisFiles['groupLevel']
  5587. },
  5588. translationPair : {}
  5589. }
  5590. transGroup[thisFiles[options.groupBy]] = transGroup[thisFiles[options.groupBy]] || thisData;
  5591. for (var row=0; row<thisFiles.data.length; row++) {
  5592. if (Boolean(thisFiles.data[row]) == false) continue;
  5593. if (Boolean(thisFiles.data[row][options.keyCol]) == false) continue;
  5594. var thisTag = thisFiles.tags[row] || [];
  5595. if (options.filterTagMode !== "") {
  5596. var intersect = options.filterTag.filter(value => thisTag.includes(value));
  5597. if (options.filterTagMode == "whitelist") {
  5598. if (intersect.length == 0) continue;
  5599. } else { // other than whitelist always assume blacklist
  5600. if (intersect.length > 0) continue;
  5601. }
  5602. }
  5603. try {
  5604. var originalWord = thisFiles.data[row][options.keyCol] = thisFiles.data[row][options.keyCol] || "";
  5605. var thisTranslation = trans.getTranslationFromRow(thisFiles.data[row], options.keyCol);
  5606. var transByContext = ui.translationByContext.generateContextTranslation(row, fileId, originalWord);
  5607. if (!options.collectUntranslated) {
  5608. if ((Boolean(thisTranslation) == false) && transByContext.length == 0) continue
  5609. if (transByContext.length > 0) transGroup[thisFiles[options.groupBy]].translationPair = Object.assign(transGroup[thisFiles[options.groupBy]].translationPair, transByContext.translation)
  5610. if (options.objectGrouping) {
  5611. if (thisFiles[options.groupIndex]) {
  5612. //assign to sub object
  5613. //console.log("assigning to child object",thisFiles[options.groupIndex]);
  5614. transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]] = transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]] || {};
  5615. if ((Boolean(thisTranslation) !== false)) transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]][originalWord] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags);
  5616. } else {
  5617. //direct translation string
  5618. if ((Boolean(thisTranslation) !== false)) transGroup[thisFiles[options.groupBy]].translationPair[originalWord] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags);
  5619. }
  5620. } else {
  5621. let thisKey = thisFiles[options.groupIndex] ? thisFiles[options.groupIndex]+contextSeparator+originalWord : originalWord
  5622. if ((Boolean(thisTranslation) !== false)) transGroup[thisFiles[options.groupBy]].translationPair[thisKey] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags);
  5623. }
  5624. } else {
  5625. if (transByContext.length > 0) transGroup[thisFiles[options.groupBy]].translationPair = Object.assign(transGroup[thisFiles[options.groupBy]].translationPair, transByContext.translation)
  5626. if (options.objectGrouping) {
  5627. if (thisFiles[options.groupIndex]) {
  5628. //assign to sub object
  5629. //console.log("assigning to child object",thisFiles[options.groupIndex]);
  5630. transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]] = transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]] || {};
  5631. transGroup[thisFiles[options.groupBy]].translationPair[thisFiles[options.groupIndex]][originalWord] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags) || "";
  5632. } else {
  5633. //direct translation string
  5634. transGroup[thisFiles[options.groupBy]].translationPair[originalWord] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags) || "";
  5635. }
  5636. } else {
  5637. let thisKey = thisFiles[options.groupIndex] ? thisFiles[options.groupIndex]+contextSeparator+originalWord : originalWord
  5638. transGroup[thisFiles[options.groupBy]].translationPair[thisKey] = trans.wordWrapText(thisTranslation, thisTag, options.wordWrapByTags) || "";
  5639. }
  5640. }
  5641. } catch (e) {
  5642. console.log("Error when processing", fileId, "row", row, thisFiles.data[row][options.keyCol]);
  5643. throw(e);
  5644. }
  5645. //console.log("at the end : ", transGroup[thisFiles[options.groupBy]]);
  5646. }
  5647. }
  5648. /**
  5649. * @event Trans#onGenerateTranslationData
  5650. * @param {Object} options
  5651. * @param {Object} options.info
  5652. * @param {Object} options.translationData
  5653. */
  5654. if (!options.disableEvent) {
  5655. this.trigger("onGenerateTranslationData", {
  5656. info:info,
  5657. translationData:transGroup
  5658. });
  5659. }
  5660. return {
  5661. info:info,
  5662. translationData:transGroup
  5663. }
  5664. }
  5665. /**
  5666. * Build context from parameter
  5667. * @param {Object} parameter - Object paramter
  5668. * @returns {string} context string
  5669. */
  5670. Trans.prototype.buildContextFromParameter = function(parameter) {
  5671. return parameter['VALUE ID']+"/"+consts.eventCode[trans.gameEngine][parameter['EVENT CODE']];
  5672. }
  5673. // =====================================================================
  5674. // DATA VALIDATION & MANIPUlATION & PROJECT CREATION DATA INITIALIZATION
  5675. // =====================================================================
  5676. /**
  5677. * Get the staging path of the current project
  5678. * @param {Trans} [transData] - Trans Object to identify the staging path
  5679. * @returns {String|undefined} A full path to the stagging directory. Return undefined when fail
  5680. * @since 4.4.4
  5681. */
  5682. Trans.prototype.getStagingPath = function(transData) {
  5683. try {
  5684. transData ||= this;
  5685. return nwPath.resolve(transData?.project?.cache?.cachePath)
  5686. } catch (e) {
  5687. return;
  5688. }
  5689. }
  5690. /**
  5691. * Retrieves the staging data path based on the provided Trans data.
  5692. * @param {any} transData - The Trans data.
  5693. * @returns {string} - The staging data path.
  5694. */
  5695. Trans.prototype.getStagingDataPath = function(transData) {
  5696. var defaultBaseData = engines.current().getProperty("stagingDataPath") || "data";
  5697. return nwPath.join(this.getStagingPath(transData), defaultBaseData);
  5698. }
  5699. /**
  5700. * Update gameInfo.json at staging location
  5701. * @param {Trans|undefined} [transData] - Trans data
  5702. */
  5703. Trans.prototype.updateStagingInfo = async function(transData) {
  5704. transData ||= this;
  5705. const stagingInfoFile = nwPath.join(this.getStagingPath(transData)||"", "gameInfo.json");
  5706. console.log("Staging info:", stagingInfoFile);
  5707. var stagingInfo = {}
  5708. if (await common.isFileAsync(stagingInfoFile)) {
  5709. stagingInfo = JSON.parse(await common.fileGetContents(stagingInfoFile));
  5710. }
  5711. stagingInfo.title = transData.project.gameTitle;
  5712. stagingInfo.engine = transData.project.gameEngine;
  5713. await common.filePutContents(stagingInfoFile, JSON.stringify(stagingInfo, undefined, 2), "UTF8", false);
  5714. return stagingInfo;
  5715. }
  5716. /**
  5717. * Get the real path to the staging file
  5718. * @param {String|Object} obj - String file ID or object
  5719. * @since 4.6.29
  5720. * @returns {String} Path to the file
  5721. */
  5722. Trans.prototype.getStagingFile = function(obj) {
  5723. if (typeof obj == "string") {
  5724. obj = this.getObjectById(obj)
  5725. }
  5726. if (!obj) return;
  5727. if (typeof obj !== "object") return;
  5728. if (!obj.path) return;
  5729. var stagintPath = nwPath.join(this.getStagingDataPath(), obj.path);
  5730. return stagintPath;
  5731. }
  5732. /**
  5733. * Insert cell
  5734. * @param {Number} index
  5735. * @param {String|null} value
  5736. */
  5737. Trans.prototype.insertCell = function(index, value) {
  5738. value = value||null;
  5739. common.batchArrayInsert(trans.data, index, value);
  5740. if(typeof trans.project == "undefined") return trans.alert(t("Please open or create a new project first!"));
  5741. for (var file in trans.project.files) {
  5742. if (file == trans.getSelectedId()) continue;
  5743. common.batchArrayInsert(trans.project.files[file].data, index, value);
  5744. }
  5745. }
  5746. /**
  5747. * Copy column
  5748. * @param {Number} from
  5749. * @param {Number} to
  5750. * @param {Object} [project=trans.project]
  5751. * @param {Object} [options]
  5752. */
  5753. Trans.prototype.copyCol = function(from, to, project, options) {
  5754. console.log("Copying column");
  5755. console.log(arguments);
  5756. options = options || {};
  5757. project = project || trans.project;
  5758. if (typeof project == 'undefined') return console.log("project is undefined");
  5759. if (typeof project.files == 'undefined') return console.log("project.files are undefined");
  5760. for (var file in project.files) {
  5761. if (Array.isArray(project.files[file].data) == false) {
  5762. console.log("no data for files "+file);
  5763. continue;
  5764. }
  5765. for (var row in project.files[file].data) {
  5766. project.files[file].data[row][to] = project.files[file].data[row][from];
  5767. }
  5768. }
  5769. }
  5770. /**
  5771. * Check whether the grid is modified or not
  5772. * @param {Boolean} [flag] - If flag is defined, then set the flag
  5773. * @returns {Boolean}
  5774. */
  5775. Trans.prototype.gridIsModified =function(flag) {
  5776. if (typeof flag == 'undefined') return this.unsavedChange;
  5777. if (!this.project) {
  5778. this.unsavedChange = false;
  5779. return;
  5780. }
  5781. if (this.unsavedChange !== flag) {
  5782. /**
  5783. * Triggered when grid is modified
  5784. * @event Trans#documentModifiedStateChange
  5785. * @param {Boolean} flag
  5786. */
  5787. this.trigger("documentModifiedStateChange", flag);
  5788. }
  5789. this.unsavedChange = flag;
  5790. //console.trace("Grid is modified");
  5791. var thisId = this.getSelectedId();
  5792. if (Boolean(this.project.files) == false) return false;
  5793. if (!this.project.files[thisId]) return false;
  5794. this.project.files[thisId]["cacheResetOnChange"] = {};
  5795. return this.unsavedChange;
  5796. }
  5797. /**
  5798. * iteratively select all files and return to the last selection
  5799. */
  5800. Trans.prototype.walkToAllFile = function() {
  5801. console.log($(".fileList .selected"));
  5802. var current = $(".fileList li").index($(".fileList .selected"));
  5803. for (var i=0; i<$(".fileList li").length; i++) {
  5804. $(".fileList li").eq(i).trigger("click");
  5805. }
  5806. $(".fileList li").eq(current).trigger("click");
  5807. }
  5808. /**
  5809. * Move a column to the new index
  5810. * @param {Number} fromIndex - Source column index
  5811. * @param {Number} toIndex - Destination column index
  5812. * @returns {Trans} Instance of trans
  5813. */
  5814. Trans.prototype.moveColumn = async function(fromIndex, toIndex) {
  5815. console.log("trans.moveColumn");
  5816. console.log(arguments);
  5817. if (typeof trans.project == 'undefined') return false;
  5818. if (toIndex > Math.min.apply(null, fromIndex)) {
  5819. console.log("move to rigth");
  5820. toIndex = toIndex-1;
  5821. }
  5822. if (fromIndex[0] == toIndex) return false;
  5823. if (toIndex < Math.max.apply(null, fromIndex)) {
  5824. console.log("move to left");
  5825. }
  5826. ui.showBusyOverlay();
  5827. for (var file in trans.project.files) {
  5828. //if (file == trans.getSelectedId()) continue;
  5829. for (var row=0; row<trans.project.files[file].data.length; row++) {
  5830. trans.project.files[file].data[row] = common.arrayMoveBatch(trans.project.files[file].data[row], fromIndex, toIndex);
  5831. // adjusting cellInfo
  5832. this.cellInfo.moveCell(file, row, fromIndex, toIndex);
  5833. }
  5834. }
  5835. //sorting colHeaders
  5836. trans.colHeaders = common.arrayMoveBatch(trans.colHeaders, fromIndex, toIndex);
  5837. //sorting column
  5838. trans.column = common.arrayMoveBatch(trans.column, fromIndex, toIndex);
  5839. await common.wait(250)
  5840. trans.grid.destroy();
  5841. trans.initTable();
  5842. ui.hideBusyOverlay();
  5843. trans.renderGridInfo();
  5844. trans.gridIsModified(true);
  5845. return trans;
  5846. }
  5847. /**
  5848. * Padding data by the length of header column
  5849. * @returns {Trans}
  5850. */
  5851. Trans.prototype.dataPadding = function() {
  5852. // padding data by the length of header column
  5853. if (typeof trans.data == 'undefined') return false;
  5854. console.log("Trans data : ", trans.data);
  5855. for (let i in trans.data) {
  5856. if (Array.isArray(trans.data[i]) == false) trans.data[i] = [];
  5857. if (trans.data[i].length >= trans.colHeaders.length) continue;
  5858. let dif = trans.colHeaders.length - trans.data[i].length;
  5859. if (dif < 0) continue;
  5860. console.log("trans.data[i] : ", trans.data[i]);
  5861. console.log("trans.data : ", trans.data[i].length);
  5862. console.log("dif length : ", dif);
  5863. let padding = Array(dif).fill(null);
  5864. trans.data[i] = trans.data[i].concat(padding);
  5865. }
  5866. if (typeof trans.project == 'undefined') return false;
  5867. for (let file in trans.project.files) {
  5868. for (let i in trans.project.files[file].data) {
  5869. if (trans.project.files[file].data[i].length >= trans.colHeaders.length) continue;
  5870. let dif = trans.colHeaders.length - trans.project.files[file].data[i].length;
  5871. let padding = Array(dif).fill(null);
  5872. trans.project.files[file].data[i] = trans.project.files[file].data[i].concat(padding);
  5873. }
  5874. }
  5875. trans.refreshGrid();
  5876. return trans;
  5877. }
  5878. /**
  5879. * Generating header based on the maximum length of the data
  5880. * @param {Trans} [trans=this] - Trans data
  5881. * @param {String} [prefix]
  5882. * @returns {Object} Column header
  5883. */
  5884. Trans.prototype.generateHeader = function(trans, prefix) {
  5885. // generating header based on the maximum length of the data
  5886. trans = trans || this;
  5887. prefix = prefix || "";
  5888. var maxLength = 0;
  5889. for (let file in trans.project.files) {
  5890. let currentData = trans.project.files[file].data;
  5891. currentData = currentData||[];
  5892. for (let i=0; i<currentData.length; i++) {
  5893. if (Array.isArray(currentData[i]) == false) continue;
  5894. if (currentData[i].length > maxLength) maxLength = currentData[i].length;
  5895. }
  5896. }
  5897. for (let i=trans.colHeaders.length-1; i<maxLength; i++) {
  5898. trans.colHeaders.push(prefix+String.fromCharCode(65+i))
  5899. trans.columns.push({});
  5900. }
  5901. return trans.colHeaders;
  5902. }
  5903. /**
  5904. * Sanitize instance of the Trans data
  5905. * @param {Trans} trans
  5906. * @returns {Trans}
  5907. */
  5908. Trans.prototype.sanitize = function(trans) {
  5909. trans = trans || this;
  5910. console.log("running trans.sanitize");
  5911. if (typeof trans.project == 'undefined') return false;
  5912. if (typeof trans.project.files == 'undefined') return false;
  5913. //var rowPad = JSON.parse(JSON.stringify(this.colHeaders))
  5914. //rowPad.fill(null)
  5915. //console.log("data of rowPad : ", rowPad);
  5916. for (var file in trans.project.files) {
  5917. var currentData = trans.project.files[file].data;
  5918. var currentContext = trans.project.files[file].context||[];
  5919. var currentTags = trans.project.files[file].tags||[];
  5920. var currentParameters = trans.project.files[file].parameters||[];
  5921. var inCache = {};
  5922. var newData = [];
  5923. var newContext = [];
  5924. var newTags = [];
  5925. var newParameters = [];
  5926. this.colHeaders = this.colHeaders||[];
  5927. if (Array.isArray(currentData) == false) {
  5928. // if not an array, overwrite with blank array.
  5929. trans.project.files[file].data = [JSON.parse(JSON.stringify(this.colHeaders)).fill(null)];
  5930. continue;
  5931. } else if (currentData.length == 0) {
  5932. trans.project.files[file].data = [JSON.parse(JSON.stringify(this.colHeaders)).fill(null)];
  5933. continue;
  5934. }
  5935. currentData = currentData||[];
  5936. for (var i=0; i<currentData.length; i++) {
  5937. if (typeof currentData[i][0] !== 'string') continue;
  5938. if (currentData[i][0].length < 1) continue;
  5939. if (typeof inCache[currentData[i][0]] == 'undefined') {
  5940. newData.push(currentData[i]);
  5941. var row = newData.length - 1;
  5942. if (currentContext[i]) newContext[row] = currentContext[i];
  5943. if (currentTags[i]) newTags[row] = currentTags[i];
  5944. if (currentParameters[i]) newParameters[row] = currentParameters[i];
  5945. inCache[currentData[i][0]] = true;
  5946. }
  5947. }
  5948. trans.project.files[file].data = newData;
  5949. trans.project.files[file].context = newContext;
  5950. trans.project.files[file].tags = newTags;
  5951. trans.project.files[file].parameters = newParameters;
  5952. }
  5953. trans.project.isDuplicatesRemoved = true;
  5954. return trans;
  5955. }
  5956. /**
  5957. * Remove duplicate entries from current trans.data
  5958. * Should be run once on initialization
  5959. * @returns {string[][]} trans.data, two dimensional array of the grid
  5960. */
  5961. Trans.prototype.removeDuplicates = function() {
  5962. console.log("running trans.removeDuplicates");
  5963. var inCache = {};
  5964. var newData = [];
  5965. for (var i=0; i<trans.data.length; i++) {
  5966. if (typeof inCache[trans.data[i][0]] == 'undefined') {
  5967. newData.push(trans.data[i]);
  5968. inCache[trans.data[i]] = true;
  5969. }
  5970. }
  5971. trans.data = newData;
  5972. return trans.data;
  5973. }
  5974. /**
  5975. * Check whether the key text is exist on a file
  5976. * @param {String} key - key text to find
  5977. * @param {String} fileId - File id to search for
  5978. * @returns {Boolean}
  5979. */
  5980. Trans.prototype.isKeyExistOn = function(key, fileId) {
  5981. if (typeof fileId == 'undefined') fileId = trans.getSelectedId();
  5982. if (typeof trans.findIdByIndex(key, fileId) == 'number') {
  5983. return true;
  5984. } else {
  5985. return false;
  5986. }
  5987. }
  5988. /**
  5989. * Check whether the key text is exist on current active file
  5990. * @param {String} key - key text to find
  5991. * @returns {Boolean}
  5992. */
  5993. Trans.prototype.isKeyExist = function(key) {
  5994. if (typeof trans.findIdByIndex(key) == 'number') {
  5995. return true;
  5996. } else {
  5997. return false;
  5998. }
  5999. }
  6000. // ============================================================
  6001. // TAGGING
  6002. // ============================================================
  6003. /**
  6004. * Set tags to the preferred row
  6005. * @param {String} file - File Id
  6006. * @param {Number} row - Row index
  6007. * @param {String|String[]} tags - tags to set
  6008. * @param {Object} options
  6009. * @param {Boolean} [options.append] - Whether to append or to override the tags with the current value
  6010. * @returns {String[]} The current tags of the preferred row
  6011. */
  6012. Trans.prototype.setTags = function(file, row, tags, options) {
  6013. /* options : {
  6014. append : boolean
  6015. }
  6016. */
  6017. options = options||{};
  6018. if (Array.isArray(tags) == false) tags = [tags];
  6019. if (typeof this.project == 'undefined') return false;
  6020. if (typeof this.project.files[file] == 'undefined') return false;
  6021. if (typeof row != 'number') return false;
  6022. if (typeof this.project.files[file].tags == 'undefined') this.project.files[file].tags = [];
  6023. if (Boolean(options.append) == true) {
  6024. this.project.files[file].tags[row] = this.project.files[file].tags[row]||[];
  6025. this.project.files[file].tags[row].push.apply(this.project.files[file].tags[row], tags);
  6026. this.project.files[file].tags[row] = this.project.files[file].tags[row].filter((v, i, a) => a.indexOf(v) === i);
  6027. } else {
  6028. this.project.files[file].tags[row] = tags;
  6029. }
  6030. //this.grid.render();
  6031. return this.project.files[file].tags[row];
  6032. }
  6033. /**
  6034. * Removes one or more tags from the preferred row
  6035. * @param {String} file - File Id
  6036. * @param {Number} row - Row index
  6037. * @param {String|String[]} tags - tags to set
  6038. * @param {Object} options
  6039. * @returns {String[]} The current tags of the preferred row
  6040. */
  6041. Trans.prototype.removeTags = function(file, row, tags, options) {
  6042. console.log("removeTags", arguments);
  6043. options = options||{};
  6044. file = file||this.getSelectedId();
  6045. if (Array.isArray(tags) == false) tags = [tags];
  6046. if (typeof this.project == 'undefined') return false;
  6047. if (typeof this.project.files[file] == 'undefined') return false;
  6048. if (typeof row != 'number') return false;
  6049. if (typeof this.project.files[file].tags == 'undefined') this.project.files[file].tags = [];
  6050. let arr = this.project.files[file].tags?.[row];
  6051. console.log("Current tags", arr);
  6052. if (Array.isArray(arr) == false) return [];
  6053. arr = arr.filter(item => !tags.includes(item))
  6054. this.project.files[file].tags[row] = arr;
  6055. return this.project.files[file].tags[row];
  6056. }
  6057. /**
  6058. * Removes one or more tags from the preferred row
  6059. * @param {String} file - File Id
  6060. * @param {Number|CellRanges} cellRange - Row index
  6061. * @param {Object} options
  6062. * @returns {String[]} The current tags of the preferred row
  6063. */
  6064. Trans.prototype.clearTags = function(file, cellRange, options) {
  6065. options = options||{};
  6066. file = file||this.getSelectedId();
  6067. if (typeof this.project == 'undefined') return false;
  6068. if (typeof this.project.files[file] == 'undefined') return false;
  6069. if (typeof cellRange == 'number') {
  6070. this.project.files[file].tags[cellRange] = [];
  6071. return this.project.files[file].tags[cellRange];
  6072. }
  6073. for (let i=0; i<cellRange.length; i++) {
  6074. var cellStart = cellRange[i].start || cellRange[i].from;
  6075. var cellEnd = cellRange[i].end || cellRange[i].to;
  6076. if (typeof cellStart.row == 'undefined') continue
  6077. if (typeof cellEnd.row == 'undefined') continue
  6078. this.project.files[file].tags = this.project.files[file].tags||[];
  6079. for (var row=cellStart.row; row <= cellEnd.row; row++) {
  6080. this.project.files[file].tags[row] = [];
  6081. }
  6082. }
  6083. return this.project.files[file].tags[row];
  6084. }
  6085. /**
  6086. * Removes all tags settings from a file
  6087. * @param {String} file - File Id
  6088. * @param {Object} options
  6089. * @returns {String[]} The current tags of the preferred file, which is an empty array
  6090. */
  6091. Trans.prototype.resetTags = function(file, options) {
  6092. options = options||{};
  6093. file = file||this.getSelectedId();
  6094. if (typeof this.project == 'undefined') return false;
  6095. if (typeof this.project.files[file] == 'undefined') return false;
  6096. return this.project.files[file].tags = [];
  6097. }
  6098. /**
  6099. * Append tags into some rows
  6100. * @param {String} file - File Id
  6101. * @param {Number} row - Row index
  6102. * @param {String|String[]} tags - tags to set
  6103. * @returns {String[]} The current tags of the preferred row
  6104. */
  6105. Trans.prototype.appendTags = function(file, row, tags, options) {
  6106. return this.setTags(file, row, tags, {append:true, noRefresh:true})
  6107. }
  6108. /**
  6109. * HOT's CellRange object
  6110. * @typedef {Object} CellRange
  6111. * @property {Object} CellRange.from - The starting cell
  6112. * @property {Object} CellRange.to - The latest selected cell
  6113. * @property {Object} CellRange.highlight - The highlighted cell
  6114. * @example
  6115. * {
  6116. "highlight": {
  6117. "row": 8,
  6118. "col": 2
  6119. },
  6120. "from": {
  6121. "row": 8,
  6122. "col": 2
  6123. },
  6124. "to": {
  6125. "row": 10,
  6126. "col": 2
  6127. }
  6128. }
  6129. */
  6130. /**
  6131. * Set tag for each CellRange object
  6132. * @param {String|String[]} tagName - Tags to put into
  6133. * @param {CellRange[]} [cellRange=trans.grid.getSelectedRange()] - Cell Range object
  6134. * @param {String} file - File Id
  6135. * @param {Object} options
  6136. * @param {Boolean} options.append - Whether to append or to override the current value with the new value
  6137. * @returns {Boolean} True on success
  6138. */
  6139. Trans.prototype.setTagForSelectedRow = function(tagName, cellRange, file, options) {
  6140. /* from cellRange object or from simple coords
  6141. cellRange :[{"start":{"row":4,"col":2},"end":{"row":4,"col":2}}]
  6142. or
  6143. result from trans.grid.getSelectedRange()
  6144. */
  6145. options = options||{};
  6146. if (typeof options.append == 'undefined' ) options.append = true;
  6147. file = file||this.getSelectedId();
  6148. if (Boolean(cellRange) == false) return false;
  6149. if (Array.isArray(cellRange) == false) return false;
  6150. for (let i=0; i<cellRange.length; i++) {
  6151. var cellStart = cellRange[i].start || cellRange[i].from;
  6152. var cellEnd = cellRange[i].end || cellRange[i].to;
  6153. if (typeof cellStart.row == 'undefined') continue
  6154. if (typeof cellEnd.row == 'undefined') continue
  6155. for (var row=cellStart.row; row <= cellEnd.row; row++) {
  6156. this.setTags(file, row, tagName, options);
  6157. }
  6158. }
  6159. this.grid.render();
  6160. return true;
  6161. }
  6162. /**
  6163. * Remove tags with cellRange object
  6164. * @param {String|String[]} tagName - Tags to put into
  6165. * @param {CellRange[]} [cellRange=trans.grid.getSelectedRange()] - Cell Range object
  6166. * @param {String} file - File Id
  6167. * @param {Object} options
  6168. * @returns {Boolean} True on success
  6169. */
  6170. Trans.prototype.removeTagForSelectedRow = function(tagName, cellRange, file, options) {
  6171. console.log("removeTagForSelectedRow", arguments);
  6172. /* from cellRange object or from simple coords
  6173. cellRange :[{"start":{"row":4,"col":2},"end":{"row":4,"col":2}}]
  6174. or
  6175. result from trans.grid.getSelectedRange()
  6176. */
  6177. options = options||{};
  6178. options.append = options.append||true;
  6179. file = file||this.getSelectedId();
  6180. if (Boolean(cellRange) == false) return false;
  6181. if (Array.isArray(cellRange) == false) return false;
  6182. for (let i=0; i<cellRange.length; i++) {
  6183. var cellStart = cellRange[i].start || cellRange[i].from;
  6184. var cellEnd = cellRange[i].end || cellRange[i].to;
  6185. if (typeof cellStart.row == 'undefined') continue
  6186. if (typeof cellEnd.row == 'undefined') continue
  6187. for (var row=cellStart.row; row <= cellEnd.row; row++) {
  6188. this.removeTags(file, row, tagName, options);
  6189. }
  6190. }
  6191. this.grid.render();
  6192. return true;
  6193. }
  6194. /**
  6195. * Check whether a row has tags or not
  6196. * @param {String|String[]} tags - Check whether a row has one of these tags
  6197. * @param {Number|Number[]} row - Row(s) to check for
  6198. * @param {String} file - the file Id
  6199. * @returns {Boolean} true on success
  6200. */
  6201. Trans.prototype.hasTags = function(tags, row, file) {
  6202. if (!tags) return false;
  6203. if (typeof row == 'undefined') return false;
  6204. file = file || this.getSelectedId();
  6205. var fileObj = this.getObjectById(file);
  6206. if (!fileObj) return false;
  6207. if (!fileObj.tags) return false;
  6208. if (!Array.isArray(fileObj.tags[row])) return false;
  6209. if (!Array.isArray(tags)) tags = [tags]
  6210. try {
  6211. for (var i in tags) {
  6212. if (fileObj.tags[row].includes(tags[i])) return true;
  6213. }
  6214. return false;
  6215. } catch (e) {
  6216. return false;
  6217. }
  6218. }
  6219. /**
  6220. * Display alert
  6221. * @async
  6222. * @param {String} text - Text to display
  6223. * @param {Number} [timeout=3000] - Timeout in miliseconds
  6224. */
  6225. Trans.prototype.alert = async function(text, timeout) {
  6226. timeout = timeout||3000;
  6227. $("#appInfo").attr("title", text);
  6228. return new Promise((resolve, reject) => {
  6229. $("#appInfo").tooltip({
  6230. content:function() {
  6231. return text;
  6232. },
  6233. show: {
  6234. effect: "slideDown",
  6235. duration: 200
  6236. },
  6237. hide: {
  6238. effect: "fade",
  6239. delay: 250
  6240. },
  6241. position: {
  6242. my: "left top",
  6243. at: "left bottom",
  6244. of: "#table"
  6245. },
  6246. open: function( event, ui ) {
  6247. setTimeout(function(){
  6248. $("#appInfo").tooltip("close");
  6249. $("#appInfo").attr("title", "");
  6250. resolve();
  6251. }, timeout);
  6252. }
  6253. });
  6254. $("#appInfo").tooltip("open");
  6255. })
  6256. }
  6257. /**
  6258. * Refresh the grid
  6259. * @param {Object} options
  6260. * @param {Boolean} options.rebuild - Whether or not to rebuild the grid
  6261. * @param {Function} options.onDone - Function to run when the process is done
  6262. */
  6263. Trans.prototype.refreshGrid = function(options) {
  6264. options = options||{};
  6265. options.rebuild = options.rebuild||false;
  6266. if(trans.getSelectedId()) {
  6267. trans.data = trans?.project?.files[trans.getSelectedId()].data;
  6268. }
  6269. if (!(trans.data)) trans.data = [[null]];
  6270. if (trans.data.length == 1) {
  6271. if (Array.isArray(trans.data[0]) == false) trans.data = [[null]]
  6272. if (Boolean(trans.data[0][0]) == false) trans.data = [[null]]
  6273. }
  6274. if (trans.data.length == 0) trans.data = [[null]]
  6275. if(trans.getSelectedId()) {
  6276. // re assign data in to trans.project.files[trans.getSelectedId()].data
  6277. // in case data is detached;
  6278. trans.project.files[trans.getSelectedId()].data = trans.data;
  6279. }
  6280. if (typeof options.onDone == 'function') {
  6281. trans.grid.addHookOnce('afterRender', function() {
  6282. options.onDone.call(trans.grid);
  6283. });
  6284. }
  6285. if (options.rebuild) {
  6286. trans.grid.destroy();
  6287. trans.initTable();
  6288. return true;
  6289. }
  6290. trans.grid.updateSettings({
  6291. data : trans.data,
  6292. colHeaders : trans.colHeaders,
  6293. columns : trans.columns
  6294. });
  6295. // TODO: for performance, should cache this:
  6296. // https://handsontable.com/docs/comments/#basic-example
  6297. trans.loadComments();
  6298. }
  6299. /**
  6300. * Open note at cell
  6301. * @param {Object} cell
  6302. * @param {Number} cell.row - Row ID
  6303. * @param {Number} cell.col - Column ID
  6304. */
  6305. Trans.prototype.editNoteAtCell = function(cell) {
  6306. /*
  6307. cel : {row : 0, col: 0}
  6308. */
  6309. if (typeof cell == 'undefined') {
  6310. try{
  6311. cell = trans.grid.getSelectedRange()[0]['highlight'];
  6312. } catch (error) {
  6313. console.log(error);
  6314. return false;
  6315. }
  6316. }
  6317. var hotComment = trans.grid.getPlugin('comments');
  6318. hotComment.showAtCell(cell.row, cell.col);
  6319. $(".htCommentTextArea").trigger("click");
  6320. $(".htCommentTextArea").focus();
  6321. }
  6322. /**
  6323. * Remove note at selected cell
  6324. * @param {CellRange[]} selection - Selected cell(s)
  6325. */
  6326. Trans.prototype.removeNoteAtSelected = function(selection) {
  6327. console.log("trans.removeNoteAtSelected");
  6328. if (typeof selection == 'undefined') {
  6329. selection = trans.grid.getSelectedRange()
  6330. }
  6331. if (Boolean(selection) == false) {
  6332. console.log("no selection were made");
  6333. return false;
  6334. }
  6335. console.log(selection);
  6336. var minRow = Math.min(selection[0]['from']['row'], selection[0]['to']['row']);
  6337. var maxRow = Math.max(selection[0]['from']['row'], selection[0]['to']['row']);
  6338. var minCol = Math.min(selection[0]['from']['col'], selection[0]['to']['col']);
  6339. var maxCol = Math.max(selection[0]['from']['col'], selection[0]['to']['col']);
  6340. var hotComment = trans.grid.getPlugin('comments');
  6341. for (var y=minRow; y<=maxRow; y++) {
  6342. for (var x=minCol; x<=maxCol; x++) {
  6343. hotComment.removeCommentAtCell(y, x);
  6344. }
  6345. }
  6346. }
  6347. /**
  6348. * Draw grid's context menu to display translator list
  6349. */
  6350. Trans.prototype.drawGridTranslatorMenu = function() {
  6351. if (!this.translatorContextMenuIsInitialized) {
  6352. console.log("Initializing translator context menu");
  6353. // init translatorContextMenu
  6354. TranslatorEngine.translators = TranslatorEngine.translators || {};
  6355. if (empty(TranslatorEngine.translators)) return;
  6356. this.gridContextMenu.translateUsing.submenu.items = [];
  6357. for (var id in TranslatorEngine.translators) {
  6358. (()=> {
  6359. var thisId = id;
  6360. var thisEngine = TranslatorEngine.translators[id];
  6361. this.gridContextMenu.translateUsing.submenu.items.push({
  6362. key: `translateUsing:${thisId}`,
  6363. name: thisEngine.name,
  6364. callback : ()=> {
  6365. this.translateSelection(undefined, {translatorEngine:thisEngine});
  6366. },
  6367. hidden : ()=> {
  6368. if (this.grid.isColumnHeaderSelected()) return true;
  6369. if (this.grid.isRowHeaderSelected()) return true;
  6370. }
  6371. })
  6372. })()
  6373. }
  6374. this.translatorContextMenuIsInitialized = true;
  6375. }
  6376. return this.gridContextMenu;
  6377. }
  6378. /**
  6379. * Get the context menu object of the grid
  6380. */
  6381. Trans.prototype.getGridContextMenu = function() {
  6382. this.drawGridTranslatorMenu();
  6383. return this.gridContextMenu;
  6384. }
  6385. Trans.prototype.updateGridContextMenu = function(menu) {
  6386. console.log("updateGridContextMenu", menu);
  6387. if (!this.gridContextMenuIsModified) return;
  6388. }
  6389. Trans.prototype.modifyGridContextMenu = function(menu) {
  6390. this.gridContextMenuIsModified = true;
  6391. }
  6392. /**
  6393. * Asynchronously calculates the height of the table based on the provided data.
  6394. * @param {Array} [data=this.data] - The data to calculate the table height from. Defaults to the data stored in the Trans instance.
  6395. * @returns {Promise<number>} - A Promise that resolves with the calculated table height.
  6396. */
  6397. Trans.prototype.calculateTableHeights = async function(data = this.data) {
  6398. console.log("Calculating table height");
  6399. const lineHeight = 23;
  6400. const padding = 2*lineHeight;
  6401. if (!data?.length) return lineHeight;
  6402. function calculateTableHeight(table) {
  6403. let totalLines = 0;
  6404. // Step 1: Find the maximum number of lines in any cell
  6405. for (let i = 0; i < table.length; i++) {
  6406. if (!table[i]?.length) continue;
  6407. let thisLength = 1;
  6408. for (let j = 0; j < table[i].length; j++) {
  6409. if (!table[i][j]) continue;
  6410. const lines = table[i][j].split('\n').length;
  6411. if (lines > thisLength) {
  6412. thisLength = lines;
  6413. }
  6414. }
  6415. totalLines += thisLength;
  6416. }
  6417. // Step 2: Calculate the height
  6418. if (totalLines < table.length) return table.length;
  6419. return totalLines;
  6420. }
  6421. if (data.length < 1000) {
  6422. return (calculateTableHeight(data) * lineHeight) + padding;
  6423. }
  6424. const Handler = require("www/js/CommonWorker.js").Handler
  6425. const workerData= {
  6426. command :"calculateHeights",
  6427. data : data,
  6428. options: {
  6429. logTarget: "ui"
  6430. }
  6431. }
  6432. const handler = new Handler("./www/js/trans.worker.js", workerData)
  6433. const result = await handler.getResult();
  6434. if (!result?.result) return lineHeight;
  6435. return (result.result * lineHeight) + padding;
  6436. }
  6437. /**
  6438. * Initialization of the grid
  6439. * @param {Object} options
  6440. */
  6441. Trans.prototype.initTable = function(options) {
  6442. options = options||{};
  6443. //trans.removeDuplicates();
  6444. var container = document.getElementById('table');
  6445. if (Boolean(container) == false) return false;
  6446. Handsontable.dom.addEvent(container, 'blur', function(event) {
  6447. console.log("event", event);
  6448. });
  6449. Handsontable.debugLevel = common.debugLevel();
  6450. /**
  6451. * Instance of the Handsontable object
  6452. * @type {Handsontable}
  6453. * @see https://handsontable.com/docs/api/core/
  6454. */
  6455. this.grid = new Handsontable(container, {
  6456. data : trans.data,
  6457. comments : true,
  6458. rowHeaders : true,
  6459. colHeaders : trans.colHeaders,
  6460. columns : trans.columns,
  6461. formulas : false,
  6462. search : true,
  6463. outsideClickDeselects:false,
  6464. viewportColumnRenderingOffset:15,
  6465. maxCols: Trans.maxCols,
  6466. //autoRowSize: true, // setting this to true will cause jumpy bugs
  6467. // dragToScroll:false,
  6468. // autoRowSize: {syncLimit: 1000},
  6469. autoRowSize: false,
  6470. //trimWhitespace : false,
  6471. //fixedColumnsLeft: 1,
  6472. minSpareRows : 1,
  6473. filters : false,
  6474. dropdownMenu : false,
  6475. autoWrapRow : true,
  6476. manualColumnMove: true,
  6477. //width: 806,
  6478. //height: 487,
  6479. manualColumnResize: true,
  6480. //copyPaste : true,
  6481. copyPaste: { columnsLimit: 15, rowsLimit: 100000 },
  6482. beforeChange: function (changes, source) {
  6483. console.log('beforeChange', arguments);
  6484. console.log(changes);
  6485. console.log(source);
  6486. // changes: [0] = row; [1]=col; [2]=initial value; [3]=changed value
  6487. if (typeof trans.selectedData == 'undefined') return console.warn("unknown selected data");
  6488. for (var i=0; i<changes.length; i++) {
  6489. // check if editing the key row
  6490. if (changes[i][1]==0 && changes[i][0] < (trans.grid.getData().length - 1)) {
  6491. console.log(JSON.stringify(changes, undefined, 2));
  6492. trans.alert(t("You should not edit key value"));
  6493. return false;
  6494. }
  6495. if (changes[i][1] != 0) continue; // skip if not first index
  6496. // reject if same key is found
  6497. if (Boolean(changes[i][3]) == false) return false;
  6498. if (trans.isKeyExistOn(changes[i][3])) {
  6499. trans.alert(t("Ilegal value")+" <b>'"+changes[i][3]+"'</b> "+t("That value already exist!"));
  6500. return false;
  6501. }
  6502. //if (typeof trans.findIdByIndex(changes[i][2]) != 'undefined') delete trans.indexIds[changes[i][2]];
  6503. if (typeof trans.findIdByIndex(changes[i][2]) == 'number') delete trans.indexIds[changes[i][2]];
  6504. //trans.indexIds[changes[i][3]] = changes[i][0];
  6505. trans.selectedData.indexIds[changes[i][3]] = changes[i][0];
  6506. }
  6507. },
  6508. afterChange: function (changes, source) {
  6509. //console.log('afterChange');
  6510. //console.log(changes);
  6511. //console.log(source);
  6512. // incoming changes is array;
  6513. // changes[index][0] = row; changes[index][1]=col;
  6514. // changes[index][2]=previous value; changes[index][3] = new value;
  6515. //console.log("afterChange");
  6516. //console.log(arguments);
  6517. trans.gridIsModified(true);
  6518. if (changes == null) return true;
  6519. if (!trans.getSelectedId()) return true;
  6520. var isChanged = false;
  6521. var progress = trans.project.files[trans.getSelectedId()].progress;
  6522. //var activeCellIndex = 0; //index changes which is active in preview
  6523. for (var cell in changes) {
  6524. if (Array.isArray(changes[cell]) == false) continue;
  6525. if (!trans.data[changes[cell][0]][0]) continue; // do not process if first row is blank or null
  6526. changes[cell][2]=changes[cell][2]||"";
  6527. changes[cell][3]=changes[cell][3]||"";
  6528. // detect current cell from array of changes
  6529. if (changes[cell][0] == trans.lastSelectedCell[0] && changes[cell][1] == trans.lastSelectedCell[1]) {
  6530. //activeCellIndex = cell;
  6531. trans.textEditorSetValue(changes[cell][3]);
  6532. }
  6533. if (changes[cell][2].length>0 && changes[cell][3].length==0) {
  6534. // removing
  6535. if (trans.countFilledCol(changes[cell][0]) == 0) {
  6536. // substracting progress
  6537. if (progress.translated <= 0) continue;
  6538. progress.translated --;
  6539. if (progress.length > 0) {
  6540. progress.percent = progress.translated/progress.length*100;
  6541. } else {
  6542. progress.percent = 0;
  6543. }
  6544. isChanged = true;
  6545. }
  6546. } else if (changes[cell][2].length==0 && changes[cell][3].length>0) {
  6547. // adding
  6548. if (trans.countFilledCol(changes[cell][0]) == 1) {
  6549. // if after adding a value, translation count in this row is exactly 1, than this is new translation for this row
  6550. // adding progress
  6551. if (progress.translated >= progress.length) continue;
  6552. progress.translated ++;
  6553. if (progress.length > 0) {
  6554. progress.percent = progress.translated/progress.length*100;
  6555. } else {
  6556. progress.percent = 0;
  6557. }
  6558. isChanged = true;
  6559. }
  6560. }
  6561. }
  6562. if (isChanged) {
  6563. var result ={};
  6564. result[trans.getSelectedId()] = progress;
  6565. trans.evalTranslationProgress(trans.getSelectedId(), result);
  6566. }
  6567. trans.trigger("afterCellChange", [changes, source]);
  6568. },
  6569. beforeContextMenuShow : (menu) => {
  6570. trans.updateGridContextMenu(menu)
  6571. },
  6572. contextMenu: {
  6573. items: trans.getGridContextMenu()
  6574. },
  6575. cells: function (row, col, prop) {
  6576. var cellProperties = {};
  6577. if (col==0) {
  6578. if (typeof trans.data[row] == 'undefined') return cellProperties;
  6579. if (trans.data[row][col] !== null && trans.data[row][col]!=="") {
  6580. cellProperties.readOnly = true;
  6581. }
  6582. }
  6583. return cellProperties;
  6584. },
  6585. afterSelection: function(row, column, row2, column2, preventScrolling, selectionLayerLevel) {
  6586. //HOT jumpy when selected, not caused by this
  6587. /**
  6588. * Triggered after grid selection
  6589. * @event Trans#beforeProcessSelection
  6590. * @param {arguments} arguments
  6591. */
  6592. console.log("do after selection", arguments);
  6593. trans.trigger("beforeProcessSelection", arguments);
  6594. trans.doAfterSelection(row, column, row2, column2);
  6595. // tried this, not fixed the jumpy:
  6596. //preventScrolling.value = true;
  6597. },
  6598. beforeInit: function() {
  6599. console.log("running before init");
  6600. },
  6601. afterInit: function() {
  6602. trans.buildIndex();
  6603. },
  6604. beforeColumnMove: function(columns, target) {
  6605. console.log("beforeColumnMove");
  6606. if (target == 0) return false;
  6607. if (columns.includes(0) == true) return false;
  6608. /*
  6609. console.log(columns);
  6610. console.log(target);
  6611. trans.moveColumn(columns, target);
  6612. */
  6613. trans.moveColumn(columns, target);
  6614. return true;
  6615. },
  6616. afterColumnMove: function(columns, target) {
  6617. console.log("afterColumnMove");
  6618. if (target == 0) return false;
  6619. if (columns.includes(0) == true) return false;
  6620. //console.log(columns);
  6621. //console.log(target);
  6622. //trans.walkToAllFile();
  6623. return true;
  6624. },
  6625. afterSetCellMeta: function(row, col, source, val){
  6626. if(source == 'comment'){
  6627. var thisData = trans.getSelectedObject();
  6628. if (!thisData) return true;
  6629. if (val == undefined) {
  6630. try {
  6631. delete thisData.comments[row][col];
  6632. }
  6633. catch(err) {
  6634. console.log("unable to delete comment.\nData row:"+row+", col:"+col+" is not exist on trans.project.files[trans.getCurrentID].comments!");
  6635. }
  6636. return true;
  6637. } else {
  6638. thisData.comments = thisData.comments||[];
  6639. thisData.comments[row] = thisData.comments[row]||[];
  6640. thisData.comments[row][col] = val.value;
  6641. return true;
  6642. }
  6643. }
  6644. },
  6645. afterRender:function(isForced) {
  6646. if (isForced == true) return true; // natural render
  6647. if ($("#currentCellText").is(":focus")) {
  6648. //console.log("eval focus");
  6649. var visibleCell = ui.getCurrentEditedCellElm();
  6650. if (visibleCell !== false) {
  6651. $("#table .currentCell").removeClass("currentCell");
  6652. visibleCell.addClass("currentCell");
  6653. }
  6654. }
  6655. },
  6656. afterRenderer:function(TD, row, column, prop, val, cellProperties) {
  6657. // fired after each cell rendered
  6658. // for performance do not put too much thing here
  6659. TD.setAttribute("data-coord", row+"-"+column);
  6660. if (column > 0) {
  6661. if (trans.getOption("gridInfo")?.isRuleActive) {
  6662. if (trans.getOption("gridInfo")?.viewOrganicCellMarker && trans.isOrganicCell(row, column)) {
  6663. $(TD).addClass("organic"); // organic is obviously viewed
  6664. } else if (trans.getOption("gridInfo")?.viewTrail && trans.isVisitedCell(row, column)) {
  6665. $(TD).addClass("viewed");
  6666. }
  6667. }
  6668. }
  6669. if (column > 0) return; // only render tag for the first column ... the rest is same
  6670. // draw last row
  6671. if (row >= trans.data.length - 1) $(TD).addClass("newKeyField");
  6672. //console.log($thisTR);
  6673. },
  6674. afterGetColHeader: function(col, TH) {
  6675. if (col==-1) $(TH).attr("data-role", "tablecorner")
  6676. },
  6677. afterGetRowHeader: function(row, TH) {
  6678. var $thisTH = $(TH)
  6679. var $thisTR = $(TH).closest("tr");
  6680. var $rowInfo = $thisTH.find(".rowInfo");
  6681. if (!$rowInfo.length) {
  6682. let $wrapper = $thisTH.find(">div");
  6683. $rowInfo = $('<span class="rowInfo"></span>').appendTo($wrapper)
  6684. }
  6685. //append info view element
  6686. (()=> {
  6687. // render tags
  6688. if (typeof trans.selectedData == 'undefined') return;
  6689. if (Array.isArray(trans.selectedData.tags) == false) return;
  6690. if (Array.isArray(trans.selectedData.tags[row]) == false) return;
  6691. if ($thisTR.hasClass("tagRendered") == true) return;
  6692. let shadowPart = [];
  6693. let borderOffset = 0;
  6694. for (var i=0; i<trans.selectedData.tags[row].length; i++) {
  6695. //console.log($thisTR.find("th"));
  6696. var segmTag = trans.selectedData.tags[row][i];
  6697. if (typeof consts.tagColor[segmTag] !== 'undefined') {
  6698. borderOffset+=consts.tagStripThickness;
  6699. shadowPart.push('inset '+borderOffset+'px 0px 0px 0px '+consts.tagColor[segmTag]);
  6700. }
  6701. $thisTH.addClass("tag-"+trans.selectedData.tags[row][i]);
  6702. }
  6703. if (shadowPart.length != 0) {
  6704. $thisTH.css("box-shadow", shadowPart.join(","));
  6705. }
  6706. $thisTR.addClass("hasTag");
  6707. $thisTR.addClass("tagRendered");
  6708. })()
  6709. // render context translation mark
  6710. if (ui.translationByContext) {
  6711. (()=> {
  6712. if (!trans.rowHasMultipleContext(row, trans.selectedData)) return;
  6713. $thisTH.addClass("hasMC")
  6714. if (ui.translationByContext.rowHasContextTranslation(row, trans.selectedData)) $thisTH.addClass("hasTC");
  6715. })()
  6716. }
  6717. // render row info
  6718. (()=>{
  6719. let rowInfoText = trans.getRowInfoText(row);
  6720. if (rowInfoText) {
  6721. $rowInfo.text(rowInfoText)
  6722. } else {
  6723. $rowInfo.text("")
  6724. }
  6725. })()
  6726. },
  6727. afterCreateRow:function(index, amount, source) {
  6728. var thisFile = trans.getSelectedId();
  6729. if (Boolean(thisFile) == false) return false;
  6730. trans.evalTranslationProgress([thisFile]);
  6731. },
  6732. beforePaste:function(data, coords) {
  6733. //console.log("beforePaste triggered");
  6734. //console.log(coords);
  6735. //console.log(arguments);
  6736. },
  6737. afterScrollVertically() {
  6738. // some part of the bottom most part are sometimes clipped, and no further scrolling is possible
  6739. // while some data are hidden beyound scrollable area
  6740. // this is the hackish solution for that.
  6741. // todo ... add 20% scroll ui.bumpGridScroll()
  6742. if (this.skipScrollEvent) return;
  6743. if (this._scrollTimer) clearTimeout(this._scrollTimer)
  6744. this._scrollTimer = setTimeout(async ()=> {
  6745. var elmHeight = $("#table .wtHolder>*:eq(0)").height();
  6746. if (elmHeight - $("#table .wtHolder").scrollTop() - $("#table .wtHolder").height() <= 0) {
  6747. //console.log("reached bottom");
  6748. if (!$(".newKeyField").visible()) {
  6749. this.render();
  6750. this.skipScrollEvent = true;
  6751. trans.grid.scrollViewportTo(ui.getFirstFullyVisibleRow());
  6752. await common.wait(50);
  6753. this.skipScrollEvent = false;
  6754. }
  6755. //this.loadData(trans.data);
  6756. //if (!$(".newKeyField").visible()) this.addHeight(400);
  6757. }
  6758. }, 200)
  6759. }
  6760. });
  6761. Handsontable.dom.addEvent($("#quickFind")[0], 'input', function (event) {
  6762. var search = trans.grid.getPlugin('search');
  6763. var queryResult = search.query(this.value);
  6764. console.log(queryResult);
  6765. trans.grid.render();
  6766. });
  6767. /**
  6768. * Handle row AutoRowSize plugin
  6769. * https://handsontable.com/docs/7.4.2/AutoRowSize.html
  6770. * Known problem: The grid will jumpy if row size is not complete when user try to click the grid.
  6771. *
  6772. */
  6773. trans.grid.autoRowSize = trans.grid.getPlugin('autoRowSize');
  6774. // hot & walkOnTable custom hook
  6775. trans.grid.isFixedHeight = true;
  6776. trans.grid.view.wt.ignoreAdjustElementSize = false;
  6777. /**
  6778. * Saves row heights to the local storage for the specified file ID.
  6779. * @param {string} [fileId=trans.getSelectedId()] - The file ID to save row heights for.
  6780. * @returns {Promise<void>} - A Promise that resolves when the row heights are saved.
  6781. */
  6782. const saveRowHeights = async function(fileId=trans.getSelectedId()) {
  6783. if (!trans.grid.getSettings().autoRowSize) return;
  6784. if (trans.grid.isFixedHeight) return;
  6785. if (trans.data?.length < 1000) return
  6786. console.log("Saving cache rowheights for ", fileId);
  6787. if (!trans?.localStorage) return;
  6788. console.log("Calculated row heights length ", trans.grid.autoRowSize.heights.length, "Current row length", trans.data.length);
  6789. if (trans.grid)
  6790. trans.localStorage.set(`${trans.getSelectedId()}?rowHeights`, trans.grid.autoRowSize.heights);
  6791. trans.localStorage.set(`${trans.getSelectedId()}?hiderDimension`, {
  6792. width:trans.grid.view.wt.wtTable.hider.style.width,
  6793. height:trans.grid.view.wt.wtTable.hider.style.height
  6794. })
  6795. }
  6796. // custom hooks
  6797. /**
  6798. * Loads row heights cache from local storage for the specified column range.
  6799. * @param {string} [colRange] - The column range to load row heights cache for.
  6800. * @returns {Promise<boolean>} - A Promise that resolves with a boolean indicating if the cache was loaded successfully.
  6801. */
  6802. trans.grid.loadRowHeightsCache = async function(colRange) {
  6803. if (!trans.grid.getSettings().autoRowSize) return;
  6804. if (trans.grid.isFixedHeight) return;
  6805. if (trans.data?.length < 1000) return
  6806. console.log("start counting rows height on colRange", colRange)
  6807. if (!trans?.localStorage) return;
  6808. let cache = await trans.localStorage.get(`${trans.getSelectedId()}?rowHeights`);
  6809. console.log("Cache row height is", cache);
  6810. if (!cache?.length) return;
  6811. trans.grid.autoRowSize.heights = await trans.localStorage.get(`${trans.getSelectedId()}?rowHeights`);
  6812. trans.grid.autoRowSize.inProgress = false;
  6813. trans.grid.cachedDimension = await trans.localStorage.get(`${trans.getSelectedId()}?hiderDimension`);
  6814. // hooks on walkontable
  6815. // trans.grid.view.wt.getCachedDimension = function() {
  6816. // if (!trans.grid.cachedDimension) return;
  6817. // if (trans.grid.cachedDimension) {
  6818. // return trans.grid.cachedDimension;
  6819. // }
  6820. // }
  6821. return true;
  6822. }
  6823. trans.grid.onCalculateAllRowsHeightStart = async function() {
  6824. ui.tableCornerShowLoading("Counting total rows height. The grid may jumpy while in counting process.");
  6825. }
  6826. trans.grid.onCalculateAllRowsHeightEnd = async function() {
  6827. if (trans.data?.length < 1000) return
  6828. ui.tableCornerHideLoading();
  6829. // cache result
  6830. saveRowHeights();
  6831. }
  6832. trans.off("beforeSelectFile");
  6833. /**
  6834. * Event handler for the "beforeSelectFile" event.
  6835. * @param {Event} evt - The event object.
  6836. * @param {Array} fileIds - An array of file IDs.
  6837. */
  6838. trans.on("beforeSelectFile", function(evt, fileIds) {
  6839. console.log("%cbeforeSelectFile", "color:pink", fileIds);
  6840. if (!fileIds?.[0]) return;
  6841. if (fileIds[0] == fileIds[1]) return; // no change made
  6842. saveRowHeights(fileIds[0]);
  6843. })
  6844. /**
  6845. * Sets the fixed table height based on the provided data.
  6846. * @param {Array} [data=[]] - The data to calculate the table height from.
  6847. * @returns {Promise<void>} - A Promise that resolves when the table height is set.
  6848. */
  6849. trans.grid.setFixedTableHeightByData = async function(data = []) {
  6850. if (!trans.grid.isFixedHeight) return;
  6851. if (!data?.length) return;
  6852. // set fixed height first with a large enough data for responsiveness
  6853. // assume every row has 10 line
  6854. let initialHeight = data.length * 22 *10
  6855. const currentId = trans.getSelectedId();
  6856. trans.grid.setFixedTableHeight(initialHeight);
  6857. // begin counting the actual height
  6858. const calculatedHeight = await trans.calculateTableHeights(data);
  6859. if (trans.getSelectedId() !== currentId) return; // exit if the table has changed during processing
  6860. console.log("Setting actual height", calculatedHeight);
  6861. trans.grid.setFixedTableHeight(calculatedHeight);
  6862. }
  6863. /**
  6864. * Sets the fixed table height.
  6865. * @param {number|string|boolean} height - The height value. If a string, it should include "px".
  6866. * @returns {string|undefined} - The set height value, or undefined if height is false.
  6867. */
  6868. trans.grid.setFixedTableHeight = function(height) {
  6869. if (!trans.grid.isFixedHeight) return;
  6870. if (typeof height == "string" && height.includes("px")) {
  6871. trans.grid.view.wt.wtTable.hider.style.height = height;
  6872. trans.grid.view.wt.ignoreAdjustElementSize = true;
  6873. } else if (typeof height == "number"){
  6874. trans.grid.view.wt.wtTable.hider.style.height = height+"px";
  6875. trans.grid.view.wt.ignoreAdjustElementSize = true;
  6876. } else if (typeof height == "boolean" && height === false) {
  6877. trans.grid.view.wt.ignoreAdjustElementSize = false;
  6878. }
  6879. return trans.grid.view.wt.wtTable.hider.style.height;
  6880. }
  6881. /**
  6882. * Adds height to the table.
  6883. * @param {number} num - The amount of height to add.
  6884. * @returns {number} - The new height after adding the specified amount.
  6885. */
  6886. trans.grid.addHeight = function(num=0) {
  6887. const currentHeight = parseInt(trans.grid.view.wt.wtTable.hider.style.height);
  6888. trans.grid.view.wt.wtTable.hider.style.height = currentHeight+num+"px";
  6889. return trans.grid.view.wt.wtTable.hider.style.height;
  6890. }
  6891. /**
  6892. * Gets the height of the table.
  6893. * @returns {string} - The height of the table.
  6894. * @see https://handsontable.com/docs/7.4.2/Core.html#getTableHeight
  6895. * @since 4.7.15
  6896. * @example
  6897. * var tableHeight
  6898. * tableHeight
  6899. * // returns "500px"
  6900. */
  6901. trans.grid.getTableHeight = function() {
  6902. return trans.grid.view.wt.wtTable.hider.style.height;
  6903. }
  6904. /**
  6905. * Check whether the current selection is selected through column header
  6906. * @returns {Boolean}
  6907. */
  6908. trans.grid.isColumnHeaderSelected = function() {
  6909. return Boolean($(".htCore thead th.ht__active_highlight").length);
  6910. }
  6911. /**
  6912. * Checks if a row header is selected.
  6913. * @returns {boolean} - True if a row header is selected, false otherwise.
  6914. */
  6915. trans.grid.isRowHeaderSelected = function() {
  6916. return Boolean($(".htCore tr th.ht__active_highlight").length);
  6917. }
  6918. /**
  6919. * Inserts a column to the right of the specified position.
  6920. * @param {string} [colName="New Col"] - The name of the new column.
  6921. * @param {number} [pos] - The position to insert the column. If not provided, the position will be selected from the currently selected cell.
  6922. * @returns {void} - This function does not return a value.
  6923. */
  6924. trans.grid.insertColumnRight = function(colName, pos) {
  6925. if (trans.columns.length >= Trans.maxCols) {
  6926. alert(t("The maximum number of columns for this project has been reached, so you cannot add any more."))
  6927. return;
  6928. }
  6929. colName = colName||"New Col";
  6930. var getCol = pos||trans.grid.getSelected()[0][1];
  6931. var getColSet = trans.columns.length;
  6932. trans.columns.push({});
  6933. common.arrayExchange(trans.columns, getColSet, getCol + 1);
  6934. common.arrayInsert(trans.colHeaders, getCol+1, colName);
  6935. //batchArrayInsert(trans.data, getCol+1, null);
  6936. console.log(trans.columns);
  6937. trans.insertCell(getCol+1, null);
  6938. trans.grid.updateSettings({
  6939. colHeaders:trans.colHeaders
  6940. })
  6941. }
  6942. /**
  6943. * Sets the width of the specified column.
  6944. * @param {number} colIndex - The index of the column to set the width for.
  6945. * @param {number} newWidth - The new width value.
  6946. * @returns {void} - This function does not return a value.
  6947. */
  6948. trans.grid.setColWidth = function(colIndex, newWidth) {
  6949. if (!trans.columns[colIndex]) return;
  6950. trans.columns[colIndex].width = newWidth;
  6951. trans.refreshGrid();
  6952. }
  6953. }
  6954. /*
  6955. hot2.updateSettings({
  6956. cells: function (row, col) {
  6957. var cellProperties = {};
  6958. if (hot2.getData()[row][col] === 'Nissan') {
  6959. cellProperties.readOnly = true;
  6960. }
  6961. return cellProperties;
  6962. }
  6963. });
  6964. */
  6965. /**
  6966. * Find a key string, then insert a text into the adjacent cell
  6967. * Starting from 5.1 this function will strips carriage returns from `find`
  6968. * @param {String} find - String to find.
  6969. * @param {String} values - Text to put into
  6970. * @param {Number} columns - Column ID to put the values into
  6971. * @param {Object} indexes - index object or addresses
  6972. * @param {Object} options
  6973. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the existing text on the destination cell or not
  6974. * @param {String[]} [options.files=this.getAllFiles()] - Selected files
  6975. * @param {Boolean} [options.keyColumn=0] - Key column id
  6976. * @param {Boolean} [options.lineByLine=false] - to set the search mode in line by line mode
  6977. * @since 4.7.15
  6978. */
  6979. Trans.prototype.findAndInsertWithIndexes = function(find="", value, columns, indexes, options) {
  6980. //console.log("findAndInsertWithIndexes", arguments);
  6981. columns = columns||1;
  6982. options = options||{};
  6983. find ||= "";
  6984. options.overwrite = options.overwrite||false;
  6985. options.files = options.files||[];
  6986. options.keyColumn = options.keyColumn || this.keyColumn || 0;
  6987. options.insensitive = options.insensitive || false;
  6988. options.lineByLine = options.lineByLine || false;
  6989. options.customFilter;
  6990. indexes = indexes || this._tempIndexes;
  6991. if (typeof options.ignoreNewLine == "undefined") options.ignoreNewLine = true;
  6992. if (options.files.length == 0) { // that means ALL!
  6993. options.files = this.getAllFiles();
  6994. }
  6995. var result = {
  6996. keyword :find,
  6997. count :0,
  6998. executionTime:0,
  6999. files :{}
  7000. };
  7001. var indexObjects = this.getFromIndexes(find, indexes, options.customFilter);
  7002. //console.log("---indexObjects", indexObjects);
  7003. if (!indexObjects && find.includes("\r")) {
  7004. // RETRY: strip-out carriage returns
  7005. find = find.replaceAll("\r", "");
  7006. result.find = find;
  7007. indexObjects = this.getFromIndexes(find, indexes, options.customFilter);
  7008. }
  7009. if (!indexObjects) return result;
  7010. //console.log("reach here");
  7011. for (let i=0; i<indexObjects.length; i++) {
  7012. let thisAddress = indexObjects[i];
  7013. var file = thisAddress.file;
  7014. var row = thisAddress.row;
  7015. if (options.ignoreNewLine) {
  7016. if (Boolean(this.project.files[file].lineBreak) !== false) {
  7017. find = common.replaceNewLine(find, this.project.files[file].lineBreak);
  7018. }
  7019. }
  7020. // not support case insensitive
  7021. /*
  7022. if (thisAddress?.rowObj?.length) {
  7023. // the newest Address object directly point to row's memory address
  7024. console.log("Found rowObject", thisAddress?.rowObj);
  7025. } else
  7026. */
  7027. if (typeof row == 'number') {
  7028. var thisRow = this.getData(file)[row];
  7029. if (!thisRow) continue;
  7030. if (options.filterTagMode == "blacklist") {
  7031. if (this.hasTags(options.filterTag, row, file)) continue;
  7032. } else if (options.filterTagMode == "whitelist") {
  7033. if (!this.hasTags(options.filterTag, row, file)) continue;
  7034. }
  7035. if (options.lineByLine) {
  7036. var currentText = thisRow[columns] || "";
  7037. var currentLines = currentText.replaceAll("\r", "").split("\n");
  7038. if (options.overwrite == false) {
  7039. if (Boolean(currentLines[thisAddress.line]) == true) continue;
  7040. }
  7041. currentLines[thisAddress.line] = value
  7042. thisRow[columns] = currentLines.join("\n");
  7043. } else {
  7044. // plain row by row
  7045. if (options.overwrite == false) {
  7046. if (Boolean(thisRow[columns]) == true) continue;
  7047. }
  7048. thisRow[columns] = value;
  7049. }
  7050. result.files[file] = result.files[file] || [];
  7051. result.files[file].push({
  7052. 'fullString':thisRow[columns],
  7053. 'row':row,
  7054. 'col':columns,
  7055. 'type':'cell',
  7056. 'lineIndex':null
  7057. });
  7058. result.count++;
  7059. }
  7060. }
  7061. return result;
  7062. }
  7063. /**
  7064. * Find a key string, then insert a text into the adjacent cell
  7065. * @param {String} find - String to find.
  7066. * @param {String} values - Text to put into
  7067. * @param {Number} columns - Column ID to put the values into
  7068. * @param {Object} options
  7069. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the existing text on the destination cell or not
  7070. * @param {String[]} [options.files=this.getAllFiles()] - Selected files
  7071. * @param {Boolean} [options.keyColumn=0] - Key column id
  7072. * @param {Boolean} [options.insensitive=false] - Whether the test is using insensitive case or not
  7073. */
  7074. Trans.prototype.findAndInsert = function(find, values, columns, options) {
  7075. // find key "find", put "values" to coloumn with index "columns"
  7076. // to all files inside trans.project.files
  7077. //console.log("trans.findAndInsert", arguments);
  7078. columns = columns||1;
  7079. options = options||{};
  7080. options.overwrite = options.overwrite||false;
  7081. options.files = options.files||[];
  7082. options.keyColumn = options.keyColumn || this.keyColumn || 0;
  7083. options.insensitive = options.insensitive || false;
  7084. if (typeof options.ignoreNewLine == "undefined") options.ignoreNewLine = true;
  7085. //console.log("incoming parameters : ");
  7086. //console.log(arguments);
  7087. if (options.files.length == 0) { // that means ALL!
  7088. options.files = this.getAllFiles();
  7089. }
  7090. var result = {
  7091. keyword :find,
  7092. count :0,
  7093. executionTime:0,
  7094. files :{}
  7095. };
  7096. for (let i=0; i<options.files.length; i++) {
  7097. let file = options.files[i];
  7098. if (options.ignoreNewLine) {
  7099. if (Boolean(this.project.files[file].lineBreak) !== false) {
  7100. find = common.replaceNewLine(find, this.project.files[file].lineBreak);
  7101. }
  7102. }
  7103. var row
  7104. if (options.insensitive) {
  7105. row = this.getRowIdByTextInsensitive(find, file)
  7106. } else {
  7107. row = this.findIdByIndex(find, file);
  7108. }
  7109. if (typeof row == 'number') {
  7110. var thisRow = this.getData(file)[row];
  7111. if (!thisRow) continue;
  7112. if (options.filterTagMode == "blacklist") {
  7113. if (this.hasTags(options.filterTag, row, file)) continue;
  7114. } else if (options.filterTagMode == "whitelist") {
  7115. if (!this.hasTags(options.filterTag, row, file)) continue;
  7116. }
  7117. if (options.overwrite == false) {
  7118. if (Boolean(thisRow[columns]) == true) continue;
  7119. }
  7120. thisRow[columns] = values;
  7121. result.files[file] = result.files[file] || [];
  7122. result.files[file].push({
  7123. 'fullString':thisRow[columns],
  7124. 'row':row,
  7125. 'col':columns,
  7126. 'type':'cell',
  7127. 'lineIndex':null
  7128. });
  7129. result.count++;
  7130. }
  7131. }
  7132. return result;
  7133. }
  7134. /**
  7135. * Find a key string, then insert a text into the adjacent cell using line-by-line algorithm
  7136. * @param {String} find - String to find.
  7137. * @param {String} values - Text to put into
  7138. * @param {Number} columns - Column ID to put the values into
  7139. * @param {Object} options
  7140. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the existing text on the destination cell or not
  7141. * @param {String[]} [options.files=this.getAllFiles()] - Selected files
  7142. * @param {Boolean} [options.keyColumn=0] - Key column id
  7143. * @param {Boolean} [options.insensitive=false] - Whether the test is using insensitive case or not
  7144. * @param {String} [options.newLine=\n] - New line character
  7145. * @param {Boolean} [options.stripCarriageReturn=\n] - Whether to strip charriage return character (\r) or not
  7146. */
  7147. Trans.prototype.findAndInsertLine = function(find, values, columns, options) {
  7148. // find key "find", put "values" to coloumn with index "columns"
  7149. // to all files inside trans.project.files
  7150. //console.log("findAndInsertLine:", arguments);
  7151. columns = columns||1;
  7152. options = options||{};
  7153. options.overwrite = options.overwrite||false;
  7154. options.files = options.files||[];
  7155. options.keyColumn = options.keyColumn||0;
  7156. options.newLine = options.newLine||undefined;
  7157. options.stripCarriageReturn = options.stripCarriageReturn||false;
  7158. if (options.stripCarriageReturn) {
  7159. find = common.stripCarriageReturn(find);
  7160. }
  7161. if (options.files.length == 0) { // that means ALL!
  7162. if (typeof trans.allFiles != 'undefined') {
  7163. options.files = trans.allFiles;
  7164. } else {
  7165. for (var file in trans.project.files) {
  7166. options.files.push(file);
  7167. }
  7168. trans.allFiles = options.files;
  7169. }
  7170. }
  7171. for (var i=0; i<options.files.length; i++) {
  7172. file = options.files[i];
  7173. var thisData = trans.project.files[file].data;
  7174. var thisNewLine = options.newLine||trans.project.files[file].lineBreak||"\n";
  7175. for (var row=0; row<thisData.length; row++) {
  7176. let keySegment
  7177. if (!thisData[row][options.keyColumn]) continue;
  7178. if (options.filterTagMode == "blacklist") {
  7179. if (this.hasTags(options.filterTag, row, file)) continue;
  7180. } else if (options.filterTagMode == "whitelist") {
  7181. if (!this.hasTags(options.filterTag, row, file)) continue;
  7182. }
  7183. thisData[row][options.keyColumn] = thisData[row][options.keyColumn]||"";
  7184. if (options.stripCarriageReturn) {
  7185. keySegment = thisData[row][options.keyColumn].replaceAll("\r", "").split("\n");
  7186. /*
  7187. var keySegment = thisData[row][options.keyColumn].split("\n").map(function(input) {
  7188. return common.stripCarriageReturn(input);
  7189. });
  7190. */
  7191. } else {
  7192. keySegment = thisData[row][options.keyColumn].split("\n");
  7193. }
  7194. if (keySegment.includes(find) == false) continue;
  7195. thisData[row][columns] = thisData[row][columns]||"";
  7196. var targetSegment = thisData[row][columns].replaceAll("\r", "").split("\n");
  7197. /*
  7198. var targetSegment = thisData[row][columns].split("\n").map(function(input) {
  7199. return common.stripCarriageReturn(input);
  7200. });
  7201. */
  7202. targetSegment = common.searchReplaceArray(keySegment, targetSegment, find, values, {overwrite:options.overwrite});
  7203. thisData[row][columns] = targetSegment.join(thisNewLine);
  7204. }
  7205. }
  7206. }
  7207. /**
  7208. * find key "find", put "values" to coloumn with index "columns"
  7209. * to all files inside trans.project.files
  7210. * @param {String} find - String to find.
  7211. * @param {String} values - Text to put into
  7212. * @param {Number} columns - Column ID to put the values into
  7213. * @param {Object} options
  7214. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the existing text on the destination cell or not
  7215. * @param {String[]} [options.files=this.getAllFiles()] - Selected files
  7216. * @param {Boolean} [options.ignoreNewLine] - Whether to ignore new line characters or not
  7217. */
  7218. Trans.prototype.findAndInsertByContext = function(find, values, columns, options) {
  7219. //console.log("trans.findAndInsertByContext:", arguments);
  7220. columns = columns||1;
  7221. options = options||{};
  7222. options.overwrite = options.overwrite||false;
  7223. options.files = options.files||[];
  7224. options.ignoreNewLine = options.ignoreNewLine||false;
  7225. if (options.files.length == 0) { // that means ALL!
  7226. options.files = this.getAllFiles();
  7227. }
  7228. for (let i=0; i<options.files.length; i++) {
  7229. let file = options.files[i];
  7230. var thisObj = this.getObjectById(file);
  7231. if (Boolean(thisObj) == false) continue;
  7232. if (Boolean(thisObj.context) == false) continue;
  7233. for (var row=0; row<thisObj.context.length; row++) {
  7234. var contextByRow = thisObj.context[row];
  7235. if (Array.isArray(contextByRow) == false) continue;
  7236. if (contextByRow.length < 1) continue;
  7237. if (Array.isArray(thisObj.data[row]) == false) continue;
  7238. for (var contextId=0; contextId<contextByRow.length; contextId++) {
  7239. if (find !== contextByRow[contextId]) continue;
  7240. // match found! assign value
  7241. if (options.overwrite == false) {
  7242. if (Boolean(thisObj.data[row][columns]) == true) continue;
  7243. }
  7244. thisObj.data[row][columns] = values;
  7245. }
  7246. }
  7247. }
  7248. }
  7249. /**
  7250. * Translate text with line-by-line algorithm
  7251. * @param {String} text - multilined text
  7252. * @param {Object} translationPair - Key pair translation object
  7253. */
  7254. Trans.prototype.translateTextByLine = function(text, translationPair, options) {
  7255. /*
  7256. translating text line by line by translationPair
  7257. text : multilined text
  7258. translationPair: object : {"key":"translation"}
  7259. output: translated text
  7260. todo : make line break type match original text
  7261. */
  7262. //console.log("trans.translateTextByLine", arguments);
  7263. if (typeof text !== 'string') return text;
  7264. if (text.length < 1) return text;
  7265. // Up to ver 3.8.21 blank text will returns original text
  7266. //var translated = text;
  7267. var translated = "";
  7268. var translatedLine = [];
  7269. var lines = text.replace(/(\r\n)/gm, "\n").split("\n");
  7270. //var lines = text.split("\n");
  7271. //console.log("lines are:", lines);
  7272. //console.log("%c-With translation pair:", "color:#0f0;", JSON.stringify(translationPair, undefined, 2))
  7273. for (var i=0; i<lines.length; i++) {
  7274. var line = lines[i];
  7275. //console.log("%c--Comparing:", "color:#0f0;", JSON.stringify(line))
  7276. if (translationPair[line]) {
  7277. translatedLine.push(translationPair[line]);
  7278. //console.log("%c--found", "color:#0f0;")
  7279. continue;
  7280. }
  7281. //console.log("%c--not found", "color:#0f0;")
  7282. // Up to ver 3.8.21 blank text will returns original text
  7283. //translatedLine.push(line);
  7284. translatedLine.push("");
  7285. }
  7286. //console.log("translatedLine:", translatedLine);
  7287. translated = translatedLine.join("\n");
  7288. //console.log("Result of trans.translateTextByLine", translated);
  7289. return translated;
  7290. }
  7291. /**
  7292. * translate from array obj
  7293. * @param {*} obj
  7294. * @param {Number} columns
  7295. * @param {Object} options
  7296. * @param {Number|'auto'} options.sourceColumn
  7297. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the existing text on the destination cell or not
  7298. * @param {Number} [options.sourceKeyColumn=0] - The source key column
  7299. * @param {String[]} [options.files=this.getAllFiles()] - Selected files
  7300. * @param {Boolean} [options.keyColumn=0] - Key column id
  7301. * @param {String} [options.newLine=\n] - New line character
  7302. * @param {Boolean} [options.stripCarriageReturn=\n] - Whether to strip charriage return character (\r) or not
  7303. */
  7304. Trans.prototype.translateFromArray = function(obj, columns, options) {
  7305. // translate from array obj
  7306. console.log("insert trans.translateFromArray", arguments);
  7307. columns = columns||1;
  7308. options = options||{};
  7309. options.sourceColumn = options.sourceColumn||"auto";
  7310. options.overwrite = options.overwrite||false;
  7311. options.files = options.files||[];
  7312. options.sourceKeyColumn = options.sourceKeyColumn||0;
  7313. options.keyColumn = options.keyColumn||0;
  7314. options.newLine = options.newLine||undefined;
  7315. options.stripCarriageReturn = options.stripCarriageReturn||false;
  7316. options.ignoreNewLine = true; // let's set to true;
  7317. //options.translationMethod = options.translationMethod||false;
  7318. obj = obj||[];
  7319. if (obj.length == 0) return false;
  7320. if (!options.indexes) {
  7321. if (options.files?.length == 0) {
  7322. options.files = this.getAllFiles();
  7323. }
  7324. options.indexes = this.buildIndexes(options.files, false);
  7325. }
  7326. for (var rowId=0; rowId<obj.length; rowId++) {
  7327. var translation;
  7328. var row = obj[rowId];
  7329. if (Boolean(row[options.sourceKeyColumn]) == false) continue;
  7330. var keyString = row[options.sourceKeyColumn];
  7331. if (options.sourceColumn == 'auto') {
  7332. translation = trans.getTranslationFromRow(row, options.sourceKeyColumn);
  7333. } else {
  7334. translation = row[options.sourceColumn];
  7335. }
  7336. //trans.findAndInsert = function(find, values, columns, options)
  7337. //trans.findAndInsert(keyString, translation, columns, options);
  7338. trans.findAndInsertWithIndexes(
  7339. keyString,
  7340. translation,
  7341. columns,
  7342. options.indexes,
  7343. {
  7344. overwrite :options.overwrite,
  7345. files :options.files
  7346. });
  7347. }
  7348. }
  7349. /**
  7350. * Abort translation process
  7351. */
  7352. Trans.prototype.abortTranslation = function() {
  7353. trans.translator = trans.translator||[];
  7354. if (typeof trans.translationTimer !== 'undefined') {
  7355. clearTimeout(trans.translationTimer);
  7356. }
  7357. for (var i=0; i<trans.translator.length; i++) {
  7358. let translator = trans.translator[i];
  7359. var thisTranslator = trans.getTranslatorEngine(translator)
  7360. if (!thisTranslator) continue;
  7361. if (typeof thisTranslator.abort == "function") {
  7362. try {
  7363. thisTranslator.abort();
  7364. } catch (e) {
  7365. ui.log("Failed to abort with message", e.toString());
  7366. }
  7367. }
  7368. thisTranslator.job = thisTranslator.job||{};
  7369. thisTranslator.job.wordcache = {};
  7370. thisTranslator.job.batch = [];
  7371. }
  7372. ui.hideLoading();
  7373. trans.refreshGrid();
  7374. trans.evalTranslationProgress();
  7375. }
  7376. /**
  7377. * Translate string by translation pair
  7378. * @param {String} str - String to translate
  7379. * @param {Object} translationPair - Key value based translation pair object
  7380. * @param {Boolean} caseInSensitive - Whether or not the translation is in case insensitive mode
  7381. * @returns {String} Translated result
  7382. */
  7383. Trans.prototype.translateStringByPair = function(str, translationPair, caseInSensitive) {
  7384. caseInSensitive = caseInSensitive||false;
  7385. if (typeof str !== 'string') return str;
  7386. if (typeof translationPair !== 'object') return str;
  7387. for (var key in translationPair) {
  7388. str = str.replaces(key, translationPair[key], caseInSensitive);
  7389. }
  7390. return str;
  7391. }
  7392. /**
  7393. * Search a translation from given trans data
  7394. * @param {String|String[]} text - Original text to translate
  7395. * @param {String|String[]} [fileFilter] - Destination file ID to search into. If blank then the method will search all file object
  7396. * @param {Trans} [transData=this] - Trans Data
  7397. * @since 6.1.14
  7398. * @returns {String|undefined} - translation result
  7399. */
  7400. Trans.prototype.translateFromTrans = function(text, fileFilter = [], transData = this) {
  7401. if (!text) return "";
  7402. if (typeof fileFilter == "string") fileFilter = [fileFilter];
  7403. const files = transData?.project?.files || {};
  7404. if (!fileFilter?.length) {
  7405. fileFilter = this.getAllFiles(files);
  7406. }
  7407. const getInstance = (text) => {
  7408. for (let i in fileFilter) {
  7409. let fileId = fileFilter[i]
  7410. let index = this.getIndexByKey(fileId, text);
  7411. if (typeof index == "undefined") continue;
  7412. let data = this.getData(fileId);
  7413. if (empty(data[index])) return "";
  7414. let translation = this.getTranslationFromRow(data[index])
  7415. if (translation) return translation;
  7416. }
  7417. }
  7418. if (Array.isArray(text)) {
  7419. let result = []
  7420. for (let i in text) {
  7421. result[i] = getInstance(text[i]) || ""
  7422. }
  7423. return result;
  7424. } else {
  7425. return getInstance(text);
  7426. }
  7427. }
  7428. /**
  7429. * Search a string from reference, will return blank if not found.
  7430. * @param {String} string - String to search for
  7431. * @param {String} [file=Common Reference] - File to be used as reference
  7432. * @returns {String} Translated text, blank if no reference found.
  7433. */
  7434. Trans.prototype.getReference = function(string, file = "Common Reference") {
  7435. if (!string) return "";
  7436. var index = this.getIndexByKey(file, string);
  7437. if (typeof index == "undefined") return "";
  7438. var data = this.getData(file);
  7439. if (empty(data[index])) return "";
  7440. return this.getTranslationFromRow(data[index]) || "";
  7441. }
  7442. /**
  7443. * Get translation from common reference. The behavior is like translation procedure.
  7444. * Will return original text if no reference found
  7445. * @param {String} input - String to be translated
  7446. * @param {Boolean} [caseInSensitive=false] - Whether to perform case insensitive search or not
  7447. * @param {String} [referenceName="Common Reference"] - The name of the reference file object
  7448. * @returns {String} translated string
  7449. */
  7450. Trans.prototype.translateByReference = function(input, caseInSensitive, referenceName="Common Reference") {
  7451. caseInSensitive = caseInSensitive||false;
  7452. //data = JSON.parse(JSON.stringify(input));
  7453. //console.log("Reference", referenceName);
  7454. if (!trans.project.files[referenceName]) return input;
  7455. trans.project.files[referenceName]["cacheResetOnChange"] = trans.project.files[referenceName]["cacheResetOnChange"]||{};
  7456. var transPair;
  7457. if (Boolean(trans.project.files[referenceName]["cacheResetOnChange"]["transPair"])!== false) {
  7458. //console.log("load translation pair from cache");
  7459. transPair = trans.project.files[referenceName]["cacheResetOnChange"]["transPair"];
  7460. } else {
  7461. transPair = trans.generateTranslationPair(trans.project.files[referenceName].data);
  7462. trans.project.files[referenceName]["cacheResetOnChange"]["transPair"] = transPair;
  7463. }
  7464. //console.log("Translate by reference pair :", transPair);
  7465. var output
  7466. if (typeof input == 'string') {
  7467. output = trans.translateStringByPair(input, transPair, caseInSensitive);
  7468. return output;
  7469. } else if (Array.isArray(input)){
  7470. output = [];
  7471. for (var i=0; i<input.length; i++) {
  7472. output[i] = trans.translateStringByPair(input[i], transPair, caseInSensitive);
  7473. }
  7474. return output;
  7475. }
  7476. return input;
  7477. }
  7478. /**
  7479. * Check whether a row has translation or not
  7480. * @param {String[]} cells - Single dimensional array representing rows
  7481. * @param {Number} [keyColumn=0]
  7482. * @param {Number|Number[]|undefined} [indexToCheck] - Index or indices to check for translation
  7483. * @returns {Boolean} True if has translation
  7484. */
  7485. Trans.prototype.rowHasTranslation = function(cells=[], keyColumn= this.keyColumn, indexToCheck) {
  7486. if (!cells || !cells.length) return false;
  7487. keyColumn = this.keyColumn || 0;
  7488. if (typeof indexToCheck == "undefined" || indexToCheck === null) {
  7489. for (let i=0; i<cells.length; i++) {
  7490. if (i == keyColumn) continue;
  7491. if (cells[i]) return true;
  7492. }
  7493. } else {
  7494. if (!Array.isArray(indexToCheck)) indexToCheck = [indexToCheck];
  7495. for (let i=0; i<indexToCheck.length; i++) {
  7496. if (indexToCheck[i] == keyColumn) continue;
  7497. if (cells[indexToCheck[i]]) return true;
  7498. }
  7499. }
  7500. return false;
  7501. }
  7502. /**
  7503. * Execute batch translation and automatically detect translation mode
  7504. * Executex the translator engine's translateAll function if available
  7505. * @param {TranslatorEngine} translator - Selected Translator engine object
  7506. * @param {Object} options
  7507. * @param {Function} [options.onFinished] - Function to run when the process completed
  7508. * @param {Number} [options.keyColumn=0] - Key column index of the table
  7509. * @param {Boolean} [options.translateOther] - Whether to translate unselected files or not
  7510. * @param {Boolean} [options.saveOnEachBatch] - Whether to save project for each batch
  7511. * @param {String[]} [options.filterTag] - Tags filter
  7512. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  7513. * @param {Boolean} [options.overwrite=false] - Whether to overwrite or not if the destination cell is not empty
  7514. * @param {Boolean} [options.ignoreTranslated=false] - Whether to skip processing or not if the row already has translation
  7515. * @param {Object} [options.translatorOptions] - Translator specific options
  7516. */
  7517. Trans.prototype.translateAll = async function(translator, options) {
  7518. const activeTranslator = this.getTranslatorEngine(translator);
  7519. this.buildIndex("Common Reference", true);
  7520. if (activeTranslator.translateAll == "function") {
  7521. return activeTranslator.translateAll(options);
  7522. }
  7523. if (activeTranslator.translatorType == "v2") {
  7524. return this.batchTranslate(activeTranslator, options);
  7525. }
  7526. if (activeTranslator.mode == "rowByRow") {
  7527. trans.translateAllByRows(translator, options);
  7528. } else {
  7529. trans.translateAllByLines(translator, options);
  7530. }
  7531. }
  7532. Trans.prototype.batchTranslate = async function(activeTranslator, options) {
  7533. // use V2 translator mechanism
  7534. const batchTranslate = new BatchTranslate(activeTranslator, options);
  7535. await ui.log.start({
  7536. buttons:[{
  7537. text:"Abort",
  7538. onClick: function(e) {
  7539. var sure = confirm(t("Are you sure want to abort this process?"));
  7540. //if (sure) trans.abortTranslation();
  7541. if (sure) batchTranslate.abort();
  7542. }
  7543. },
  7544. {
  7545. text:"Pause",
  7546. onClick: function(e) {
  7547. alert(t("Process paused!\nPress OK to continue!"));
  7548. }
  7549. }
  7550. ]
  7551. });
  7552. await batchTranslate.translateAll();
  7553. await ui.log.end();
  7554. await this.onBatchTranslationDone(options);
  7555. return;
  7556. }
  7557. /**
  7558. * Execute batch translation with row by row mode
  7559. * @param {TranslatorEngine} translator - Selected Translator engine object
  7560. * @param {Object} options
  7561. * @param {Function} [options.onFinished] - Function to run when the process completed
  7562. * @param {Number} [options.keyColumn=0] - Key column index of the table
  7563. * @param {Boolean} [options.translateOther] - Whether to translate unselected files or not
  7564. * @param {Boolean} [options.saveOnEachBatch] - Whether to save project for each batch
  7565. * @param {String[]} [options.filterTag] - Tags filter
  7566. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  7567. * @param {Boolean} [options.overwrite=false] - Whether to overwrite or not if the destination cell is not empty
  7568. * @param {Boolean} [options.ignoreTranslated=false] - Whether to skip processing or not if the row already has translation
  7569. * @param {Object} [options.translatorOptions] - Translator specific options
  7570. */
  7571. Trans.prototype.translateAllByRows = async function(translator, options) {
  7572. // TRANSLATE ALL
  7573. console.log("Running trans.translateAll", options);
  7574. ui.loadingProgress(0, "Running trans.translateAll");
  7575. var thisTranslator = this.getTranslatorEngine(translator);
  7576. if (typeof trans.project == 'undefined') return trans.alert(t("Unable to process, project not found"));
  7577. if (typeof trans.project.files == 'undefined') return trans.alert(t("Unable to process, data not found"));
  7578. if (typeof thisTranslator == 'undefined') return trans.alert(t("Translation engine not found"));
  7579. if (thisTranslator.isDisabled) return trans.alert(t("Translation engine ")+translator+t(" is disabled!"));
  7580. if (!trans.getSelectedId()) {
  7581. trans.selectFile($(".fileList .data-selector").eq(0));
  7582. }
  7583. options = options||{};
  7584. options.onFinished = options.onFinished||function() {};
  7585. options.keyColumn = options.keyColumn||0;
  7586. options.translateOther = options.translateOther|| false;
  7587. options.ignoreTranslated= options.ignoreTranslated || false;
  7588. options.overwrite = options.overwrite || false;
  7589. options.saveOnEachBatch = options.saveOnEachBatch || false;
  7590. // COLLECTING DATA
  7591. thisTranslator.job = thisTranslator.job||{};
  7592. thisTranslator.job.wordcache = {};
  7593. thisTranslator.job.batch = [];
  7594. thisTranslator.batchDelay = thisTranslator.batchDelay||trans.config.batchDelay;
  7595. // CALCULATING max request length
  7596. var currentMaxLength = trans.config.maxRequestLength;
  7597. if (thisTranslator.maxRequestLength < currentMaxLength) currentMaxLength = thisTranslator.maxRequestLength;
  7598. // SHOW loading bar
  7599. ui.showLoading({
  7600. buttons:[{
  7601. text:"Abort",
  7602. onClick: function(e) {
  7603. var sure = confirm(t("Are you sure want to abort this process?"));
  7604. if (sure) trans.abortTranslation();
  7605. }
  7606. },
  7607. {
  7608. text:"Pause",
  7609. onClick: function(e) {
  7610. alert(t("Process paused!\nPress OK to continue!"));
  7611. }
  7612. }
  7613. ]
  7614. });
  7615. ui.log("Start batch translation in Row by Row mode, with options:", options);
  7616. ui.log(`Translator is: ${translator}`);
  7617. console.log("Current maximum request length : "+currentMaxLength);
  7618. console.log("Start collecting data!");
  7619. ui.loadingProgress(0, "Start collecting data!");
  7620. var currentBatchID = 0;
  7621. var currentRequestLength = 0;
  7622. // to store key and source column pair when source column !=0;
  7623. var keyIndex = {};
  7624. // collecting selected row
  7625. var selectedFiles = trans.getCheckedFiles();
  7626. ui.loadingProgress(undefined, t("Selected files :")+selectedFiles.join(", "));
  7627. // none selected means all
  7628. if (selectedFiles.length == 0) selectedFiles = this.getAllFiles();
  7629. for (var thisIndex in selectedFiles) {
  7630. var file = selectedFiles[thisIndex];
  7631. ui.loadingProgress(undefined, t("Collecting data from :")+file);
  7632. try {
  7633. var currentData = trans.project.files[file].data;
  7634. } catch(e) {
  7635. console.warn("Can not access", file, "in trans.project.files" );
  7636. continue;
  7637. }
  7638. if (typeof thisTranslator.job.batch[currentBatchID] == 'undefined') thisTranslator.job.batch[currentBatchID] = [];
  7639. for (var i=0; i< currentData.length; i++) {
  7640. // skip if col[0] is empty, regardless keyColum, because we will use that latter
  7641. if (!currentData[i][0]) continue;
  7642. var currentSentence = currentData[i][options.keyColumn];
  7643. var escapedSentence = str_ireplace($DV.config.lineSeparator, thisTranslator.lineSubstitute, thisTranslator.escapeCharacter(currentSentence));
  7644. // skiping when empty
  7645. if (!currentSentence) continue;
  7646. // skip according to tags
  7647. if (options.filterTagMode == "blacklist") {
  7648. if (this.hasTags(options.filterTag, i, file)) continue;
  7649. } else if (options.filterTagMode == "whitelist") {
  7650. if (!this.hasTags(options.filterTag, i, file)) continue;
  7651. }
  7652. // skip line that already translated
  7653. if (options.ignoreTranslated) {
  7654. if (this.rowHasTranslation(currentData[i], options.keyColumn)) continue;
  7655. }
  7656. // skip line if cell is not empty & overwrite option is false
  7657. if (options.overwrite == false) {
  7658. if (currentData[i][thisTranslator.targetColumn]) {
  7659. console.log("Ignored because overwite options", options.overwrite, currentData[i][thisTranslator.targetColumn]);
  7660. continue;
  7661. }
  7662. }
  7663. if (currentSentence.trim().length == 0) continue;
  7664. // assign keyIndex pair
  7665. keyIndex[currentSentence] = currentData[i][0];
  7666. if (escapedSentence.length > currentMaxLength) {
  7667. console.log('current sentence is bigger than maxRequestLength!');
  7668. currentBatchID++;
  7669. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7670. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7671. currentBatchID++;
  7672. currentRequestLength = 0;
  7673. continue;
  7674. }
  7675. //if (currentSentence.length+currentRequestLength > currentMaxLength) {
  7676. if (escapedSentence.length+currentRequestLength > currentMaxLength) {
  7677. currentBatchID++;
  7678. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7679. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7680. currentRequestLength = 0;
  7681. continue;
  7682. }
  7683. // make each line unique
  7684. if (typeof thisTranslator.job.wordcache[currentSentence] !== 'undefined') {
  7685. continue;
  7686. } else {
  7687. thisTranslator.job.wordcache[currentSentence] = true;
  7688. }
  7689. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7690. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7691. //currentRequestLength += currentSentence.length;
  7692. currentRequestLength += escapedSentence.length;
  7693. }
  7694. }
  7695. await ui.log("Generating indexes");
  7696. var tempIndexes = this.buildIndexes(selectedFiles);
  7697. thisTranslator.job.batchLength = thisTranslator.job.batch.length;
  7698. console.log("current batch:", thisTranslator.job.batch);
  7699. ui.loadingProgress(0, "Data collection is done!");
  7700. console.log("Data collection is done!");
  7701. console.log("We have "+thisTranslator.job.batch.length+" batch totals!");
  7702. console.log("==========================================");
  7703. console.log("Begin translating using "+translator+"!");
  7704. var processPart = async function() {
  7705. if (typeof thisTranslator.job.batch == 'undefined') return "batch job undefined, quiting!";
  7706. if (thisTranslator.job.batch.length < 1) {
  7707. console.log("Batch job is finished");
  7708. trans.refreshGrid();
  7709. trans.evalTranslationProgress();
  7710. if (typeof options.onFinished == 'function') {
  7711. options.onFinished.call(this);
  7712. }
  7713. ui.loadingProgress(100, t("Translation finished"));
  7714. //ui.hideLoading();
  7715. ui.loadingClearButton();
  7716. ui.loadingEnd();
  7717. trans.onBatchTranslationDone(options);
  7718. trans.translationTimer = undefined;
  7719. return "batch job is finished!";
  7720. }
  7721. console.log("running processPart");
  7722. var currentData = thisTranslator.job.batch.pop();
  7723. console.log("current data : ");
  7724. console.log(currentData);
  7725. var preTransData;
  7726. if (thisTranslator.skipReferencePair) {
  7727. preTransData = currentData;
  7728. } else {
  7729. preTransData = trans.translateByReference(currentData);
  7730. }
  7731. thisTranslator.translate(preTransData, {
  7732. mode: "rowByRow",
  7733. onAfterLoading:async function(result) {
  7734. console.log(result);
  7735. if (typeof result.translation !== 'undefined') {
  7736. console.log("applying translation to table !");
  7737. console.log("calculating progress");
  7738. var percent = thisTranslator.job.batch.length/thisTranslator.job.batchLength*100;
  7739. percent = 100-percent;
  7740. ui.loadingProgress(percent, t("applying translation to table!"));
  7741. var targetFiles = selectedFiles;
  7742. if (options.translateOther) targetFiles = trans.getAllFiles();
  7743. trans.trigger("batchTranslationResult", {original:currentData, translation:result.translation, translator:thisTranslator})
  7744. for (var index in result.translation) {
  7745. //trans.findAndInsert(keyIndex[currentData[index]],
  7746. trans.findAndInsertWithIndexes(
  7747. keyIndex[currentData[index]],
  7748. result.translation[index],
  7749. thisTranslator.targetColumn,
  7750. tempIndexes,
  7751. {
  7752. filterTag : options.filterTag || [],
  7753. filterTagMode : options.filterTagMode,
  7754. keyColumn : options.keyColumn,
  7755. overwrite : options.overwrite,
  7756. files : targetFiles
  7757. });
  7758. }
  7759. if (options.saveOnEachBatch) {
  7760. ui.log("Saving your project");
  7761. await trans.save();
  7762. }
  7763. ui.loadingProgress(undefined, (thisTranslator.job.batchLength-thisTranslator.job.batch.length)+"/"+thisTranslator.job.batchLength+" batch done, waiting "+thisTranslator.batchDelay+" ms...");
  7764. trans.translationTimer = setTimeout(function(){ processPart(); }, thisTranslator.batchDelay);
  7765. }
  7766. //trans.refreshGrid();
  7767. //trans.grid.render();
  7768. },
  7769. onError:function(evt, type, errorType) {
  7770. console.log("ERROR on transling data");
  7771. var percent = thisTranslator.job.batch.length/thisTranslator.job.batchLength*100;
  7772. percent = 100-percent;
  7773. ui.loadingProgress(percent,
  7774. t("Error when translating data!")+"\r\n"+
  7775. t("\tHTTP Status : ")+evt.status+"\r\n"+
  7776. t("\tError Type : ")+errorType+"\r\n"+
  7777. t("You are probably temporarily banned by your translation service!\r\nPlease use online translation service in moderation\r\nThis usualy fixed by itself within a day or two.\r\n"));
  7778. ui.loadingProgress(undefined, (thisTranslator.job.batchLength-thisTranslator.job.batch.length)+"/"+thisTranslator.job.batchLength+t(" batch done, ")+t("waiting ")+thisTranslator.batchDelay+t(" ms..."));
  7779. trans.translationTimer = setTimeout(function(){ processPart(); }, thisTranslator.batchDelay);
  7780. }
  7781. });
  7782. }
  7783. processPart();
  7784. }
  7785. /**
  7786. * Execute batch translation with line-by-line mode
  7787. * @param {TranslatorEngine} translator - Selected Translator engine object
  7788. * @param {Object} options
  7789. * @param {Function} [options.onFinished] - Function to run when the process completed
  7790. * @param {Number} [options.keyColumn=0] - Key column index of the table
  7791. * @param {Boolean} [options.translateOther] - Whether to translate unselected files or not
  7792. * @param {Boolean} [options.saveOnEachBatch] - Whether to save project for each batch
  7793. * @param {String[]} [options.filterTag] - Tags filter
  7794. * @param {'blacklist'|'whitelist'} [options.filterTagMode] - Filter mode
  7795. * @param {Boolean} [options.overwrite=false] - Whether to overwrite or not if the destination cell is not empty
  7796. * @param {Boolean} [options.ignoreTranslated=false] - Whether to skip processing or not if the row already has translation
  7797. */
  7798. Trans.prototype.translateAllByLines = async function(translator, options) {
  7799. // TRANSLATE ALL
  7800. console.log("Running trans.translateAllByLines", arguments);
  7801. ui.loadingProgress(0, t("Running trans.translateAll"));
  7802. var thisTranslator = this.getTranslatorEngine(translator);
  7803. if (typeof trans.project == 'undefined') return trans.alert(t("Unable to process, project not found"));
  7804. if (typeof trans.project.files == 'undefined') return trans.alert(t("Unable to process, data not found"));
  7805. if (typeof thisTranslator == 'undefined') return trans.alert(t("Translation engine not found"));
  7806. if (thisTranslator.isDisabled) return trans.alert(t("Translation engine ")+translator+t(" is disabled!"));
  7807. if (!trans.getSelectedId()) {
  7808. trans.selectFile($(".fileList .data-selector").eq(0));
  7809. }
  7810. options = options||{};
  7811. options.onFinished = options.onFinished||function() {};
  7812. options.keyColumn = options.keyColumn||0;
  7813. options.translateOther = options.translateOther|| false;
  7814. options.ignoreTranslated= options.ignoreTranslated || false;
  7815. options.overwrite = options.overwrite || false;
  7816. options.saveOnEachBatch = options.saveOnEachBatch || false;
  7817. var fetchMode = "both"
  7818. if (options.ignoreTranslated) {
  7819. fetchMode = "untranslated"
  7820. }
  7821. // COLLECTING DATA
  7822. thisTranslator.job = thisTranslator.job||{};
  7823. thisTranslator.job.wordcache = {};
  7824. thisTranslator.job.batch = [];
  7825. thisTranslator.batchDelay = thisTranslator.batchDelay||trans.config.batchDelay;
  7826. // CALCULATING max request length
  7827. var currentMaxLength = trans.config.maxRequestLength;
  7828. if (thisTranslator.maxRequestLength < currentMaxLength) currentMaxLength = thisTranslator.maxRequestLength;
  7829. // SHOW loading bar
  7830. ui.showLoading({
  7831. buttons:[{
  7832. text:"Abort",
  7833. onClick: function(e) {
  7834. var sure = confirm(t("Are you sure want to abort this process?"));
  7835. if (sure) trans.abortTranslation();
  7836. }
  7837. },
  7838. {
  7839. text:"Pause",
  7840. onClick: function(e) {
  7841. alert(t("Process paused!\nPress OK to continue!"));
  7842. }
  7843. }
  7844. ]
  7845. });
  7846. ui.log("Start batch translation in Line by Line mode, with options:", options);
  7847. ui.log(`Translator is: ${translator}`);
  7848. console.log("Current maximum request length : "+currentMaxLength);
  7849. console.log("Start collecting data!");
  7850. ui.loadingProgress(0, t("Start collecting data!"));
  7851. var currentBatchID = 0;
  7852. var currentRequestLength = 0;
  7853. // collecting selected row
  7854. var selectedFiles = trans.getCheckedFiles();
  7855. ui.loadingProgress(undefined, t("Selected files :")+selectedFiles.join(", "));
  7856. var transTableInfo = trans.generateTranslationTableLine(trans.project, {
  7857. files : selectedFiles,
  7858. mode : "lineByLine",
  7859. fetch : fetchMode,
  7860. keyColumn : options.keyColumn,
  7861. filterLanguage : this.getSl(),
  7862. filterTag : options.filterTag || [],
  7863. filterTagMode : options.filterTagMode,
  7864. ignoreTranslated : options.ignoreTranslated,
  7865. targetColumn : thisTranslator.targetColumn,
  7866. overwrite : options.overwrite,
  7867. ignoreWhitespace : thisTranslator.ignoreWhitespace,
  7868. collectAddress : true
  7869. });
  7870. var transTable = transTableInfo.pairs;
  7871. console.log("Fetch mode : ", fetchMode);
  7872. console.log("Translatable : ", transTable);
  7873. currentBatchID = 0;
  7874. currentRequestLength = 0;
  7875. for (var translateKey in transTable) {
  7876. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7877. var currentSentence = translateKey;
  7878. var escapedSentence = str_ireplace($DV.config.lineSeparator, thisTranslator.lineSubstitute, thisTranslator.escapeCharacter(currentSentence));
  7879. // skiping when empty
  7880. if (Boolean(currentSentence) == false) continue;
  7881. if (typeof currentSentence !== 'string') continue;
  7882. if (currentSentence.trim().length == 0) continue;
  7883. if (escapedSentence.length > currentMaxLength) {
  7884. console.log('current sentence is bigger than maxRequestLength!');
  7885. currentBatchID++;
  7886. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7887. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7888. currentBatchID++;
  7889. currentRequestLength = 0;
  7890. continue;
  7891. }
  7892. if (escapedSentence.length+currentRequestLength > currentMaxLength) {
  7893. currentBatchID++;
  7894. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7895. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7896. currentRequestLength = 0;
  7897. continue;
  7898. }
  7899. thisTranslator.job.batch[currentBatchID] = thisTranslator.job.batch[currentBatchID]||[];
  7900. thisTranslator.job.batch[currentBatchID].push(currentSentence);
  7901. //currentRequestLength += currentSentence.length;
  7902. currentRequestLength += escapedSentence.length;
  7903. }
  7904. // cleaning up transTable for RAM friendly
  7905. transTable = undefined;
  7906. thisTranslator.job.batchLength = thisTranslator.job.batch.length;
  7907. ui.loadingProgress(0, t("Data collection is done!"));
  7908. console.log("Data collection is done!");
  7909. console.log("We have "+thisTranslator.job.batch.length+" batch totals!");
  7910. console.log("==========================================");
  7911. console.log("Begin translating using "+translator+"!");
  7912. await ui.log("Generating indexes");
  7913. var tempIndexes = this.buildIndexes(selectedFiles, true);
  7914. console.log("indexes:", tempIndexes);
  7915. var processPart = async function() {
  7916. if (typeof thisTranslator.job.batch == 'undefined') return "batch job undefined, quiting!";
  7917. if (thisTranslator.job.batch.length < 1) {
  7918. console.log("Batch job is finished");
  7919. // filling skipped translation
  7920. var selectedObj = [];
  7921. if (options.translateOther == false) selectedObj = trans.getCheckedFiles();
  7922. trans.fillEmptyLine(selectedObj, [], thisTranslator.targetColumn, options.keyColumn, {
  7923. lineFilter : function(str) {
  7924. return !common.isInLanguage(str, trans.getSl());
  7925. },
  7926. fromKeyOnly : options.ignoreTranslated,
  7927. filterTag : options.filterTag || [],
  7928. filterTagMode : options.filterTagMode,
  7929. overwrite : options.overwrite
  7930. });
  7931. trans.refreshGrid();
  7932. trans.evalTranslationProgress();
  7933. if (typeof options.onFinished == 'function') {
  7934. options.onFinished.call(this);
  7935. }
  7936. ui.loadingProgress(100, t("Translation finished"));
  7937. //ui.hideLoading();
  7938. ui.loadingClearButton();
  7939. ui.loadingEnd();
  7940. trans.onBatchTranslationDone(options);
  7941. trans.translationTimer = undefined;
  7942. return "batch job is finished!";
  7943. }
  7944. var translatePart = async function() {
  7945. console.log("running processPart");
  7946. var selectedObj = [];
  7947. if (options.translateOther == false) selectedObj = trans.getCheckedFiles();
  7948. trans.fillEmptyLine(selectedObj, [], thisTranslator.targetColumn, options.keyColumn, {
  7949. lineFilter : function(str) {
  7950. return !common.isInLanguage(str, trans.getSl());
  7951. },
  7952. fromKeyOnly : options.ignoreTranslated,
  7953. filterTag : options.filterTag || [],
  7954. filterTagMode : options.filterTagMode,
  7955. overwrite : options.overwrite
  7956. });
  7957. var currentData = thisTranslator.job.batch.pop();
  7958. console.log("current data : ");
  7959. console.log(currentData);
  7960. var preTransData;
  7961. if (thisTranslator.skipReferencePair) {
  7962. preTransData = currentData;
  7963. } else {
  7964. preTransData = trans.translateByReference(currentData);
  7965. }
  7966. thisTranslator.translate(preTransData, {
  7967. onAfterLoading:async function(result) {
  7968. console.log("onAfterLoading translation result:", result);
  7969. if (typeof result.translation !== 'undefined') {
  7970. console.log("applying translation to table !");
  7971. //console.log("calculating progress");
  7972. var percent = thisTranslator.job.batch.length/thisTranslator.job.batchLength*100;
  7973. percent = 100-percent;
  7974. ui.loadingProgress(percent, t("applying translation to table!"));
  7975. trans.trigger("batchTranslationResult", {original:currentData, translation:result.translation, translator:thisTranslator})
  7976. for (var index in result.translation) {
  7977. trans.findAndInsertWithIndexes(
  7978. currentData[index],
  7979. result.translation[index],
  7980. thisTranslator.targetColumn,
  7981. //tempIndexes,
  7982. transTableInfo.addresses,
  7983. {
  7984. files : selectedObj,
  7985. keyColumn : options.keyColumn,
  7986. stripCarriageReturn : true,
  7987. filterTag : options.filterTag || [],
  7988. filterTagMode : options.filterTagMode,
  7989. overwrite : options.overwrite,
  7990. lineByLine : true
  7991. });
  7992. }
  7993. if (options.saveOnEachBatch) {
  7994. ui.log("Saving your project");
  7995. await trans.save();
  7996. }
  7997. //ui.loadingProgress(undefined, (thisTranslator.job.batchLength-thisTranslator.job.batch.length)+"/"+thisTranslator.job.batchLength+" batch done, waiting "+thisTranslator.batchDelay+" ms...");
  7998. ui.loadingProgress(undefined, (thisTranslator.job.batchLength-thisTranslator.job.batch.length)+"/"+thisTranslator.job.batchLength+" batch done!");
  7999. processPart();
  8000. }
  8001. },
  8002. onError:function(evt, type, errorType) {
  8003. console.log("ERROR on transling data");
  8004. var percent = thisTranslator.job.batch.length/thisTranslator.job.batchLength*100;
  8005. percent = 100-percent;
  8006. ui.loadingProgress(percent,
  8007. t("Error when translating data!")+"\r\n"+
  8008. t("\tHTTP Status : ")+evt.status+"\r\n"+
  8009. t("\tError Type : ")+errorType+"\r\n"+
  8010. t("You are probably temporarily banned by your translation service!\r\nPlease use online translation service in moderation\r\nThis usualy fixed by itself within a day or two.\r\n"));
  8011. ui.loadingProgress(undefined, (thisTranslator.job.batchLength-thisTranslator.job.batch.length)+"/"+thisTranslator.job.batchLength+" batch done!");
  8012. processPart();
  8013. }
  8014. });
  8015. }
  8016. if (thisTranslator.job.batchLength == thisTranslator.job.batch.length) {
  8017. translatePart();
  8018. } else {
  8019. ui.loadingProgress(undefined, "Waiting "+thisTranslator.batchDelay+" ms...");
  8020. trans.translationTimer = setTimeout(function(){ translatePart(); }, thisTranslator.batchDelay);
  8021. }
  8022. }
  8023. processPart();
  8024. }
  8025. /**
  8026. * Function to run when translation is completed
  8027. * @param {Object} options The same options with trans.translateAll function
  8028. */
  8029. Trans.prototype.onBatchTranslationDone = function(options) {
  8030. if (options.playSoundOnComplete) {
  8031. var myAudioElement = new Audio('/www/audio/done.mp3');
  8032. myAudioElement.addEventListener("canplay", event => {
  8033. /* the audio is now playable; play it if permissions allow */
  8034. myAudioElement.play();
  8035. });
  8036. }
  8037. }
  8038. /**
  8039. * Get translator engine object by its ID
  8040. * @param {String} id - The ID of translator engine
  8041. * @returns {TranslatorEngine} The translator engine
  8042. */
  8043. Trans.prototype.getTranslatorEngine = function(id) {
  8044. if (TranslatorEngine.translators[id]) return TranslatorEngine.translators[id];
  8045. if (this[id] instanceof TranslatorEngine) return this[id];
  8046. if (id instanceof TranslatorEngine) return id;
  8047. console.warn(id, " is not a translator engine");
  8048. }
  8049. /**
  8050. * Get currently active Translator Engine
  8051. */
  8052. Trans.prototype.getActiveTranslatorEngine = function() {
  8053. return this.getTranslatorEngine(this.getActiveTranslator());
  8054. }
  8055. /**
  8056. * Set active translator engine
  8057. * @param {String|TranslatorEngine} translator - Translator engine ID or object
  8058. * @since 7.3.26
  8059. */
  8060. Trans.prototype.setActiveTranslator = function(translator) {
  8061. if (typeof translator == 'string') {
  8062. translator = this.getTranslatorEngine(translator);
  8063. }
  8064. if (!translator?.id) return;
  8065. this.setOption("translator", translator.id);
  8066. }
  8067. /**
  8068. * Determines translate selection by row or by line
  8069. * @param {CellRange[]} [currentSelection=trans.grid.getSelected()] - Cell range to be translated
  8070. * @param {Object} options
  8071. * @param {Object} [options.translatorEngine=this.getActiveTranslatorEngine()] - Translator engine to be used
  8072. */
  8073. Trans.prototype.translateSelection = async function(currentSelection, options = {}) {
  8074. //var activeTranslator = options.translatorEngine || this.getActiveTranslatorEngine();
  8075. this.buildIndex("Common Reference", true);
  8076. var trans = this;
  8077. currentSelection = currentSelection||trans.grid.getSelectedRange()||[[]];
  8078. if (typeof currentSelection == 'undefined') {
  8079. alert(t("nothing is selected"));
  8080. return false;
  8081. }
  8082. if (typeof trans.translator == "undefined" || trans.translator.length < 1) {
  8083. alert(t("no translator loaded"));
  8084. return false;
  8085. }
  8086. var currentEngine = options.translatorEngine || this.getActiveTranslatorEngine();
  8087. options.mode ||= currentEngine.mode
  8088. options.ignoreWhitespace ||= currentEngine.ignoreWhitespace
  8089. console.log("translating selection ", options.mode);
  8090. if (currentEngine.isDisabled == true) return alert(currentEngine.id+" is disabled!");
  8091. ui.tableCornerShowLoading();
  8092. var textPool = [];
  8093. var thisData = trans.grid.getData();
  8094. var rowPool = common.gridSelectedCells() || [];
  8095. var tempTextPool = [];
  8096. for (var i=0; i<rowPool.length; i++) {
  8097. var col = rowPool[i].col;
  8098. if (col == this.keyColumn) continue;
  8099. tempTextPool.push(thisData[rowPool[i].row][this.keyColumn]);
  8100. }
  8101. if (!tempTextPool) return;
  8102. console.log("Text pool", tempTextPool);
  8103. var translationTable = trans.generateTranslationTableFromStrings(tempTextPool, currentEngine, options);
  8104. console.log("Translation table:", JSON.stringify(translationTable, undefined, 2));
  8105. translationTable = await this.processWith("translationTableFilter", translationTable, currentEngine) || translationTable;
  8106. console.warn("Filtered translationTable", JSON.stringify(translationTable, undefined, 2));
  8107. for (var phrase in translationTable.include) {
  8108. textPool.push(phrase);
  8109. }
  8110. console.log(textPool);
  8111. console.log(rowPool);
  8112. if (rowPool.length < 1) {
  8113. ui.tableCornerHideLoading();
  8114. return;
  8115. }
  8116. var preTransData;
  8117. if (currentEngine.skipReferencePair) {
  8118. preTransData = textPool;
  8119. } else {
  8120. preTransData = trans.translateByReference(textPool);
  8121. }
  8122. console.log("Translate using : ",currentEngine.id);
  8123. // TODO: If all result has already been translated via TM, then no need to pass into Translator engine.
  8124. currentEngine.translate(preTransData, {
  8125. onAfterLoading:async function(result) {
  8126. console.log("Translation result:");
  8127. console.log(result);
  8128. console.log("text pool :");
  8129. console.log(textPool);
  8130. console.log("rowpool:");
  8131. console.log(rowPool);
  8132. console.log("translation result : ");
  8133. trans.trigger("batchTranslationResult", {original:textPool, translation:result.translation, translator:currentEngine})
  8134. var transTable = trans.generateTranslationTableFromResult(textPool, result.translation, translationTable.exclude);
  8135. console.log("translation table : ");
  8136. console.log(transTable);
  8137. trans.applyTransTableToSelectedCell(transTable, currentSelection, undefined, options);
  8138. ui.tableCornerHideLoading();
  8139. trans.grid.render();
  8140. trans.evalTranslationProgress();
  8141. trans.textEditorSetValue(trans.getTextFromLastSelected());
  8142. }
  8143. });
  8144. }
  8145. /**
  8146. * Translate selected cell with row-by-row algorighm
  8147. * @param {CellRange[]} [currentSelection=trans.grid.getSelected()] - Cell range to be translated
  8148. * @param {Object} options
  8149. * @param {Object} [options.translatorEngine=this.getActiveTranslatorEngine()] - Translator engine to be used
  8150. * @deprecated - Since 5.1.0
  8151. */
  8152. Trans.prototype.translateSelectionByRow = async function(currentSelection, options = {}) {
  8153. options.mode = "rowByRow";
  8154. return this.translateSelection(currentSelection, options = {})
  8155. }
  8156. /**
  8157. * Translate selected cell with line-by-line algorighm
  8158. * @param {CellRange[]} [currentSelection=trans.grid.getSelected()] - Cell range to be translated
  8159. * @param {Object} options
  8160. * @param {Object} [options.translatorEngine=this.getActiveTranslatorEngine()] - Translator engine to be used
  8161. * @deprecated - Since 5.1.0
  8162. */
  8163. Trans.prototype.translateSelectionByLine = async function(currentSelection, options = {}) {
  8164. options.mode = "lineByLine";
  8165. return this.translateSelection(currentSelection, options = {})
  8166. }
  8167. Trans.prototype.translateSelectionAsOneLine = async function(currentSelection, options = {}) {
  8168. console.log("Merge to one line then translate");
  8169. currentSelection = currentSelection||trans.grid.getSelectedRange()||[[]];
  8170. if (typeof currentSelection == 'undefined') {
  8171. alert(t("nothing is selected"));
  8172. return false;
  8173. }
  8174. if (typeof trans.translator == "undefined" || trans.translator.length < 1) {
  8175. alert(t("no translator loaded"));
  8176. return false;
  8177. }
  8178. var currentEngine = options.translatorEngine || this.getActiveTranslatorEngine();
  8179. var originalText = this.getSelectedOriginalTexts(currentSelection);
  8180. var sourceText = this.getSelectedOriginalTextsAsOneLine(currentSelection);
  8181. var selectedRows = common.gridSelectedRows(currentSelection);
  8182. var rowIndex = {};
  8183. for (var i=0; i<selectedRows.length; i++) {
  8184. rowIndex[selectedRows[i]] = i;
  8185. }
  8186. console.log("Row index:", rowIndex);
  8187. var data = this.getData();
  8188. console.log("Original text:", originalText);
  8189. ui.tableCornerShowLoading();
  8190. var preTransData;
  8191. if (currentEngine.skipReferencePair) {
  8192. preTransData = sourceText;
  8193. } else {
  8194. preTransData = trans.translateByReference(sourceText);
  8195. }
  8196. console.log("Translating", preTransData);
  8197. currentEngine.translate(preTransData, {
  8198. mode: "rowByRow",
  8199. onAfterLoading: (result) => {
  8200. if (typeof result.translation !== 'undefined') {
  8201. console.log("result translation:", result.translation);
  8202. var formattedResult = common.cloneFormatting(originalText, result.translation.join(" "));
  8203. console.log("Formatted result:", formattedResult);
  8204. console.log("Write back the translated result according to the row");
  8205. var selectedCells = common.gridSelectedCells(currentSelection)
  8206. for (var i=0; i<selectedCells.length; i++) {
  8207. if (selectedCells[i].col == this.keyColumn) continue;
  8208. data[selectedCells[i].row][selectedCells[i].col] = formattedResult[rowIndex[selectedCells[i].row]];
  8209. }
  8210. }
  8211. ui.tableCornerHideLoading();
  8212. trans.grid.render();
  8213. trans.evalTranslationProgress();
  8214. trans.textEditorSetValue(trans.getTextFromLastSelected());
  8215. }
  8216. });
  8217. }
  8218. /**
  8219. * Translate using all availables translator into their corresponding default column.
  8220. * @param {CellRange} currentSelection
  8221. */
  8222. Trans.prototype.translateSelectionIntoDef =function(currentSelection) {
  8223. /*
  8224. this function will translate using all available translator into their correspinding
  8225. default column.
  8226. */
  8227. console.log("translating selection into default coloumn");
  8228. currentSelection = currentSelection||trans.grid.getSelected()||[[]];
  8229. if (typeof currentSelection == 'undefined') {
  8230. alert(t("nothing is selected"));
  8231. return false;
  8232. }
  8233. if (typeof trans.translator == "undefined" || trans.translator.length < 1) {
  8234. alert(t("no translator loaded"));
  8235. return false;
  8236. }
  8237. var textPool = [];
  8238. var thisData = trans.grid.getData();
  8239. var rowPool = [];
  8240. for (var index=0; index<currentSelection.length; index++) {
  8241. for (var row=currentSelection[index][0]; row<=currentSelection[index][2]; row++) {
  8242. rowPool.push(row);
  8243. textPool.push(thisData[row][0]);
  8244. }
  8245. }
  8246. //var dataString = textPool.join($DV.config.lineSeparator);
  8247. var dataString = textPool;
  8248. console.log(dataString);
  8249. console.log(rowPool);
  8250. for (var i=0; i<trans.translator.length; i++ ) {
  8251. console.log(i);
  8252. var currentPlugin = trans.translator[i];
  8253. var thisTranslator = this.getTranslatorEngine(currentPlugin);
  8254. if (thisTranslator.isDisabled == true) continue;
  8255. if (typeof thisTranslator.targetColumn == "undefined") {
  8256. console.warn("Skipping. Reason : TargetColumn property is not set for engine ", currentPlugin)
  8257. continue;
  8258. }
  8259. var preTransData = trans.translateByReference(dataString);
  8260. thisTranslator.translate(preTransData, {
  8261. onAfterLoading:function(result) {
  8262. if (typeof result.translation !== 'undefined') {
  8263. for (var x in result.translation) {
  8264. trans.data[rowPool[x]][thisTranslator.targetColumn] = result.translation[x];
  8265. }
  8266. }
  8267. //trans.refreshGrid();
  8268. trans.grid.render();
  8269. trans.evalTranslationProgress();
  8270. }
  8271. });
  8272. }
  8273. }
  8274. /**
  8275. * Apply translation table into selected cell
  8276. * @param {Object} transTable - Translation table formatted object
  8277. * @param {CellRange} [currentSelection=trans.grid.getSelected()] - Cell range to put translation into
  8278. * @param {String[][]} [transData=this.data] - Two dimensional array representing the grid
  8279. * @param {Object} [options]
  8280. * @param {Number} [options.indexKey=0] - Index of the key column
  8281. */
  8282. Trans.prototype.applyTransTableToSelectedCell = function(transTable, currentSelection, transData, options) {
  8283. /*
  8284. transTable = translation table format;
  8285. selectedCell = array of cell selection
  8286. transData = either trans.data / trans.project.files['file'].data
  8287. */
  8288. transData = transData||trans.data; // current selected file
  8289. currentSelection = currentSelection||trans.grid.getSelected()||[[]];
  8290. options = options||{};
  8291. options.indexKey = options.indexKey||0;
  8292. if (typeof currentSelection == 'undefined') {
  8293. alert(t("nothing is selected"));
  8294. return false;
  8295. }
  8296. //console.log("applyTransTableToSelectedCell", arguments);
  8297. var rowPool = common.gridSelectedCells(currentSelection) || [];
  8298. if (options.mode == "rowByRow") {
  8299. for (let i=0; i<rowPool.length; i++) {
  8300. let col = rowPool[i].col;
  8301. let row = rowPool[i].row;
  8302. if (col == this.keyColumn) continue;
  8303. if (Array.isArray(transData[row]) == false) continue;
  8304. transData[row][col] = transTable[transData[row][options.indexKey]];
  8305. }
  8306. } else {
  8307. for (let i=0; i<rowPool.length; i++) {
  8308. let col = rowPool[i].col;
  8309. let row = rowPool[i].row;
  8310. if (col == this.keyColumn) continue;
  8311. if (Array.isArray(transData[row]) == false) continue;
  8312. //console.log("---looking for", JSON.stringify(transData[row][options.indexKey]));
  8313. //console.log("transtable:", JSON.stringify(transTable, undefined, 2))
  8314. transData[row][col] = this.translateTextByLine(transData[row][options.indexKey], transTable);
  8315. }
  8316. }
  8317. }
  8318. /**
  8319. * Translate selected row with translation pane. (Live translator)
  8320. * @param {Number} row
  8321. * @param {Number} col
  8322. * @returns {Boolean}
  8323. */
  8324. Trans.prototype.translateSelectedRow = function(row, col) {
  8325. if (typeof row == 'undefined') return false;
  8326. if (trans.config.autoTranslate == false) return false;
  8327. //if ($("#translationPane").attr("src") == "") return false;
  8328. col = col||0;
  8329. var currentText = trans.data[row][col];
  8330. if (!currentText) return false;
  8331. var translatorWindow = $("#translationPane")[0].contentWindow;
  8332. if (ui.windows['translator']) {
  8333. translatorWindow = ui.windows['translator'];
  8334. }
  8335. if (!translatorWindow.translator) return t("unable to load translator window");
  8336. translatorWindow.translator.translateAll(currentText);
  8337. return true;
  8338. }
  8339. /**
  8340. * Get translation by index of the translation portlet (Live translator)
  8341. * @param {Number} index - Index of the portlet
  8342. * @returns {String} Translated text
  8343. */
  8344. Trans.prototype.getTranslationByIndex = function(index) {
  8345. if (typeof index == 'undefined') return false;
  8346. //if ($("#translationPane").attr("src") == "") return false;
  8347. var translatorWindow = $("#translationPane")[0].contentWindow;
  8348. if (ui.windows['translator']) {
  8349. translatorWindow = ui.windows['translator'];
  8350. }
  8351. return translatorWindow.$(".mainPane .portlet").eq(index).find(".portlet-content").text();
  8352. }
  8353. /**
  8354. * Import translation from other .trans file
  8355. * @param {String|Trans} refPath - path to the Trans File or an object content of transFile
  8356. * @param {Object} options
  8357. * @param {Number} [options.targetColumn=1] - target column to write for
  8358. * @param {Boolean} [options.overwrite=false] - Whether to overwrite the destination cell or not
  8359. * @param {String[]} [options.files] - imported selected file list
  8360. * @param {String[]} [options.destination] - destination file list
  8361. * @param {lineByLine|rowByRow|contextTrans|copyByRow} [options.compareMode=contextTrans] - Copy method
  8362. */
  8363. Trans.prototype.importTranslation = async function(refPath, options) {
  8364. console.log("importTranslation", arguments);
  8365. if (typeof refPath == 'undefined') return trans.alert(t("Reference path cannot empty!"));
  8366. options = options || {};
  8367. options.targetColumn = options.targetColumn||1;
  8368. options.overwrite = options.overwrite||false;
  8369. options.files = options.files||[]; // imported selected file list
  8370. options.destination = options.destination||[]; // destination file list
  8371. options.compareMode = options.compareMode||0; // context to context
  8372. options.ignoreLangCheck = true; // always ignore language check!
  8373. options.destinationMode = options.destinationMode || "selected";
  8374. options.caseInsensitive ||= false;
  8375. console.log("refPath & options : ");
  8376. console.log(arguments);
  8377. //return true;
  8378. // selecting file is required
  8379. if (!trans.getSelectedId()) {
  8380. trans.selectFile($(".panel-left .fileList .data-selector").eq(0));
  8381. }
  8382. var lowerCaseText = undefined;
  8383. if (options.caseInsensitive) {
  8384. lowerCaseText = function(text) {
  8385. return text.toLowerCase().replaceAll("\r", "");
  8386. }
  8387. }
  8388. var applyImportedTranslation = async (loadedData) => {
  8389. console.log("Applying translation");
  8390. ui.loadingProgress(30, t("Collecting translation refference"));
  8391. await ui.log("Collecting translation refference");
  8392. var refTranslation = {};
  8393. var tempIndexes;
  8394. if (options.compareMode == 'lineByLine') {
  8395. refTranslation = trans.generateTranslationTableLine(loadedData.project.files, options);
  8396. let targetFiles;
  8397. if (options.destinationMode == "selected") {
  8398. targetFiles = this.getCheckedFiles()
  8399. }
  8400. tempIndexes = this.buildIndexes(targetFiles, true, {customFilter:lowerCaseText});
  8401. } else if (options.compareMode == 'rowByRow') {
  8402. refTranslation = trans.generateTranslationTable(loadedData.project.files, options);
  8403. let targetFiles;
  8404. if (options.destinationMode == "selected") {
  8405. targetFiles = this.getCheckedFiles()
  8406. }
  8407. tempIndexes = this.buildIndexes(targetFiles, false, {customFilter:lowerCaseText});
  8408. } else if (options.compareMode == 'contextTrans') {
  8409. refTranslation = trans.generateContextTranslationPair(loadedData.project.files, options);
  8410. }
  8411. //console.log("reference translation is : ", refTranslation);
  8412. //console.log(refTranslation);
  8413. loadedData = trans.mergeReference(loadedData);
  8414. var numData = Object.keys(refTranslation).length
  8415. await ui.log(`Processing ${numData} reference(s)`);
  8416. ui.loadingProgress(50, t("Applying translation!"));
  8417. var count = 0;
  8418. var lastProgress = 50;
  8419. if (options.compareMode == 'lineByLine') { // line by line
  8420. for (let key in refTranslation) {
  8421. let origKey = key;
  8422. if (options.caseInsensitive) key = lowerCaseText(key);
  8423. trans.findAndInsertWithIndexes(
  8424. key,
  8425. refTranslation[origKey],
  8426. options.targetColumn,
  8427. tempIndexes,
  8428. {
  8429. overwrite :options.overwrite,
  8430. files :options.destination,
  8431. lineByLine :true,
  8432. customFilter:lowerCaseText
  8433. });
  8434. ui.loadingProgress(50+(count/numData*50));
  8435. count++;
  8436. }
  8437. } else if (options.compareMode == 'rowByRow') { // row by row
  8438. console.log("Row by Row translation");
  8439. for (let key in refTranslation) {
  8440. let origKey = key;
  8441. if (options.caseInsensitive) key = lowerCaseText(key);
  8442. trans.findAndInsertWithIndexes(
  8443. key,
  8444. refTranslation[origKey],
  8445. options.targetColumn,
  8446. tempIndexes,
  8447. {
  8448. overwrite :options.overwrite,
  8449. files :options.destination,
  8450. insensitive :true,
  8451. customFilter:lowerCaseText
  8452. });
  8453. var thisProgress = Math.round(50+(count/numData*50))
  8454. if (thisProgress > lastProgress) {
  8455. ui.loadingProgress(50+(count/numData*50));
  8456. await ui.log(`Handled: ${count}/${numData}`);
  8457. lastProgress = thisProgress;
  8458. }
  8459. count++;
  8460. }
  8461. } else if (options.compareMode == 'contextTrans') {
  8462. console.log("Translation by context");
  8463. for (var key in refTranslation) {
  8464. trans.findAndInsertByContext(key, refTranslation[key], options.targetColumn, {
  8465. overwrite:options.overwrite,
  8466. files:options.destination
  8467. });
  8468. ui.loadingProgress(50+(count/numData*50));
  8469. count++;
  8470. }
  8471. } else if (options.compareMode == 'copyByRow') {
  8472. this.copyTranslationToRow(loadedData.project.files, options.targetColumn, options);
  8473. }
  8474. /**
  8475. * Triggered after import translation process is done
  8476. * @param {Object} options
  8477. * @param {Object} options.options
  8478. * @param {Object} options.loadedData
  8479. * @param {Object} options.refTranslation
  8480. */
  8481. trans.trigger("onAfterImportTranslations", {
  8482. options:options,
  8483. loadedData:loadedData,
  8484. refTranslation:refTranslation
  8485. });
  8486. await common.wait(20)
  8487. trans.evalTranslationProgress();
  8488. trans.refreshGrid();
  8489. ui.loadingProgress(100, "Done!");
  8490. ui.loadingEnd();
  8491. }
  8492. ui.showLoading();
  8493. ui.loadingProgress(0, t("Importing translation"));
  8494. await common.wait(200);
  8495. if (typeof refPath == 'object' && typeof refPath.project !== 'undefined') {
  8496. // refference path already loaded
  8497. console.log("refPath is an object : ");
  8498. await applyImportedTranslation(refPath);
  8499. return true;
  8500. }
  8501. console.log("Opening "+refPath);
  8502. fs.readFile(refPath, async function (err, data) {
  8503. if (err) {
  8504. console.log("error opening file : "+refPath);
  8505. data = data.toString();
  8506. if (typeof options.onFailed =='function') options.onFailed.call(trans, data);
  8507. throw err;
  8508. } else {
  8509. ui.loadingProgress(20, t("Parsing data"));
  8510. await ui.log("Parsing data");
  8511. await common.wait(200);
  8512. data = data.toString();
  8513. //console.log(data);
  8514. var jsonData = JSON.parse(data);
  8515. console.log("Result data : ");
  8516. console.log(jsonData);
  8517. applyImportedTranslation(jsonData);
  8518. console.log("Done!");
  8519. if (typeof options.onSuccess == 'function') options.onSuccess.call(trans, jsonData);
  8520. trans.isOpeningFile = false;
  8521. }
  8522. });
  8523. }
  8524. Trans.prototype.translateAllBySelectedCells = async function(currentSelection, fileId, options) {
  8525. currentSelection = currentSelection||this.grid.getSelectedRange()||[[]];
  8526. fileId = fileId || this.getSelectedId();
  8527. options = options || {};
  8528. ui.showBusyOverlay();
  8529. await common.wait(100);
  8530. var targetFiles = this.getAllFilesExcept([fileId]);
  8531. //console.log("Target files:", targetFiles);
  8532. var selectedTransTable = this.generateSelectedTranslationTable(currentSelection, fileId, options);
  8533. console.log("Selected transtable", selectedTransTable);
  8534. var tempIndexes = this.buildIndexes(targetFiles);
  8535. var found = [];
  8536. for (var keyword in selectedTransTable) {
  8537. var foundCells = this.getFromIndexes(keyword, tempIndexes);
  8538. if (!foundCells) continue;
  8539. for (var y=0; y<foundCells.length; y++) {
  8540. var foundCell = foundCells[y];
  8541. var targetData = this.getData(foundCell.file);
  8542. for (var i=0; i<selectedTransTable[keyword].length; i++) {
  8543. var cellInfo = selectedTransTable[keyword][i];
  8544. var oldValue = targetData[foundCell.row][cellInfo.col];
  8545. if (cellInfo.col == this.keyColumn) continue;
  8546. targetData[foundCell.row][cellInfo.col] = cellInfo.value;
  8547. //console.log("Setting up file", foundCell.file, "row", foundCell.row, "col", cellInfo.col, "with value:", cellInfo.value);
  8548. found.push({
  8549. file:foundCell.file,
  8550. row:foundCell.row,
  8551. col:cellInfo.col,
  8552. oldValue:oldValue,
  8553. newValue:cellInfo.value
  8554. })
  8555. }
  8556. }
  8557. }
  8558. ui.hideBusyOverlay();
  8559. return found;
  8560. }
  8561. /**
  8562. * Get texts from selected cells on the grid
  8563. * @since 4.7.16
  8564. * @param {*} currentSelection
  8565. * @param {*} fileId
  8566. * @returns {String[]} Array of texts from the selected cells
  8567. */
  8568. Trans.prototype.getSelectedTexts = function(currentSelection, fileId) {
  8569. currentSelection = currentSelection||this.grid.getSelectedRange()||[[]];
  8570. fileId = fileId || this.getSelectedId();
  8571. var data = this.getData(fileId);
  8572. var selectedCells = common.gridSelectedCells(currentSelection);
  8573. var result = [];
  8574. for (var i=0; i<selectedCells.length; i++) {
  8575. result.push(
  8576. data[selectedCells[i].row][selectedCells[i].col] || ""
  8577. )
  8578. }
  8579. return result;
  8580. }
  8581. /**
  8582. * Get text from the grid
  8583. * @param {Number} row - Row index
  8584. * @param {Number} column - Column index
  8585. * @param {String} [file] - File id
  8586. * @returns {String} - Text of the selected row, column and file
  8587. */
  8588. Trans.prototype.getText = function(row, column, file) {
  8589. if (!file) {
  8590. return this.data?.[row]?.[column]
  8591. }
  8592. const obj = trans.getObjectById(file);
  8593. return obj?.[row]?.[column]
  8594. }
  8595. /**
  8596. * Get cell comments on a coordinate
  8597. * @param {Number} row - Row index
  8598. * @param {Number} column - Column index
  8599. * @param {String} [file] - File id
  8600. * @returns {String} - Comment of the selected row, column and file
  8601. */
  8602. Trans.prototype.getCellComment = function(row, column, file) {
  8603. let obj
  8604. if (!file) {
  8605. obj = this.getSelectedObject();
  8606. } else {
  8607. obj = this.getObjectById(file)
  8608. }
  8609. if (!obj.comments) return;
  8610. return obj.comments?.[row]?.[column];
  8611. }
  8612. /**
  8613. * Select original texts from grid selection
  8614. * @param {CellRange[]|Number[][]} currentSelection - Current selection
  8615. * @param {String} fileId - File id
  8616. * @returns {String[]} Array of string of the selected original texts
  8617. */
  8618. Trans.prototype.getSelectedOriginalTexts = function(currentSelection, fileId) {
  8619. currentSelection = currentSelection||this.grid.getSelectedRange()||[[]];
  8620. fileId = fileId || this.getSelectedId();
  8621. var data = this.getData(fileId);
  8622. var selectedCells = common.gridSelectedCells(currentSelection);
  8623. var result = [];
  8624. for (var i=0; i<selectedCells.length; i++) {
  8625. result.push(
  8626. data[selectedCells[i].row][this.keyColumn] || ""
  8627. )
  8628. }
  8629. return result;
  8630. }
  8631. /**
  8632. * Get texts from selected cells and merge them into one line
  8633. * @since 4.7.16
  8634. * @param {*} currentSelection
  8635. * @param {*} fileId
  8636. * @returns {String} Text of the selected cell in one line
  8637. */
  8638. Trans.prototype.getSelectedTextsAsOneLine = function(currentSelection, fileId) {
  8639. var texts = this.getSelectedTexts(currentSelection, fileId) || [];
  8640. var merged = texts.join(" ");
  8641. return merged.replaceAll("\r", "").replaceAll("\n", " ");
  8642. }
  8643. /**
  8644. * Get original texts from selected cells and merge them into one line
  8645. * @since 4.7.16
  8646. * @param {*} currentSelection
  8647. * @param {*} fileId
  8648. * @returns {String} Original text of the selected cell in one line
  8649. */
  8650. Trans.prototype.getSelectedOriginalTextsAsOneLine = function(currentSelection, fileId) {
  8651. currentSelection = currentSelection||this.grid.getSelectedRange()||[[]];
  8652. fileId = fileId || this.getSelectedId();
  8653. var data = this.getData(fileId);
  8654. var rows = common.gridSelectedRows()
  8655. var result = []
  8656. for (var i=0; i<rows.length; i++) {
  8657. result.push(
  8658. data[rows[i]][this.keyColumn] || ""
  8659. )
  8660. }
  8661. return result.join(" ");
  8662. }
  8663. // ==================================================================
  8664. // PUT DOM RELATED CODE HERE
  8665. // ==================================================================
  8666. /**
  8667. * returns related key ID from trans.project.files
  8668. * returning false when error
  8669. * @returns {String|False} The currently seleceted ID
  8670. */
  8671. Trans.prototype.getSelectedId = function() {
  8672. // returning false when error
  8673. // returns related key ID from trans.project.files
  8674. // getting the value from trans.project.selectedId is faster than DOM
  8675. //if (trans.project?.selectedId) return trans.project.selectedId;
  8676. if (!trans.project) return false;
  8677. return trans.project?.selectedId
  8678. /*
  8679. if ($(".fileList .selected").length == 0 ) return false;
  8680. return $(".fileList .selected").data("id");
  8681. */
  8682. }
  8683. /**
  8684. * Get selected row's context
  8685. * @param {Number} rowNumber - Row id to look for
  8686. * @returns {String} Context
  8687. */
  8688. Trans.prototype.getSelectedContext = function(rowNumber) {
  8689. rowNumber = rowNumber || trans.lastSelectedCell[0]
  8690. var context = trans.getSelectedObject().context;
  8691. try {
  8692. return context[rowNumber]
  8693. } catch (e) {
  8694. context[rowNumber] = [];
  8695. return context[rowNumber];
  8696. }
  8697. }
  8698. /**
  8699. * Get selected row's parameters
  8700. * @returns {Object} parameters of the selected row
  8701. */
  8702. Trans.prototype.getSelectedParameters = function() {
  8703. if (!trans.lastSelectedCell) return;
  8704. var rowNumber = trans.lastSelectedCell[0]
  8705. var obj =trans.getSelectedObject()
  8706. obj.parameters = obj.parameters || [];
  8707. obj.parameters[rowNumber] = obj.parameters[rowNumber] || []
  8708. return obj.parameters[rowNumber]
  8709. }
  8710. /**
  8711. * Get parameters by row id & file id
  8712. * @param {Number} row - The row id
  8713. * @param {String} file - The file id
  8714. * @returns {Object|false} parameters of the selected row or false if no parameter is found
  8715. */
  8716. Trans.prototype.getParamatersByRow = function(row, file) {
  8717. file = file || this.getSelectedId();
  8718. if (typeof row !== "number") return false;
  8719. var thisObj = trans.getObjectById(file);
  8720. if (!thisObj?.parameters) return false;
  8721. return thisObj.parameters[row];
  8722. }
  8723. /**
  8724. * Set parameters by row id & file id
  8725. * @param {Number} row - The row id
  8726. * @param {Object} parameters - The parameters to be set
  8727. * @param {String} [file=this.getSelectedId()] - The file id
  8728. */
  8729. Trans.prototype.setParametersByRow = function(row, parameters, file) {
  8730. file = file || this.getSelectedId();
  8731. const thisObj = this.getObjectById(file);
  8732. thisObj.parameters = thisObj.parameters || [];
  8733. thisObj.parameters[row] = parameters;
  8734. }
  8735. /**
  8736. * Get row info text from file object's parameters
  8737. * @param {Number} row - Row index
  8738. * @param {Boolean} [full=false] - Whether to display full result or not
  8739. * @param {String} [file=Trans.getSelectedId()] - Target file object
  8740. * @param {Boolean} [untranslated=false] - Whether to display untranslated text or not
  8741. * @returns {String} row info
  8742. */
  8743. Trans.prototype.getRowInfoText = function(row, full=false, file="", untranslated=false) {
  8744. file = file || this.getSelectedId();
  8745. const thisParam = this.getParamatersByRow(row, file);
  8746. if (!thisParam) return "";
  8747. const rowInfoReference = (this.getOption("gridInfo")||{}).referenceName || "Actor Reference";
  8748. var result;
  8749. if (full) {
  8750. result = [];
  8751. for (let i in thisParam) {
  8752. if (!thisParam[i]) continue;
  8753. if (typeof thisParam[i] !== "object") continue;
  8754. if (untranslated) {
  8755. if (thisParam[i].rowInfoText) result.push(thisParam[i].rowInfoText);
  8756. } else {
  8757. if (thisParam[i].rowInfoText) result.push(this.translateByReference(thisParam[i].rowInfoText, false, rowInfoReference));
  8758. }
  8759. }
  8760. let uniqueItems = [...new Set(result)]
  8761. return uniqueItems.join(", ")
  8762. }
  8763. result = "";
  8764. for (let i in thisParam) {
  8765. if (!thisParam[i]) continue;
  8766. if (typeof thisParam[i] !== "object") continue;
  8767. if (result) return result+"++";
  8768. if (untranslated) {
  8769. if (thisParam[i].rowInfoText) result = thisParam[i].rowInfoText;
  8770. } else {
  8771. if (thisParam[i].rowInfoText) result = this.translateByReference(thisParam[i].rowInfoText, false, rowInfoReference);
  8772. }
  8773. }
  8774. return result;
  8775. }
  8776. /**
  8777. * Set row info text (eg. Character name) to the object's parameters
  8778. * @param {Number} row - Row id
  8779. * @param {String} text - Text to be set
  8780. * @param {String} [file=this.getSelectedId()] - File id
  8781. */
  8782. Trans.prototype.setRowInfoText = function(row, text, file) {
  8783. file = file || this.getSelectedId();
  8784. const thisParam = this.getParamatersByRow(row, file);
  8785. if (!thisParam) return false;
  8786. thisParam[0] ||= {};
  8787. thisParam[0].rowInfoText = text;
  8788. return true;
  8789. }
  8790. /**
  8791. * Get selected key text from row
  8792. * Usually cell 0
  8793. * @param {*} rowNumber - Row id
  8794. * @returns {String|undefined} key text
  8795. */
  8796. Trans.prototype.getSelectedKeyText = function(rowNumber) {
  8797. rowNumber = rowNumber || trans.lastSelectedCell[0]
  8798. try {
  8799. var data = trans.getSelectedObject().data;
  8800. return data[rowNumber][trans.keyColumn]
  8801. } catch (e) {
  8802. // do nothing
  8803. }
  8804. }
  8805. /**
  8806. * returns related object from trans.project.files[currently selected]
  8807. * returning false when error
  8808. * @returns {Object|false}
  8809. */
  8810. Trans.prototype.getSelectedObject = function() {
  8811. // returning false when error
  8812. // returns related object from trans.project.files[currently selected]
  8813. if ($(".fileList .selected").length == 0 ) return false;
  8814. var currentID = trans.getSelectedId();
  8815. return trans.project.files[currentID];
  8816. }
  8817. /**
  8818. * Get file object by its id
  8819. * @param {String} id - The file id
  8820. * @returns {Object} the file object. Equal to trans.project.files[id]
  8821. */
  8822. Trans.prototype.getObjectById = function(id) {
  8823. if (!id) return;
  8824. try {
  8825. return trans.project?.files?.[id]
  8826. } catch (e){
  8827. console.warn(e);
  8828. return;
  8829. }
  8830. }
  8831. /**
  8832. * Get list of the checked file(s) on the left pane
  8833. * @returns {String[]} Array of the checked file id
  8834. */
  8835. Trans.prototype.getCheckedFiles = function() {
  8836. var result = [];
  8837. var checkbox = $(".fileList .data-selector .fileCheckbox:checked");
  8838. for (var i=0; i<checkbox.length; i++) {
  8839. result.push(checkbox.eq(i).attr("value"));
  8840. }
  8841. return result;
  8842. }
  8843. /**
  8844. * Get selected objects
  8845. * @returns {Object} Selected object
  8846. */
  8847. Trans.prototype.getCheckedObjects = function() {
  8848. var result = {};
  8849. var checkbox = $(".fileList .data-selector .fileCheckbox:checked");
  8850. for (var i=0; i<checkbox.length; i++) {
  8851. var id = checkbox.eq(i).attr("value");
  8852. result[id] = this.getObjectById(id)
  8853. }
  8854. return result;
  8855. }
  8856. /**
  8857. * Get all file ids on the project
  8858. * @param {Object} [obj=this.project.files] - list of file objects
  8859. * @param {Boolean} [excludeReference=false] - wether to exclude reference or not
  8860. * @returns {String[]}
  8861. */
  8862. Trans.prototype.getAllFiles = function(obj, excludeReference) {
  8863. var result = [];
  8864. obj = obj||trans?.project?.files;
  8865. if (typeof obj == 'undefined') return result;
  8866. if (obj?.project?.files) {
  8867. obj = obj?.project?.files;
  8868. }
  8869. if (excludeReference) {
  8870. for (let file in obj ) {
  8871. if (obj[file]?.dirname == "*") continue; // skip reference
  8872. result.push(file);
  8873. }
  8874. return result;
  8875. }
  8876. for (let file in obj ) {
  8877. result.push(file);
  8878. }
  8879. return result;
  8880. }
  8881. /**
  8882. * Get all file ids on the project, except filteredIds
  8883. * @since 4.7.17
  8884. * @param {String[]} filteredIds - list of exceptions
  8885. * @param {Object} [obj=this.project.files] - list of file objects
  8886. * @returns {String[]}
  8887. */
  8888. Trans.prototype.getAllFilesExcept = function(filteredIds, obj) {
  8889. if (typeof filteredIds == "string") filteredIds = [filteredIds];
  8890. filteredIds = filteredIds || [];
  8891. obj = obj||trans.project.files;
  8892. var result = [];
  8893. for (var file in obj ) {
  8894. if (filteredIds.includes(file)) continue;
  8895. result.push(file);
  8896. }
  8897. return result;
  8898. }
  8899. /**
  8900. * Get all files with 100% progress
  8901. * @param {*} [obj=this.project.files] - list of file objects
  8902. * @returns {String[]} List of the files
  8903. */
  8904. Trans.prototype.getAllCompletedFiles = function(obj) {
  8905. var result = [];
  8906. obj = obj||this.project.files;
  8907. if (typeof obj == 'undefined') return result;
  8908. for (var file in obj ) {
  8909. //console.log(file, obj[file]);
  8910. if (typeof obj[file] !== "object") continue;
  8911. if (typeof obj[file].progress !== "object") continue;
  8912. if (obj[file].progress.percent == 100) {
  8913. result.push(file);
  8914. }
  8915. }
  8916. return result;
  8917. }
  8918. /**
  8919. * Get all files with less than 100% progress
  8920. * @param {*} [obj=this.project.files] - list of file objects
  8921. * @returns {String[]} List of the files
  8922. */
  8923. Trans.prototype.getAllIncompletedFiles = function(obj) {
  8924. var result = [];
  8925. obj = obj||this.project.files;
  8926. if (typeof obj == 'undefined') return result;
  8927. for (var file in obj ) {
  8928. //console.log(file, obj[file]);
  8929. if (typeof obj[file] !== "object") continue;
  8930. if (typeof obj[file].progress !== "object") continue;
  8931. if (obj[file].progress.percent < 100) {
  8932. result.push(file);
  8933. }
  8934. }
  8935. return result;
  8936. }
  8937. /**
  8938. * Get all files marked as completed
  8939. * @param {*} [obj=this.project.files] - list of file objects
  8940. * @returns {String[]} List of the files
  8941. * @since 4.4.5
  8942. */
  8943. Trans.prototype.getAllMarkedAsCompleted = function(obj) {
  8944. var result = [];
  8945. obj = obj||this.project.files;
  8946. if (typeof obj == 'undefined') return result;
  8947. for (var file in obj ) {
  8948. if (typeof obj[file] !== "object") continue;
  8949. if (typeof obj[file].progress !== "object") continue;
  8950. if (obj[file].isCompleted) {
  8951. result.push(file);
  8952. }
  8953. }
  8954. return result;
  8955. }
  8956. /**
  8957. * Get attachment content by ID
  8958. * @param {String} id - ID of the attachment
  8959. * @since 6.3.27
  8960. * @returns {undefined|String} - Attachment content
  8961. */
  8962. Trans.prototype.getAttachmentContent = function(id) {
  8963. if (!id) return;
  8964. if (!trans.project?.attachments?.[id]) return;
  8965. return trans.project.attachments[id].data;
  8966. }
  8967. /**
  8968. * Scroll horizontally to the selected column.
  8969. * The column in argument 1 will be displayed next to the frozen cols
  8970. * @param {*} col - Column index to be shown
  8971. */
  8972. Trans.prototype.scrollHToCol = function(col) {
  8973. var $container = $("#table .ht_master .wtHolder")
  8974. if (!col) return $container[0].scrollLeft = 0
  8975. var $colls = $("#table .ht_master .wtHolder colgroup col");
  8976. //var margin = $colls.eq(0).outerWidth()
  8977. var scrollWidth = 0
  8978. for (var i=1; i<col; i++) {
  8979. scrollWidth += $colls.eq(i+1).outerWidth();
  8980. }
  8981. console.log(scrollWidth)
  8982. $container[0].scrollLeft = scrollWidth;
  8983. }
  8984. // ==============================================================
  8985. // SEARCH
  8986. // ==============================================================
  8987. /**
  8988. * Go to cell. Will select the cell and scroll the viewport to the cell.
  8989. * @param {Number} row
  8990. * @param {Number} col
  8991. * @param {String|JQuery} fileId
  8992. */
  8993. Trans.prototype.goTo = function(row, col, fileId) {
  8994. console.log(arguments);
  8995. fileId = fileId || this.getSelectedId()
  8996. /*
  8997. trans.selectFile(context, {
  8998. onDone:function() {
  8999. trans.grid.selectCell(row,col,row,col);
  9000. }
  9001. });
  9002. */
  9003. // commit any change on current cell
  9004. this.grid.deselectCell();
  9005. if (fileId !== this.getSelectedId()) {
  9006. var $selected = this.selectFile(fileId);
  9007. //$($selected)[0].scrollIntoView({behavior: "smooth"});
  9008. $($selected)[0].scrollIntoView({block:"center"});
  9009. }
  9010. this.grid.selectCell(row,col,row,col);
  9011. this.grid.scrollViewportTo(row,col);
  9012. this.scrollHToCol(col);
  9013. //setTimeout (function() {trans.grid.selectCell(row,col,row,col)}, 1000);
  9014. }
  9015. /**
  9016. * Get the last selected Cell
  9017. * @returns {Number[]} Array of row and column
  9018. * Return `[0,0]` if no cell is selected;
  9019. * @since 4.4.4
  9020. */
  9021. Trans.prototype.getLastSelectedCell = function() {
  9022. return this.lastSelectedCell;
  9023. }
  9024. /**
  9025. * Go to the next untranslated cell
  9026. * @returns {Boolean} Whether the operation is successful or not
  9027. */
  9028. Trans.prototype.goToNextUntranslated = function() {
  9029. var selectedCell = this.getLastSelectedCell();
  9030. var data = this.getCurrentData();
  9031. var starting = selectedCell[0]+1;
  9032. if (starting >= data.length) starting = 0;
  9033. for (var rowId=starting; rowId<data.length; rowId++) {
  9034. if (this.rowHasTranslation(data[rowId])) continue;
  9035. break;
  9036. }
  9037. if (rowId >= data.length) rowId = data.length - 1;
  9038. return this.goTo(rowId, selectedCell[1]);
  9039. }
  9040. /**
  9041. * Go to the previous untranslated cell
  9042. * @returns {Boolean} Whether the operation is successful or not
  9043. */
  9044. Trans.prototype.goToPreviousUntranslated = function() {
  9045. var selectedCell = this.getLastSelectedCell();
  9046. var data = this.getCurrentData();
  9047. var starting = selectedCell[0]-1;
  9048. if (starting <= 0) starting = data.length - 1;
  9049. console.log("starting", starting);
  9050. for (var rowId=starting; rowId>=0; rowId--) {
  9051. if (this.rowHasTranslation(data[rowId])) continue;
  9052. break;
  9053. }
  9054. console.log("Move to row", rowId);
  9055. if (rowId < 0) rowId = 0;
  9056. return this.goTo(rowId, selectedCell[1]);
  9057. }
  9058. /**
  9059. * Search for some keyword
  9060. * @param {String} keyword - Keyword
  9061. * @param {Object} options
  9062. * @param {Boolean} [options.caseSensitive] - Whether the search is in case sensitive mode or not
  9063. * @param {Boolean} [options.lineMatch] - Whether the search is with the line match mode or not
  9064. * @param {Boolean} [options.isRegexp] - Whether the keyword is a regexp or not
  9065. * @returns {SearchResult} the search result
  9066. */
  9067. Trans.prototype.search = function(keyword, options) {
  9068. var globToRegExp = require('glob-to-regexp');
  9069. console.log("entering trans.search", arguments);
  9070. if (typeof keyword == "undefined") return null;
  9071. if (typeof keyword.length <=1) return "Keyword too short!";
  9072. if (typeof trans.project == "undefined") return null;
  9073. if (typeof trans.project.files == "undefined") return null;
  9074. options = options|| {};
  9075. options.caseSensitive = options.caseSensitive||false;
  9076. options.lineMatch = options.lineMatch||false;
  9077. options.isRegexp = options.isRegexp||false;
  9078. options.searchLocations = options.searchLocations || [];
  9079. if (options.searchLocations.length == 0) options.searchLocations = ['grid'];
  9080. if (options.lineMatch) options.searchInContext = false;
  9081. if (Array.isArray(options.files) == false) {
  9082. options.files = [];
  9083. for (let file in trans.project.files) {
  9084. options.files.push(file);
  9085. }
  9086. }
  9087. if (options.caseSensitive == false && options.isRegexp == false) {
  9088. keyword = keyword.toLowerCase();
  9089. }
  9090. var start = new Date().getTime();
  9091. /**
  9092. * @typedef SearchResult
  9093. * @property {String} keyword - The keyword used
  9094. * @property {Number} count - Total numbers of the result
  9095. * @property {Boolean} isRegExp - Whether the keyword is regular expression or not
  9096. * @property {Number} executionTime - Execution time in ms
  9097. * @property {Object} files - list of the search result by file id
  9098. * @property {String} files.fullString - Full string of the result
  9099. * @property {Number} files.row - Row id
  9100. * @property {Number} files.col - Column id
  9101. * @property {cell|context|comment} files.type - type of the search result
  9102. * @property {Number} files.lineIndex - The line index
  9103. */
  9104. var result = {
  9105. keyword:keyword,
  9106. count:0,
  9107. isRegexp:options.isRegexp,
  9108. executionTime:0,
  9109. files:{}
  9110. };
  9111. // check if regexp is valid
  9112. var keywordExp;
  9113. if (options.isRegexp) {
  9114. keywordExp = common.evalRegExpStr(keyword);
  9115. if (keywordExp == false) {
  9116. alert(keyword+t(" is not a valid javascript's regexp!\r\nFind out more about Javascipt's Regular Expression at :\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"));
  9117. return result;
  9118. }
  9119. } else if (keyword.includes("*")) {
  9120. // glob style keyword
  9121. try {
  9122. var fixedKeywordExp = globToRegExp(keyword).toString().replace(/\/\^(.*?)\$\//, '$1');
  9123. keywordExp = new RegExp(fixedKeywordExp, 'i'); // insensitive
  9124. console.log("Glob style keyword detected", keywordExp);
  9125. } catch (e) {
  9126. console.warn('Error when converting glob pattern to RegExp');
  9127. }
  9128. }
  9129. //line match algorithm
  9130. if (options.lineMatch) {
  9131. for (let cont in options.files) {
  9132. let file = options.files[cont];
  9133. if (Array.isArray(trans.project.files[file].data) == false) continue;
  9134. let currentFile = trans.project.files[file].data;
  9135. for (let row=0; row<currentFile.length; row++) {
  9136. if (currentFile[row].length == 0) continue;
  9137. for (let col=0; col<currentFile[row].length; col++) {
  9138. if (typeof currentFile[row][col] !== "string") continue;
  9139. if (keywordExp) {
  9140. // regular expression search
  9141. if (keywordExp.test(currentFile[row][col])) {
  9142. // match found
  9143. let lineIndex = common.lineIndexRegExp(currentFile[row][col], keywordExp);
  9144. result.files[file] = result.files[file]||[];
  9145. result.files[file].push({
  9146. 'fullString':currentFile[row][col],
  9147. 'row':row,
  9148. 'col':col,
  9149. 'type':'cell',
  9150. 'lineIndex':lineIndex
  9151. });
  9152. result.count++;
  9153. break;
  9154. }
  9155. } else {
  9156. // normal search
  9157. if (options.caseSensitive) {
  9158. if (currentFile[row][col].indexOf(keyword) == -1) continue;
  9159. } else {
  9160. if (currentFile[row][col].toLowerCase().indexOf(keyword) == -1) continue;
  9161. }
  9162. let lineIndex = common.lineIndex(currentFile[row][col], keyword, options.caseSensitive);
  9163. if (lineIndex != -1) {
  9164. // match found
  9165. result.files[file] = result.files[file]||[];
  9166. result.files[file].push({
  9167. 'fullString':currentFile[row][col],
  9168. 'row':row,
  9169. 'col':col,
  9170. 'type':'cell',
  9171. 'lineIndex':lineIndex
  9172. });
  9173. result.count++;
  9174. break;
  9175. }
  9176. }
  9177. }
  9178. }
  9179. }
  9180. let end = new Date().getTime();
  9181. result.executionTime = end - start;
  9182. return result;
  9183. }
  9184. console.log("Search location:", options.searchLocations);
  9185. // common algorithm
  9186. if (options.searchLocations.includes("grid")) {
  9187. //for (var file in trans.project.files) {
  9188. for (let cont in options.files) {
  9189. let file = options.files[cont];
  9190. if (Array.isArray(trans.project.files[file].data) == false) continue;
  9191. let currentFile = trans.project.files[file].data;
  9192. for (let row=0; row<currentFile.length; row++) {
  9193. if (currentFile[row].length == 0) continue;
  9194. for (let col=0; col<currentFile[row].length; col++) {
  9195. if (typeof currentFile[row][col] !== "string") continue;
  9196. if (keywordExp) {
  9197. //console.log("regexp search:", keywordExp, currentFile[row][col], keywordExp.test(currentFile[row][col]));
  9198. //console.log(typeof keywordExp);
  9199. // regular expression search
  9200. if (keywordExp.test(currentFile[row][col])) {
  9201. // match found
  9202. result.files[file] = result.files[file]||[];
  9203. result.files[file].push({
  9204. 'fullString':currentFile[row][col],
  9205. 'row':row,
  9206. 'col':col,
  9207. 'type':'cell'
  9208. });
  9209. result.count++;
  9210. break;
  9211. }
  9212. } else {
  9213. if (options.caseSensitive) {
  9214. if (currentFile[row][col].indexOf(keyword) == -1) continue;
  9215. } else {
  9216. if (currentFile[row][col].toLowerCase().indexOf(keyword) == -1) continue;
  9217. }
  9218. result.files[file] = result.files[file]||[];
  9219. result.files[file].push({
  9220. 'fullString':currentFile[row][col],
  9221. 'row':row,
  9222. 'col':col,
  9223. 'type':'cell'
  9224. });
  9225. result.count++;
  9226. }
  9227. }
  9228. }
  9229. }
  9230. }
  9231. if (options.searchLocations.includes("context")) {
  9232. for (let idx in options.files) {
  9233. let file = options.files[idx];
  9234. if (Array.isArray(trans.project.files[file].context) == false) continue;
  9235. let currentFile = trans.project.files[file].context;
  9236. for (let row=0; row<currentFile.length; row++) {
  9237. if (Array.isArray(currentFile[row]) == false) continue;
  9238. if (currentFile[row].length == 0) continue;
  9239. for (let cont=0; cont<currentFile[row].length; cont++) {
  9240. if (typeof currentFile[row][cont] !== "string") continue;
  9241. if (keywordExp) {
  9242. if (keywordExp.test(currentFile[row][cont]) == false) continue;
  9243. } else if (options.caseSensitive) {
  9244. if (currentFile[row][cont].indexOf(keyword) == -1) continue;
  9245. } else {
  9246. if (currentFile[row][cont].toLowerCase().indexOf(keyword) == -1) continue;
  9247. }
  9248. result.files[file] = result.files[file]||[];
  9249. result.files[file].push({
  9250. 'fullString':currentFile[row][cont],
  9251. 'row':row,
  9252. 'col':0,
  9253. 'type':'context'
  9254. });
  9255. result.count++;
  9256. }
  9257. }
  9258. }
  9259. }
  9260. if (options.searchLocations.includes("tag")) {
  9261. for (let cont in options.files) {
  9262. let file = options.files[cont];
  9263. let tags = keyword.split(" ");
  9264. let currentFile = trans.project.files[file].data;
  9265. for (let row=0; row<currentFile.length; row++) {
  9266. if (trans.hasTags(tags, row, file) == false) continue;
  9267. result.files[file] = result.files[file]||[];
  9268. result.files[file].push({
  9269. 'fullString':currentFile[row][this.keyColumn],
  9270. 'row':row,
  9271. 'col':0,
  9272. 'type':'cell'
  9273. });
  9274. result.count++;
  9275. }
  9276. }
  9277. }
  9278. if (options.searchLocations.includes("comment")) {
  9279. console.log("searching comment");
  9280. for (let idx in options.files) {
  9281. let file = options.files[idx];
  9282. if (Boolean(trans.project.files[file].comments) == false) continue;
  9283. let currentFile = trans.project.files[file].comments;
  9284. console.log("processing", file);
  9285. for (let row in currentFile) {
  9286. if (Boolean(currentFile[row]) == false) continue;
  9287. for (let col in currentFile[row]) {
  9288. if (typeof currentFile[row][col] !== "string") continue;
  9289. if (keywordExp) {
  9290. if (keywordExp.test(currentFile[row][col]) == false) continue;
  9291. } else if (options.caseSensitive) {
  9292. if (currentFile[row][col].indexOf(keyword) == -1) continue;
  9293. } else {
  9294. if (currentFile[row][col].toLowerCase().indexOf(keyword) == -1) continue;
  9295. }
  9296. result.files[file] = result.files[file]||[];
  9297. result.files[file].push({
  9298. 'fullString':currentFile[row][col],
  9299. 'row':row,
  9300. 'col':col,
  9301. 'type':'comment'
  9302. });
  9303. result.count++;
  9304. }
  9305. }
  9306. }
  9307. }
  9308. var end = new Date().getTime();
  9309. result.executionTime = end - start;
  9310. return result;
  9311. }
  9312. /**
  9313. * Search for some keyword and replace it with a text
  9314. * @param {String} keyword - Keyword
  9315. * @param {String} replacer - Replacer
  9316. * @param {Object} options
  9317. * @param {Boolean} [options.caseSensitive] - Whether the search is in case sensitive mode or not
  9318. * @param {Boolean} [options.lineMatch] - Whether the search is with the line match mode or not
  9319. * @param {Boolean} [options.isRegexp] - Whether the keyword is a regexp or not
  9320. * @returns {SearchResult} the search result
  9321. */
  9322. Trans.prototype.replace = function(keyword, replacer, options) {
  9323. console.log("entering trans.search");
  9324. if (typeof keyword == "undefined") return null;
  9325. if (typeof keyword.length <=1) return t("Keyword too short!");
  9326. if (typeof trans.project == "undefined") return null;
  9327. if (typeof trans.project.files == "undefined") return null;
  9328. replacer = replacer||"";
  9329. options = options|| {};
  9330. options.caseSensitive = options.caseSensitive||false;
  9331. options.isRegexp = options.isRegexp||false;
  9332. if (Array.isArray(options.files) == false) {
  9333. options.files = [];
  9334. for (var file in trans.project.files) {
  9335. options.files.push(file);
  9336. }
  9337. }
  9338. if (options.caseSensitive == false && options.isRegexp == false) {
  9339. keyword = keyword.toLowerCase();
  9340. }
  9341. var start = new Date().getTime();
  9342. var result = {
  9343. 'keyword':keyword,
  9344. count:0,
  9345. isRegexp:options.isRegexp,
  9346. executionTime:0,
  9347. files:{}
  9348. };
  9349. // check if regexp is valid
  9350. if (options.isRegexp) {
  9351. var keywordExp = common.evalRegExpStr(keyword);
  9352. if (keywordExp == false) {
  9353. alert(keyword+t(" is not a valid javascript's regexp!\r\nFind out more about Javascipt's Regular Expression at :\r\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"));
  9354. return result;
  9355. }
  9356. }
  9357. //for (var file in trans.project.files) {
  9358. for (let cont in options.files) {
  9359. let file = options.files[cont];
  9360. if (Array.isArray(trans.project.files[file].data) == false) continue;
  9361. let currentFile = trans.project.files[file].data;
  9362. //console.log("handling file : ", file, currentFile);
  9363. for (let row=0; row<currentFile.length; row++) {
  9364. if (currentFile[row].length == 0) continue;
  9365. for (let col=1; col<currentFile[row].length; col++) { // skip first row
  9366. if (typeof currentFile[row][col] !== "string") continue;
  9367. if (options.isRegexp) {
  9368. // regular expression search
  9369. if (keywordExp.test(currentFile[row][col])) {
  9370. // match found
  9371. let original = trans.project.files[file].data[row][col];
  9372. trans.project.files[file].data[row][col] = currentFile[row][col].replace(keywordExp, replacer);
  9373. result.files[file] = result.files[file]||[];
  9374. result.files[file].push({
  9375. 'fullString':trans.project.files[file].data[row][col],
  9376. 'row':row,
  9377. 'col':col,
  9378. 'originalString' : original
  9379. });
  9380. result.count++;
  9381. break;
  9382. }
  9383. continue;
  9384. }
  9385. // normal search
  9386. if (options.caseSensitive) {
  9387. if (currentFile[row][col].indexOf(keyword) == -1) continue;
  9388. } else {
  9389. if (currentFile[row][col].toLowerCase().indexOf(keyword) == -1) continue;
  9390. }
  9391. let original = trans.project.files[file].data[row][col];
  9392. trans.project.files[file].data[row][col] = currentFile[row][col].replaces(keyword, replacer, !options.caseSensitive);
  9393. result.files[file] = result.files[file]||[];
  9394. result.files[file].push({
  9395. 'fullString':trans.project.files[file].data[row][col],
  9396. 'row':row,
  9397. 'col':col,
  9398. 'originalString' : original
  9399. });
  9400. result.count++;
  9401. }
  9402. }
  9403. }
  9404. var end = new Date().getTime();
  9405. result.executionTime = end - start;
  9406. trans.refreshGrid();
  9407. //trans.selectFile($(".fileList .selected"));
  9408. return result;
  9409. }
  9410. /**
  9411. * Search for some keyword and put the text on target column
  9412. * @param {String} keyword - Keyword
  9413. * @param {String} put - The text to put into
  9414. * @param {Number} targetCOl - The index of the column to put into
  9415. * @param {Object} options
  9416. * @param {Boolean} [options.caseSensitive] - Whether the search is in case sensitive mode or not
  9417. * @param {Boolean} [options.lineMatch] - Whether the search is with the line match mode or not
  9418. * @param {Boolean} [options.isRegexp] - Whether the keyword is a regexp or not
  9419. * @returns {SearchResult} the search result
  9420. */
  9421. Trans.prototype.findPut = function(keyword, put, targetCol, options) {
  9422. console.log("entering trans.search");
  9423. if (typeof keyword == "undefined") return null;
  9424. if (typeof keyword.length <=1) return t("Keyword too short!");
  9425. if (typeof trans.project == "undefined") return null;
  9426. if (typeof trans.project.files == "undefined") return null;
  9427. if (targetCol < 1) return false;
  9428. options = options|| {};
  9429. options.caseSensitive = options.caseSensitive||false;
  9430. options.lineMatch = options.lineMatch||false;
  9431. if (typeof options.overwrite == "undefined") options.overwrite = true;
  9432. if (Array.isArray(options.files) == false) {
  9433. options.files = [];
  9434. for (var file in trans.project.files) {
  9435. options.files.push(file);
  9436. }
  9437. }
  9438. if (options.caseSensitive == false) {
  9439. keyword = keyword.toLowerCase();
  9440. }
  9441. var start = new Date().getTime();
  9442. var result = {
  9443. keyword :keyword,
  9444. count :0,
  9445. executionTime:0,
  9446. files:{}
  9447. };
  9448. // todo: If keyword contains more than one line, then use row by row matching
  9449. if (keyword.includes("\n") || options.mode=="rowByRow") {
  9450. console.log("Entering row by row search");
  9451. result = this.findAndInsert(keyword, put, targetCol , {
  9452. insensitive : !options.caseSensitive,
  9453. overwrite : options.overwrite
  9454. });
  9455. } else {
  9456. //line match algorithm
  9457. for (let cont in options.files) {
  9458. let file = options.files[cont];
  9459. if (Array.isArray(trans.project.files[file].data) == false) continue;
  9460. let currentFile = trans.project.files[file].data;
  9461. for (let row=0; row<currentFile.length; row++) {
  9462. if (currentFile[row].length == 0) continue;
  9463. for (let col=0; col<currentFile[row].length; col++) {
  9464. if (typeof currentFile[row][col] !== "string") continue;
  9465. if (options.caseSensitive) {
  9466. if (currentFile[row][col].indexOf(keyword) == -1) continue;
  9467. } else {
  9468. if (currentFile[row][col].toLowerCase().indexOf(keyword) == -1) continue;
  9469. }
  9470. var lineIndex = common.lineIndex(currentFile[row][col], keyword, options.caseSensitive);
  9471. if (lineIndex != -1) {
  9472. // match found
  9473. var newTxt = common.insertLineAt(currentFile[row][targetCol], put, lineIndex, {
  9474. lineBreak:trans.project.files[file].lineBreak||"\n"
  9475. });
  9476. currentFile[row][targetCol] = newTxt;
  9477. result.files[file] = result.files[file]||[];
  9478. result.files[file].push({
  9479. 'fullString':currentFile[row][col],
  9480. 'row':row,
  9481. 'col':col,
  9482. 'type':'cell',
  9483. 'lineIndex':lineIndex
  9484. });
  9485. result.count++;
  9486. break;
  9487. }
  9488. }
  9489. }
  9490. }
  9491. }
  9492. var end = new Date().getTime();
  9493. result.executionTime = end - start;
  9494. trans.refreshGrid();
  9495. return result;
  9496. }
  9497. /**
  9498. * Hooks
  9499. */
  9500. class TransProjectHook{
  9501. constructor () {
  9502. this.hooks = {}
  9503. }
  9504. }
  9505. TransProjectHook.prototype.defineHook = function(hookName, fn) {
  9506. if (typeof hookName !== "string") throw new Error(`hookName must be a string ${typeof hookName} given`)
  9507. if (typeof fn !== "function") throw new Error(`hookName must be a function ${typeof fn} given`)
  9508. this.hooks[hookName] = fn;
  9509. }
  9510. TransProjectHook.prototype.getHook = function(hookName) {
  9511. return this.hooks[hookName];
  9512. }
  9513. TransProjectHook.prototype.run = async function(hookName, ...args) {
  9514. if (typeof this.hooks[hookName] == "function") {
  9515. await this.hooks[hookName].apply(window.trans, args);
  9516. }
  9517. // if not defined then look for the setting in trans.project.options.hooks
  9518. const hooks = trans.getOption("hooks");
  9519. if (!hooks) return;
  9520. if (typeof hooks?.afterExport !== "string") return;
  9521. const userConsent = await ui.confirmRunScript();
  9522. if (!userConsent) return;
  9523. let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
  9524. const newFunc = new AsyncFunction(hooks.afterExport);
  9525. const execResult = newFunc.apply(trans, args);
  9526. return execResult;
  9527. }
  9528. //================================================================
  9529. // NEW TRANS INSTANCE
  9530. //================================================================
  9531. /**
  9532. * @namespace
  9533. * @instance
  9534. */
  9535. var trans = new Trans()
  9536. window.trans = trans;
  9537. trans.cellInfo = new Trans.CellInfo();
  9538. trans.projectHook = new TransProjectHook();
  9539. //trans.projectHook.hooks = require("www/js/trans.projecthooks.js");
  9540. /**
  9541. * Grid context menu object
  9542. * @memberof! Trans#
  9543. */
  9544. trans.gridContextMenu = {
  9545. 'commentsAddEdit': {
  9546. name: t("Add comment"),
  9547. hidden: function() {
  9548. if (trans.grid.isColumnHeaderSelected()) return true;
  9549. if (trans.grid.isRowHeaderSelected()) return true;
  9550. return false;
  9551. }
  9552. },
  9553. 'commentsRemove':{
  9554. name: t("Delete comment"),
  9555. hidden: function() {
  9556. if (trans.grid.isColumnHeaderSelected()) return true;
  9557. if (trans.grid.isRowHeaderSelected()) return true;
  9558. return false;
  9559. }
  9560. },
  9561. "sepx": '---------',
  9562. 'translateThisCell':{
  9563. name: function() {
  9564. var def = "<span class='HOTMenuTranslateHere'>"+t("Translate here")+" <kbd>ctrl+g</kbd></span>";
  9565. if (typeof trans.project == 'undefined') return def;
  9566. trans.project.options = trans.project.options||{};
  9567. var thisTrans = trans.getActiveTranslator()
  9568. console.log("thisTrans", thisTrans);
  9569. if (typeof thisTrans == 'undefined') return def;
  9570. var from = trans.getSl()||"??";
  9571. var to = trans.getTl()||"??";
  9572. var thisTranslatorName = trans.getTranslatorEngine(thisTrans)?.name;
  9573. if (!thisTranslatorName) return def;
  9574. return t("Translate here using ")+thisTranslatorName+" ("+from+"<i class='icon-right-bold'></i>"+to+") <kbd>ctrl+g</kbd>"
  9575. },
  9576. callback: function() {
  9577. trans.translateSelection();
  9578. },
  9579. hidden: function() {
  9580. if (trans.grid.isColumnHeaderSelected()) return true;
  9581. if (trans.grid.isRowHeaderSelected()) return true;
  9582. if (!trans.getActiveTranslator()) return true;
  9583. return false;
  9584. }
  9585. },
  9586. 'translateUsing': {
  9587. name: function() {
  9588. trans.drawGridTranslatorMenu();
  9589. return t('Translate using...')
  9590. },
  9591. submenu: {
  9592. items: []
  9593. },
  9594. hidden: function() {
  9595. if (trans.grid.isRowHeaderSelected()) return true;
  9596. return false;
  9597. }
  9598. },
  9599. 'mergeThenTranslate': {
  9600. name: "<span>Merge then translate <kbd>ctrl+shift+g</kbd></span>",
  9601. hidden: function() {
  9602. if (trans.grid.isRowHeaderSelected()) return true;
  9603. return false;
  9604. },
  9605. callback: async function() {
  9606. trans.translateSelectionAsOneLine();
  9607. }
  9608. },
  9609. 'translateSimiliar': {
  9610. name: "<span>Translate like this <kbd>ctrl+l</kbd></span>",
  9611. hidden: function() {
  9612. if (trans.grid.isRowHeaderSelected()) return true;
  9613. return false;
  9614. },
  9615. callback: async function() {
  9616. var conf = confirm(t("Do you want to translate all the same texts found across this project with the translation on the selected cell(s)?"))
  9617. if (!conf) return;
  9618. var result = await trans.translateAllBySelectedCells();
  9619. alert(result.length + t(` cell(s) has been written!`))
  9620. }
  9621. },
  9622. '---------':{},
  9623. 'columnWidth': {
  9624. name: t("Column width"),
  9625. callback: function(origin, selection, e) {
  9626. console.log("column width : ", arguments);
  9627. var cols = common.gridSelectedCols();
  9628. var width = prompt("Enter new width", this.getColWidth(cols[0]));
  9629. width = parseInt(width);
  9630. if (width < 1) return alert(t("Width must greater than 0"))
  9631. for (var i=0; i<cols.length; i++) {
  9632. this.setColWidth(cols[i], width)
  9633. }
  9634. },
  9635. hidden: function() {
  9636. if (this.isColumnHeaderSelected()) return false;
  9637. if (this.isRowHeaderSelected()) return true;
  9638. return true;
  9639. }
  9640. },
  9641. 'sepn' :{
  9642. name: '---------',
  9643. hidden: function() {
  9644. if (this.isColumnHeaderSelected()) return false;
  9645. if (this.isRowHeaderSelected()) return true;
  9646. return true;
  9647. }
  9648. },
  9649. 'col-right': {
  9650. name: t("Insert column right"),
  9651. callback: function() {
  9652. trans.grid.insertColumnRight();
  9653. },
  9654. hidden: function() {
  9655. if (trans.grid.isColumnHeaderSelected()) return false;
  9656. if (trans.grid.isRowHeaderSelected()) return true;
  9657. return true;
  9658. }
  9659. //disabled: false
  9660. },
  9661. 'duplicateCol': {
  9662. name: t("Duplicate column"),
  9663. callback: function() {
  9664. var getCol = trans.grid.getSelected()[0][1];
  9665. var getColSet = trans.columns.length;
  9666. var colHeaderName = trans.colHeaders[getCol]||"New Col";
  9667. //var currentData = trans.grid.getData();
  9668. trans.columns.push({});
  9669. common.arrayExchange(trans.columns, getColSet, getCol + 1);
  9670. common.arrayInsert(trans.colHeaders, getCol+1, colHeaderName);
  9671. //batchArrayInsert(trans.data, getCol+1, null);
  9672. console.log(trans.columns);
  9673. trans.insertCell(getCol+1, null);
  9674. trans.copyCol(getCol, getCol+1);
  9675. trans.grid.updateSettings({
  9676. colHeaders:trans.colHeaders
  9677. })
  9678. //trans.grid.render()
  9679. },
  9680. hidden: function() {
  9681. if (trans.grid.isColumnHeaderSelected()) {
  9682. if (trans.grid.getSelected()[0][1] != trans.grid.getSelected()[0][3] ||
  9683. trans.grid.getSelected().length > 1 ) return true;
  9684. return false;
  9685. }
  9686. return true;
  9687. }
  9688. //disabled: false
  9689. },
  9690. 'removeColumn': {
  9691. name: t("Remove this column"),
  9692. callback: function(origin, selection, e) {
  9693. console.log(arguments);
  9694. var conf = confirm(t("Remove selected column?\nThis can not be undone!"));
  9695. if (conf) {
  9696. trans.removeColumn(selection[0].start.col, {refreshGrid:true});
  9697. }
  9698. },
  9699. hidden: function() {
  9700. if (trans.grid.isColumnHeaderSelected()) return false;
  9701. if (trans.grid.isRowHeaderSelected()) return true;
  9702. return true;
  9703. }
  9704. },
  9705. 'renameColumn': {
  9706. name: t("Rename this column"),
  9707. callback: function(origin, selection, e) {
  9708. console.log(arguments);
  9709. var thisCol = selection[0].start.col;
  9710. var colName = trans.colHeaders[thisCol];
  9711. var conf = prompt(t("Please enter new name"), colName);
  9712. if (conf) {
  9713. trans.renameColumn(thisCol, conf, {refreshGrid:true});
  9714. }
  9715. },
  9716. hidden: function() {
  9717. if (trans.grid.isColumnHeaderSelected()) return false;
  9718. if (trans.grid.isRowHeaderSelected()) return true;
  9719. return true;
  9720. }
  9721. },
  9722. "sep0": '---------',
  9723. 'tags': {
  9724. name:"Tags",
  9725. submenu: {
  9726. items: [
  9727. {
  9728. key: 'tags:red',
  9729. name: '<i class="tag red icon-circle"></i> '+t('Red'),
  9730. callback: function(key, selection, clickEvent) {
  9731. trans.setTagForSelectedRow("red", selection);
  9732. }
  9733. },
  9734. {
  9735. key: 'tags:yellow',
  9736. name: '<i class="tag yellow icon-circle"></i> '+t('Yellow'),
  9737. callback: function(key, selection, clickEvent) {
  9738. trans.setTagForSelectedRow("yellow", selection);
  9739. }
  9740. },
  9741. {
  9742. key: 'tags:green',
  9743. name: '<i class="tag green icon-circle"></i> '+t('Green'),
  9744. callback: function(key, selection, clickEvent) {
  9745. trans.setTagForSelectedRow("green", selection);
  9746. }
  9747. },
  9748. {
  9749. key: 'tags:blue',
  9750. name: '<i class="tag blue icon-circle"></i> '+t('Blue'),
  9751. callback: function(key, selection, clickEvent) {
  9752. trans.setTagForSelectedRow("blue", selection);
  9753. }
  9754. },
  9755. {
  9756. key: 'tags:gold',
  9757. name: '<i class="tag gold icon-circle"></i> '+t('Gold'),
  9758. callback: function(key, selection, clickEvent) {
  9759. trans.setTagForSelectedRow("gold", selection);
  9760. }
  9761. },
  9762. {
  9763. key: 'tags:more',
  9764. name: '<i class="tag icon-tags"></i> '+t('More tags...')+' <kbd>ctrl+t</kbd>',
  9765. callback: function(key, selection, clickEvent) {
  9766. //setTimeout(function() {
  9767. ui.taggingDialog(selection);
  9768. //}, 0);
  9769. }
  9770. },
  9771. {
  9772. key: 'tags:clear',
  9773. name: '<i class="tag icon-blank"></i> '+t('Clear tags'),
  9774. callback: function(key, selection, clickEvent) {
  9775. trans.clearTags(undefined, selection);
  9776. trans.grid.render();
  9777. }
  9778. }
  9779. ]
  9780. }
  9781. },
  9782. "sep1": '---------',
  9783. 'deleteRow': {
  9784. name: function() {
  9785. return t("Delete Row")+" <kbd>shift+del</kbd>"
  9786. },
  9787. callback: function(origin, selection, e) {
  9788. var conf = confirm(t("Do you want to remove the currently selected row(s)?"));
  9789. if (!conf) return;
  9790. trans.removeRow(trans.getSelectedId(), common.gridSelectedRows());
  9791. trans.refreshGrid();
  9792. trans.grid.deselectCell();
  9793. },
  9794. hidden: function() {
  9795. if (trans.grid.isColumnHeaderSelected()) return true;
  9796. if (trans.grid.isRowHeaderSelected()) return false;
  9797. return false;
  9798. }
  9799. },
  9800. 'clearContextTranslation': {
  9801. name: t("Clear Context Translation")+" <kbd>alt+del</kbd>",
  9802. callback: function(origin, selection, e) {
  9803. /**
  9804. * Trigger when user runs Clear Context Translation
  9805. * @event Trans#clearContextTranslationByRow
  9806. * @param {Object} options
  9807. * @param {Object} options.file
  9808. * @param {Object} options.row
  9809. * @param {Object} options.type
  9810. */
  9811. trans.trigger("clearContextTranslationByRow", {file:trans.getSelectedId(), row:trans.grid.getSelectedRange(), type:"range"});
  9812. },
  9813. hidden: function() {
  9814. if (trans.grid.isColumnHeaderSelected()) return true;
  9815. if (trans.grid.isRowHeaderSelected()) return false;
  9816. return false;
  9817. }
  9818. },
  9819. "sep2": '---------',
  9820. 'createAutomation' : {
  9821. name: t("Create Automation"),
  9822. callback: function(origin, selection, e) {
  9823. console.log(arguments);
  9824. var options = {
  9825. workspace: "gridSelection",
  9826. cellRange: trans.grid.getSelectedRange()
  9827. }
  9828. ui.openAutomationEditor("codeEditor_gridSelection", options);
  9829. }
  9830. },
  9831. 'runAutomation' : {
  9832. name: ()=> {
  9833. trans.updateRunScriptGridMenu();
  9834. return t("Run Automation");
  9835. }
  9836. },
  9837. 'clearAutomation' : {
  9838. name: t("Clear Automation"),
  9839. callback: function() {
  9840. var conf = confirm(t("Are you sure want to clear all quick launch scripts?"));
  9841. if (!conf) return;
  9842. sys.setConfig("codeEditor/gridSelection", {quickLaunch:[]});
  9843. sys.saveConfig();
  9844. }
  9845. },
  9846. "sep3": '---------',
  9847. 'appendToReference': {
  9848. name: t("Append rows to reference")+" <kbd>ctrl+shift+d</kbd>",
  9849. callback: function(origin, selection, e) {
  9850. trans.appendSelectedRowToReference();
  9851. },
  9852. hidden: function() {
  9853. if (trans.grid.isColumnHeaderSelected()) return true;
  9854. return false;
  9855. }
  9856. },
  9857. 'properties': {
  9858. name: t("Row properties"),
  9859. callback: function(origin, selection, e) {
  9860. console.log(arguments);
  9861. ui.openRowProperties();
  9862. },
  9863. hidden: function() {
  9864. if (trans.grid.isColumnHeaderSelected()) return true;
  9865. if (trans.grid.isRowHeaderSelected()) return false;
  9866. return false;
  9867. }
  9868. }
  9869. /*
  9870. ,
  9871. "colors": { // Own custom option
  9872. name: 'Colors...',
  9873. submenu: {
  9874. // Custom option with submenu of items
  9875. items: [
  9876. {
  9877. // Key must be in the form "parent_key:child_key"
  9878. key: 'colors:red',
  9879. name: 'Red',
  9880. callback: function(key, selection, clickEvent) {
  9881. setTimeout(function() {
  9882. alert('You clicked red!');
  9883. }, 0);
  9884. }
  9885. },
  9886. { key: 'colors:green', name: 'Green' },
  9887. { key: 'colors:blue', name: 'Blue' }
  9888. ]
  9889. }
  9890. },
  9891. "credits": { // Own custom property
  9892. // Custom rendered element in the context menu
  9893. renderer: function(hot, wrapper, row, col, prop, itemValue) {
  9894. console.log("rendering credits");
  9895. console.log(arguments);
  9896. var elem = document.createElement('marquee');
  9897. elem.style.cssText = 'background: lightgray;';
  9898. elem.textContent = 'Brought to you by...';
  9899. return elem;
  9900. },
  9901. disableSelection: true, // Prevent mouseoever from highlighting the item for selection
  9902. isCommand: false // Prevent clicks from executing command and closing the menu
  9903. },
  9904. "about": { // Own custom option
  9905. name: function () { // `name` can be a string or a function
  9906. return '<b>Custom option</b>'; // Name can contain HTML
  9907. },
  9908. hidden: function () { // `hidden` can be a boolean or a function
  9909. // Hide the option when the first column was clicked
  9910. console.log(trans.grid.isColumnHeaderSelected());
  9911. if (trans.grid.isColumnHeaderSelected()) return false;
  9912. //return this.getSelectedLast()[1] == 0; // `this` === hot3
  9913. return true;
  9914. },
  9915. callback: function(key, selection, clickEvent) { // Callback for specific option
  9916. setTimeout(function() {
  9917. alert('Hello world!'); // Fire alert after menu close (with timeout)
  9918. }, 0);
  9919. }
  9920. }
  9921. */
  9922. }
  9923. // backup current settings for close / new project actions
  9924. //var transTemplate = JSON.parse(JSON.stringify(trans));
  9925. trans.fileLoader = new FileLoader();
  9926. trans.fileLoader.add("json", function(path) {
  9927. trans.open(path);
  9928. })
  9929. trans.fileLoader.add("trans", function(path) {
  9930. trans.open(path);
  9931. })
  9932. trans.fileLoader.add("tpp", function(path) {
  9933. //trans.importTpp(openedFile);
  9934. trans.importTpp(path);
  9935. })
  9936. /**
  9937. * Attachment object.
  9938. * Located at trans.project.attachments
  9939. * @class
  9940. * @param {Object} obj
  9941. */
  9942. window.Attachment = function(obj) {
  9943. obj = obj || {};
  9944. Object.assign(this, obj);
  9945. }
  9946. // ==============================================================
  9947. //
  9948. // E V E N T S
  9949. //
  9950. // ==============================================================
  9951. $(document).ready(function() {
  9952. if ($('body').is('[data-window="trans"]') == false) return;
  9953. trans.fileSelectorContextMenuInit();
  9954. //trans.gridBodyContextMenu();
  9955. const windowOnResize = function() {
  9956. $(document).trigger("windowResizeStop");
  9957. trans.grid.render();
  9958. ui.fixCellInfoSize();
  9959. }
  9960. $(window).resize(debounce(windowOnResize, 100));
  9961. trans.initTable();
  9962. trans.isLoaded = true;
  9963. // project level button initialization
  9964. trans.on("transLoaded", async ()=> {
  9965. console.warn("Trans loaded");
  9966. $(".menu-button > .button-gridInfo.gridInfo").removeClass("checked")
  9967. if (trans.getOption("gridInfo")?.isRuleActive) $(".menu-button > .button-gridInfo.gridInfo").addClass("checked")
  9968. })
  9969. });