library_godot_os.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*************************************************************************/
  2. /* library_godot_os.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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. const IDHandler = {
  31. $IDHandler: {
  32. _last_id: 0,
  33. _references: {},
  34. get: function (p_id) {
  35. return IDHandler._references[p_id];
  36. },
  37. add: function (p_data) {
  38. const id = ++IDHandler._last_id;
  39. IDHandler._references[id] = p_data;
  40. return id;
  41. },
  42. remove: function (p_id) {
  43. delete IDHandler._references[p_id];
  44. },
  45. },
  46. };
  47. autoAddDeps(IDHandler, '$IDHandler');
  48. mergeInto(LibraryManager.library, IDHandler);
  49. const GodotConfig = {
  50. $GodotConfig__postset: 'Module["initConfig"] = GodotConfig.init_config;',
  51. $GodotConfig__deps: ['$GodotRuntime'],
  52. $GodotConfig: {
  53. canvas: null,
  54. locale: 'en',
  55. canvas_resize_policy: 2, // Adaptive
  56. virtual_keyboard: false,
  57. persistent_drops: false,
  58. on_execute: null,
  59. on_exit: null,
  60. init_config: function (p_opts) {
  61. GodotConfig.canvas_resize_policy = p_opts['canvasResizePolicy'];
  62. GodotConfig.canvas = p_opts['canvas'];
  63. GodotConfig.locale = p_opts['locale'] || GodotConfig.locale;
  64. GodotConfig.virtual_keyboard = p_opts['virtualKeyboard'];
  65. GodotConfig.persistent_drops = !!p_opts['persistentDrops'];
  66. GodotConfig.on_execute = p_opts['onExecute'];
  67. GodotConfig.on_exit = p_opts['onExit'];
  68. },
  69. locate_file: function (file) {
  70. return Module['locateFile'](file); // eslint-disable-line no-undef
  71. },
  72. clear: function () {
  73. GodotConfig.canvas = null;
  74. GodotConfig.locale = 'en';
  75. GodotConfig.canvas_resize_policy = 2;
  76. GodotConfig.virtual_keyboard = false;
  77. GodotConfig.persistent_drops = false;
  78. GodotConfig.on_execute = null;
  79. GodotConfig.on_exit = null;
  80. },
  81. },
  82. godot_js_config_canvas_id_get__sig: 'vii',
  83. godot_js_config_canvas_id_get: function (p_ptr, p_ptr_max) {
  84. GodotRuntime.stringToHeap(`#${GodotConfig.canvas.id}`, p_ptr, p_ptr_max);
  85. },
  86. godot_js_config_locale_get__sig: 'vii',
  87. godot_js_config_locale_get: function (p_ptr, p_ptr_max) {
  88. GodotRuntime.stringToHeap(GodotConfig.locale, p_ptr, p_ptr_max);
  89. },
  90. };
  91. autoAddDeps(GodotConfig, '$GodotConfig');
  92. mergeInto(LibraryManager.library, GodotConfig);
  93. const GodotFS = {
  94. $GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'],
  95. $GodotFS__postset: [
  96. 'Module["initFS"] = GodotFS.init;',
  97. 'Module["copyToFS"] = GodotFS.copy_to_fs;',
  98. ].join(''),
  99. $GodotFS: {
  100. _idbfs: false,
  101. _syncing: false,
  102. _mount_points: [],
  103. is_persistent: function () {
  104. return GodotFS._idbfs ? 1 : 0;
  105. },
  106. // Initialize godot file system, setting up persistent paths.
  107. // Returns a promise that resolves when the FS is ready.
  108. // We keep track of mount_points, so that we can properly close the IDBFS
  109. // since emscripten is not doing it by itself. (emscripten GH#12516).
  110. init: function (persistentPaths) {
  111. GodotFS._idbfs = false;
  112. if (!Array.isArray(persistentPaths)) {
  113. return Promise.reject(new Error('Persistent paths must be an array'));
  114. }
  115. if (!persistentPaths.length) {
  116. return Promise.resolve();
  117. }
  118. GodotFS._mount_points = persistentPaths.slice();
  119. function createRecursive(dir) {
  120. try {
  121. FS.stat(dir);
  122. } catch (e) {
  123. if (e.errno !== ERRNO_CODES.ENOENT) {
  124. throw e;
  125. }
  126. FS.mkdirTree(dir);
  127. }
  128. }
  129. GodotFS._mount_points.forEach(function (path) {
  130. createRecursive(path);
  131. FS.mount(IDBFS, {}, path);
  132. });
  133. return new Promise(function (resolve, reject) {
  134. FS.syncfs(true, function (err) {
  135. if (err) {
  136. GodotFS._mount_points = [];
  137. GodotFS._idbfs = false;
  138. GodotRuntime.print(`IndexedDB not available: ${err.message}`);
  139. } else {
  140. GodotFS._idbfs = true;
  141. }
  142. resolve(err);
  143. });
  144. });
  145. },
  146. // Deinit godot file system, making sure to unmount file systems, and close IDBFS(s).
  147. deinit: function () {
  148. GodotFS._mount_points.forEach(function (path) {
  149. try {
  150. FS.unmount(path);
  151. } catch (e) {
  152. GodotRuntime.print('Already unmounted', e);
  153. }
  154. if (GodotFS._idbfs && IDBFS.dbs[path]) {
  155. IDBFS.dbs[path].close();
  156. delete IDBFS.dbs[path];
  157. }
  158. });
  159. GodotFS._mount_points = [];
  160. GodotFS._idbfs = false;
  161. GodotFS._syncing = false;
  162. },
  163. sync: function () {
  164. if (GodotFS._syncing) {
  165. GodotRuntime.error('Already syncing!');
  166. return Promise.resolve();
  167. }
  168. GodotFS._syncing = true;
  169. return new Promise(function (resolve, reject) {
  170. FS.syncfs(false, function (error) {
  171. if (error) {
  172. GodotRuntime.error(`Failed to save IDB file system: ${error.message}`);
  173. }
  174. GodotFS._syncing = false;
  175. resolve(error);
  176. });
  177. });
  178. },
  179. // Copies a buffer to the internal file system. Creating directories recursively.
  180. copy_to_fs: function (path, buffer) {
  181. const idx = path.lastIndexOf('/');
  182. let dir = '/';
  183. if (idx > 0) {
  184. dir = path.slice(0, idx);
  185. }
  186. try {
  187. FS.stat(dir);
  188. } catch (e) {
  189. if (e.errno !== ERRNO_CODES.ENOENT) {
  190. throw e;
  191. }
  192. FS.mkdirTree(dir);
  193. }
  194. FS.writeFile(path, new Uint8Array(buffer));
  195. },
  196. },
  197. };
  198. mergeInto(LibraryManager.library, GodotFS);
  199. const GodotOS = {
  200. $GodotOS__deps: ['$GodotRuntime', '$GodotConfig', '$GodotFS'],
  201. $GodotOS__postset: [
  202. 'Module["request_quit"] = function() { GodotOS.request_quit() };',
  203. 'Module["onExit"] = GodotOS.cleanup;',
  204. 'GodotOS._fs_sync_promise = Promise.resolve();',
  205. ].join(''),
  206. $GodotOS: {
  207. request_quit: function () {},
  208. _async_cbs: [],
  209. _fs_sync_promise: null,
  210. atexit: function (p_promise_cb) {
  211. GodotOS._async_cbs.push(p_promise_cb);
  212. },
  213. cleanup: function (exit_code) {
  214. const cb = GodotConfig.on_exit;
  215. GodotFS.deinit();
  216. GodotConfig.clear();
  217. if (cb) {
  218. cb(exit_code);
  219. }
  220. },
  221. finish_async: function (callback) {
  222. GodotOS._fs_sync_promise.then(function (err) {
  223. const promises = [];
  224. GodotOS._async_cbs.forEach(function (cb) {
  225. promises.push(new Promise(cb));
  226. });
  227. return Promise.all(promises);
  228. }).then(function () {
  229. return GodotFS.sync(); // Final FS sync.
  230. }).then(function (err) {
  231. // Always deferred.
  232. setTimeout(function () {
  233. callback();
  234. }, 0);
  235. });
  236. },
  237. },
  238. godot_js_os_finish_async__sig: 'vi',
  239. godot_js_os_finish_async: function (p_callback) {
  240. const func = GodotRuntime.get_func(p_callback);
  241. GodotOS.finish_async(func);
  242. },
  243. godot_js_os_request_quit_cb__sig: 'vi',
  244. godot_js_os_request_quit_cb: function (p_callback) {
  245. GodotOS.request_quit = GodotRuntime.get_func(p_callback);
  246. },
  247. godot_js_os_fs_is_persistent__sig: 'i',
  248. godot_js_os_fs_is_persistent: function () {
  249. return GodotFS.is_persistent();
  250. },
  251. godot_js_os_fs_sync__sig: 'vi',
  252. godot_js_os_fs_sync: function (callback) {
  253. const func = GodotRuntime.get_func(callback);
  254. GodotOS._fs_sync_promise = GodotFS.sync();
  255. GodotOS._fs_sync_promise.then(function (err) {
  256. func();
  257. });
  258. },
  259. godot_js_os_execute__sig: 'ii',
  260. godot_js_os_execute: function (p_json) {
  261. const json_args = GodotRuntime.parseString(p_json);
  262. const args = JSON.parse(json_args);
  263. if (GodotConfig.on_execute) {
  264. GodotConfig.on_execute(args);
  265. return 0;
  266. }
  267. return 1;
  268. },
  269. godot_js_os_shell_open__sig: 'vi',
  270. godot_js_os_shell_open: function (p_uri) {
  271. window.open(GodotRuntime.parseString(p_uri), '_blank');
  272. },
  273. godot_js_os_hw_concurrency_get__sig: 'i',
  274. godot_js_os_hw_concurrency_get: function () {
  275. return navigator.hardwareConcurrency || 1;
  276. },
  277. godot_js_os_download_buffer__sig: 'viiii',
  278. godot_js_os_download_buffer: function (p_ptr, p_size, p_name, p_mime) {
  279. const buf = GodotRuntime.heapSlice(HEAP8, p_ptr, p_size);
  280. const name = GodotRuntime.parseString(p_name);
  281. const mime = GodotRuntime.parseString(p_mime);
  282. const blob = new Blob([buf], { type: mime });
  283. const url = window.URL.createObjectURL(blob);
  284. const a = document.createElement('a');
  285. a.href = url;
  286. a.download = name;
  287. a.style.display = 'none';
  288. document.body.appendChild(a);
  289. a.click();
  290. a.remove();
  291. window.URL.revokeObjectURL(url);
  292. },
  293. };
  294. autoAddDeps(GodotOS, '$GodotOS');
  295. mergeInto(LibraryManager.library, GodotOS);