utils.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. FS.mkdir('/userfs');
  32. FS.mount(IDBFS, {}, '/userfs');
  33. function createRecursive(dir) {
  34. try {
  35. FS.stat(dir);
  36. } catch (e) {
  37. if (e.errno !== ERRNO_CODES.ENOENT) {
  38. throw e;
  39. }
  40. FS.mkdirTree(dir);
  41. }
  42. }
  43. persistentPaths.forEach(function(path) {
  44. createRecursive(path);
  45. FS.mount(IDBFS, {}, path);
  46. });
  47. return new Promise(function(resolve, reject) {
  48. FS.syncfs(true, function(err) {
  49. if (err) {
  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['copyToFS'] = function(path, buffer) {
  60. var p = path.lastIndexOf("/");
  61. var dir = "/";
  62. if (p > 0) {
  63. dir = path.slice(0, path.lastIndexOf("/"));
  64. }
  65. try {
  66. FS.stat(dir);
  67. } catch (e) {
  68. if (e.errno !== ERRNO_CODES.ENOENT) {
  69. throw e;
  70. }
  71. FS.mkdirTree(dir);
  72. }
  73. // With memory growth, canOwn should be false.
  74. FS.writeFile(path, new Uint8Array(buffer), {'flags': 'wx+'});
  75. }
  76. Module.drop_handler = (function() {
  77. var upload = [];
  78. var uploadPromises = [];
  79. var uploadCallback = null;
  80. function readFilePromise(entry, path) {
  81. return new Promise(function(resolve, reject) {
  82. entry.file(function(file) {
  83. var reader = new FileReader();
  84. reader.onload = function() {
  85. var f = {
  86. "path": file.relativePath || file.webkitRelativePath,
  87. "name": file.name,
  88. "type": file.type,
  89. "size": file.size,
  90. "data": reader.result
  91. };
  92. if (!f['path'])
  93. f['path'] = f['name'];
  94. upload.push(f);
  95. resolve()
  96. };
  97. reader.onerror = function() {
  98. console.log("Error reading file");
  99. reject();
  100. }
  101. reader.readAsArrayBuffer(file);
  102. }, function(err) {
  103. console.log("Error!");
  104. reject();
  105. });
  106. });
  107. }
  108. function readDirectoryPromise(entry) {
  109. return new Promise(function(resolve, reject) {
  110. var reader = entry.createReader();
  111. reader.readEntries(function(entries) {
  112. for (var i = 0; i < entries.length; i++) {
  113. var ent = entries[i];
  114. if (ent.isDirectory) {
  115. uploadPromises.push(readDirectoryPromise(ent));
  116. } else if (ent.isFile) {
  117. uploadPromises.push(readFilePromise(ent));
  118. }
  119. }
  120. resolve();
  121. });
  122. });
  123. }
  124. function processUploadsPromises(resolve, reject) {
  125. if (uploadPromises.length == 0) {
  126. resolve();
  127. return;
  128. }
  129. uploadPromises.pop().then(function() {
  130. setTimeout(function() {
  131. processUploadsPromises(resolve, reject);
  132. //processUploadsPromises.bind(null, resolve, reject)
  133. }, 0);
  134. });
  135. }
  136. function dropFiles(files) {
  137. var args = files || [];
  138. var argc = args.length;
  139. var argv = stackAlloc((argc + 1) * 4);
  140. for (var i = 0; i < argc; i++) {
  141. HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i]);
  142. }
  143. HEAP32[(argv >> 2) + argc] = 0;
  144. // Defined in javascript_main.cpp
  145. ccall('_drop_files_callback', 'void', ['number', 'number'], [argv, argc]);
  146. }
  147. return function(ev) {
  148. ev.preventDefault();
  149. if (ev.dataTransfer.items) {
  150. // Use DataTransferItemList interface to access the file(s)
  151. for (var i = 0; i < ev.dataTransfer.items.length; i++) {
  152. const item = ev.dataTransfer.items[i];
  153. var entry = null;
  154. if ("getAsEntry" in item) {
  155. entry = item.getAsEntry();
  156. } else if ("webkitGetAsEntry" in item) {
  157. entry = item.webkitGetAsEntry();
  158. }
  159. if (!entry) {
  160. console.error("File upload not supported");
  161. } else if (entry.isDirectory) {
  162. uploadPromises.push(readDirectoryPromise(entry));
  163. } else if (entry.isFile) {
  164. uploadPromises.push(readFilePromise(entry));
  165. } else {
  166. console.error("Unrecognized entry...", entry);
  167. }
  168. }
  169. } else {
  170. console.error("File upload not supported");
  171. }
  172. uploadCallback = new Promise(processUploadsPromises).then(function() {
  173. const DROP = "/tmp/drop-" + parseInt(Math.random() * Math.pow(2, 31)) + "/";
  174. var drops = [];
  175. var files = [];
  176. upload.forEach((elem) => {
  177. var path = elem['path'];
  178. Module['copyToFS'](DROP + path, elem['data']);
  179. var idx = path.indexOf("/");
  180. if (idx == -1) {
  181. // Root file
  182. drops.push(DROP + path);
  183. } else {
  184. // Subdir
  185. var sub = path.substr(0, idx);
  186. idx = sub.indexOf("/");
  187. if (idx < 0 && drops.indexOf(DROP + sub) == -1) {
  188. drops.push(DROP + sub);
  189. }
  190. }
  191. files.push(DROP + path);
  192. });
  193. uploadPromises = [];
  194. upload = [];
  195. dropFiles(drops);
  196. var dirs = [DROP.substr(0, DROP.length -1)];
  197. files.forEach(function (file) {
  198. FS.unlink(file);
  199. var dir = file.replace(DROP, "");
  200. var idx = dir.lastIndexOf("/");
  201. while (idx > 0) {
  202. dir = dir.substr(0, idx);
  203. if (dirs.indexOf(DROP + dir) == -1) {
  204. dirs.push(DROP + dir);
  205. }
  206. idx = dir.lastIndexOf("/");
  207. }
  208. });
  209. // Remove dirs.
  210. dirs = dirs.sort(function(a, b) {
  211. var al = (a.match(/\//g) || []).length;
  212. var bl = (b.match(/\//g) || []).length;
  213. if (al > bl)
  214. return -1;
  215. else if (al < bl)
  216. return 1;
  217. return 0;
  218. });
  219. dirs.forEach(function(dir) {
  220. FS.rmdir(dir);
  221. });
  222. });
  223. }
  224. })();
  225. function EventHandlers() {
  226. function Handler(target, event, method, capture) {
  227. this.target = target;
  228. this.event = event;
  229. this.method = method;
  230. this.capture = capture;
  231. }
  232. var listeners = [];
  233. function has(target, event, method, capture) {
  234. return listeners.findIndex(function(e) {
  235. return e.target === target && e.event === event && e.method === method && e.capture == capture;
  236. }) !== -1;
  237. }
  238. this.add = function(target, event, method, capture) {
  239. if (has(target, event, method, capture)) {
  240. return;
  241. }
  242. listeners.push(new Handler(target, event, method, capture));
  243. target.addEventListener(event, method, capture);
  244. };
  245. this.remove = function(target, event, method, capture) {
  246. if (!has(target, event, method, capture)) {
  247. return;
  248. }
  249. target.removeEventListener(event, method, capture);
  250. };
  251. this.clear = function() {
  252. listeners.forEach(function(h) {
  253. h.target.removeEventListener(h.event, h.method, h.capture);
  254. });
  255. listeners.length = 0;
  256. };
  257. }
  258. Module.listeners = new EventHandlers();