utils.js 7.6 KB

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