utils.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*************************************************************************/
  2. /* utils.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. Module['initFS'] = function(persistentPaths) {
  31. Module.mount_points = ['/userfs'].concat(persistentPaths);
  32. function createRecursive(dir) {
  33. try {
  34. FS.stat(dir);
  35. } catch (e) {
  36. if (e.errno !== ERRNO_CODES.ENOENT) {
  37. throw e;
  38. }
  39. FS.mkdirTree(dir);
  40. }
  41. }
  42. Module.mount_points.forEach(function(path) {
  43. createRecursive(path);
  44. FS.mount(IDBFS, {}, path);
  45. });
  46. return new Promise(function(resolve, reject) {
  47. FS.syncfs(true, function(err) {
  48. if (err) {
  49. Module.mount_points = [];
  50. Module.idbfs = false;
  51. console.log("IndexedDB not available: " + err.message);
  52. } else {
  53. Module.idbfs = true;
  54. }
  55. resolve(err);
  56. });
  57. });
  58. };
  59. Module['deinitFS'] = function() {
  60. Module.mount_points.forEach(function(path) {
  61. try {
  62. FS.unmount(path);
  63. } catch (e) {
  64. console.log("Already unmounted", e);
  65. }
  66. if (Module.idbfs && IDBFS.dbs[path]) {
  67. IDBFS.dbs[path].close();
  68. delete IDBFS.dbs[path];
  69. }
  70. });
  71. Module.mount_points = [];
  72. };
  73. Module['copyToFS'] = function(path, buffer) {
  74. var p = path.lastIndexOf("/");
  75. var dir = "/";
  76. if (p > 0) {
  77. dir = path.slice(0, path.lastIndexOf("/"));
  78. }
  79. try {
  80. FS.stat(dir);
  81. } catch (e) {
  82. if (e.errno !== ERRNO_CODES.ENOENT) {
  83. throw e;
  84. }
  85. FS.mkdirTree(dir);
  86. }
  87. // With memory growth, canOwn should be false.
  88. FS.writeFile(path, new Uint8Array(buffer), {'flags': 'wx+'});
  89. }
  90. Module.drop_handler = (function() {
  91. var upload = [];
  92. var uploadPromises = [];
  93. var uploadCallback = null;
  94. function readFilePromise(entry, path) {
  95. return new Promise(function(resolve, reject) {
  96. entry.file(function(file) {
  97. var reader = new FileReader();
  98. reader.onload = function() {
  99. var f = {
  100. "path": file.relativePath || file.webkitRelativePath,
  101. "name": file.name,
  102. "type": file.type,
  103. "size": file.size,
  104. "data": reader.result
  105. };
  106. if (!f['path'])
  107. f['path'] = f['name'];
  108. upload.push(f);
  109. resolve()
  110. };
  111. reader.onerror = function() {
  112. console.log("Error reading file");
  113. reject();
  114. }
  115. reader.readAsArrayBuffer(file);
  116. }, function(err) {
  117. console.log("Error!");
  118. reject();
  119. });
  120. });
  121. }
  122. function readDirectoryPromise(entry) {
  123. return new Promise(function(resolve, reject) {
  124. var reader = entry.createReader();
  125. reader.readEntries(function(entries) {
  126. for (var i = 0; i < entries.length; i++) {
  127. var ent = entries[i];
  128. if (ent.isDirectory) {
  129. uploadPromises.push(readDirectoryPromise(ent));
  130. } else if (ent.isFile) {
  131. uploadPromises.push(readFilePromise(ent));
  132. }
  133. }
  134. resolve();
  135. });
  136. });
  137. }
  138. function processUploadsPromises(resolve, reject) {
  139. if (uploadPromises.length == 0) {
  140. resolve();
  141. return;
  142. }
  143. uploadPromises.pop().then(function() {
  144. setTimeout(function() {
  145. processUploadsPromises(resolve, reject);
  146. //processUploadsPromises.bind(null, resolve, reject)
  147. }, 0);
  148. });
  149. }
  150. function dropFiles(files) {
  151. var args = files || [];
  152. var argc = args.length;
  153. var argv = stackAlloc((argc + 1) * 4);
  154. for (var i = 0; i < argc; i++) {
  155. HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i]);
  156. }
  157. HEAP32[(argv >> 2) + argc] = 0;
  158. // Defined in javascript_main.cpp
  159. ccall('_drop_files_callback', 'void', ['number', 'number'], [argv, argc]);
  160. }
  161. return function(ev) {
  162. ev.preventDefault();
  163. if (ev.dataTransfer.items) {
  164. // Use DataTransferItemList interface to access the file(s)
  165. for (var i = 0; i < ev.dataTransfer.items.length; i++) {
  166. const item = ev.dataTransfer.items[i];
  167. var entry = null;
  168. if ("getAsEntry" in item) {
  169. entry = item.getAsEntry();
  170. } else if ("webkitGetAsEntry" in item) {
  171. entry = item.webkitGetAsEntry();
  172. }
  173. if (!entry) {
  174. console.error("File upload not supported");
  175. } else if (entry.isDirectory) {
  176. uploadPromises.push(readDirectoryPromise(entry));
  177. } else if (entry.isFile) {
  178. uploadPromises.push(readFilePromise(entry));
  179. } else {
  180. console.error("Unrecognized entry...", entry);
  181. }
  182. }
  183. } else {
  184. console.error("File upload not supported");
  185. }
  186. uploadCallback = new Promise(processUploadsPromises).then(function() {
  187. const DROP = "/tmp/drop-" + parseInt(Math.random() * Math.pow(2, 31)) + "/";
  188. var drops = [];
  189. var files = [];
  190. upload.forEach((elem) => {
  191. var path = elem['path'];
  192. Module['copyToFS'](DROP + path, elem['data']);
  193. var idx = path.indexOf("/");
  194. if (idx == -1) {
  195. // Root file
  196. drops.push(DROP + path);
  197. } else {
  198. // Subdir
  199. var sub = path.substr(0, idx);
  200. idx = sub.indexOf("/");
  201. if (idx < 0 && drops.indexOf(DROP + sub) == -1) {
  202. drops.push(DROP + sub);
  203. }
  204. }
  205. files.push(DROP + path);
  206. });
  207. uploadPromises = [];
  208. upload = [];
  209. dropFiles(drops);
  210. var dirs = [DROP.substr(0, DROP.length -1)];
  211. files.forEach(function (file) {
  212. FS.unlink(file);
  213. var dir = file.replace(DROP, "");
  214. var idx = dir.lastIndexOf("/");
  215. while (idx > 0) {
  216. dir = dir.substr(0, idx);
  217. if (dirs.indexOf(DROP + dir) == -1) {
  218. dirs.push(DROP + dir);
  219. }
  220. idx = dir.lastIndexOf("/");
  221. }
  222. });
  223. // Remove dirs.
  224. dirs = dirs.sort(function(a, b) {
  225. var al = (a.match(/\//g) || []).length;
  226. var bl = (b.match(/\//g) || []).length;
  227. if (al > bl)
  228. return -1;
  229. else if (al < bl)
  230. return 1;
  231. return 0;
  232. });
  233. dirs.forEach(function(dir) {
  234. FS.rmdir(dir);
  235. });
  236. });
  237. }
  238. })();
  239. function EventHandlers() {
  240. function Handler(target, event, method, capture) {
  241. this.target = target;
  242. this.event = event;
  243. this.method = method;
  244. this.capture = capture;
  245. }
  246. var listeners = [];
  247. function has(target, event, method, capture) {
  248. return listeners.findIndex(function(e) {
  249. return e.target === target && e.event === event && e.method === method && e.capture == capture;
  250. }) !== -1;
  251. }
  252. this.add = function(target, event, method, capture) {
  253. if (has(target, event, method, capture)) {
  254. return;
  255. }
  256. listeners.push(new Handler(target, event, method, capture));
  257. target.addEventListener(event, method, capture);
  258. };
  259. this.remove = function(target, event, method, capture) {
  260. if (!has(target, event, method, capture)) {
  261. return;
  262. }
  263. target.removeEventListener(event, method, capture);
  264. };
  265. this.clear = function() {
  266. listeners.forEach(function(h) {
  267. h.target.removeEventListener(h.event, h.method, h.capture);
  268. });
  269. listeners.length = 0;
  270. };
  271. }
  272. Module.listeners = new EventHandlers();