library_godot_os.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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-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. 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. resize_on_start: false,
  56. on_execute: null,
  57. init_config: function (p_opts) {
  58. GodotConfig.resize_on_start = !!p_opts['resizeCanvasOnStart'];
  59. GodotConfig.canvas = p_opts['canvas'];
  60. GodotConfig.locale = p_opts['locale'] || GodotConfig.locale;
  61. GodotConfig.on_execute = p_opts['onExecute'];
  62. // This is called by emscripten, even if undocumented.
  63. Module['onExit'] = p_opts['onExit']; // eslint-disable-line no-undef
  64. },
  65. locate_file: function (file) {
  66. return Module['locateFile'](file); // eslint-disable-line no-undef
  67. },
  68. },
  69. godot_js_config_canvas_id_get: function (p_ptr, p_ptr_max) {
  70. GodotRuntime.stringToHeap(`#${GodotConfig.canvas.id}`, p_ptr, p_ptr_max);
  71. },
  72. godot_js_config_locale_get: function (p_ptr, p_ptr_max) {
  73. GodotRuntime.stringToHeap(GodotConfig.locale, p_ptr, p_ptr_max);
  74. },
  75. godot_js_config_is_resize_on_start: function () {
  76. return GodotConfig.resize_on_start ? 1 : 0;
  77. },
  78. };
  79. autoAddDeps(GodotConfig, '$GodotConfig');
  80. mergeInto(LibraryManager.library, GodotConfig);
  81. const GodotFS = {
  82. $GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'],
  83. $GodotFS__postset: [
  84. 'Module["initFS"] = GodotFS.init;',
  85. 'Module["deinitFS"] = GodotFS.deinit;',
  86. 'Module["copyToFS"] = GodotFS.copy_to_fs;',
  87. ].join(''),
  88. $GodotFS: {
  89. _idbfs: false,
  90. _syncing: false,
  91. _mount_points: [],
  92. is_persistent: function () {
  93. return GodotFS._idbfs ? 1 : 0;
  94. },
  95. // Initialize godot file system, setting up persistent paths.
  96. // Returns a promise that resolves when the FS is ready.
  97. // We keep track of mount_points, so that we can properly close the IDBFS
  98. // since emscripten is not doing it by itself. (emscripten GH#12516).
  99. init: function (persistentPaths) {
  100. GodotFS._idbfs = false;
  101. if (!Array.isArray(persistentPaths)) {
  102. return Promise.reject(new Error('Persistent paths must be an array'));
  103. }
  104. if (!persistentPaths.length) {
  105. return Promise.resolve();
  106. }
  107. GodotFS._mount_points = persistentPaths.slice();
  108. function createRecursive(dir) {
  109. try {
  110. FS.stat(dir);
  111. } catch (e) {
  112. if (e.errno !== ERRNO_CODES.ENOENT) {
  113. throw e;
  114. }
  115. FS.mkdirTree(dir);
  116. }
  117. }
  118. GodotFS._mount_points.forEach(function (path) {
  119. createRecursive(path);
  120. FS.mount(IDBFS, {}, path);
  121. });
  122. return new Promise(function (resolve, reject) {
  123. FS.syncfs(true, function (err) {
  124. if (err) {
  125. GodotFS._mount_points = [];
  126. GodotFS._idbfs = false;
  127. GodotRuntime.print(`IndexedDB not available: ${err.message}`);
  128. } else {
  129. GodotFS._idbfs = true;
  130. }
  131. resolve(err);
  132. });
  133. });
  134. },
  135. // Deinit godot file system, making sure to unmount file systems, and close IDBFS(s).
  136. deinit: function () {
  137. GodotFS._mount_points.forEach(function (path) {
  138. try {
  139. FS.unmount(path);
  140. } catch (e) {
  141. GodotRuntime.print('Already unmounted', e);
  142. }
  143. if (GodotFS._idbfs && IDBFS.dbs[path]) {
  144. IDBFS.dbs[path].close();
  145. delete IDBFS.dbs[path];
  146. }
  147. });
  148. GodotFS._mount_points = [];
  149. GodotFS._idbfs = false;
  150. GodotFS._syncing = false;
  151. },
  152. sync: function () {
  153. if (GodotFS._syncing) {
  154. GodotRuntime.error('Already syncing!');
  155. return Promise.resolve();
  156. }
  157. GodotFS._syncing = true;
  158. return new Promise(function (resolve, reject) {
  159. FS.syncfs(false, function (error) {
  160. if (error) {
  161. GodotRuntime.error(`Failed to save IDB file system: ${error.message}`);
  162. }
  163. GodotFS._syncing = false;
  164. resolve(error);
  165. });
  166. });
  167. },
  168. // Copies a buffer to the internal file system. Creating directories recursively.
  169. copy_to_fs: function (path, buffer) {
  170. const idx = path.lastIndexOf('/');
  171. let dir = '/';
  172. if (idx > 0) {
  173. dir = path.slice(0, idx);
  174. }
  175. try {
  176. FS.stat(dir);
  177. } catch (e) {
  178. if (e.errno !== ERRNO_CODES.ENOENT) {
  179. throw e;
  180. }
  181. FS.mkdirTree(dir);
  182. }
  183. FS.writeFile(path, new Uint8Array(buffer));
  184. },
  185. },
  186. };
  187. mergeInto(LibraryManager.library, GodotFS);
  188. const GodotOS = {
  189. $GodotOS__deps: ['$GodotFS', '$GodotRuntime'],
  190. $GodotOS__postset: [
  191. 'Module["request_quit"] = function() { GodotOS.request_quit() };',
  192. 'GodotOS._fs_sync_promise = Promise.resolve();',
  193. ].join(''),
  194. $GodotOS: {
  195. request_quit: function () {},
  196. _async_cbs: [],
  197. _fs_sync_promise: null,
  198. atexit: function (p_promise_cb) {
  199. GodotOS._async_cbs.push(p_promise_cb);
  200. },
  201. finish_async: function (callback) {
  202. GodotOS._fs_sync_promise.then(function (err) {
  203. const promises = [];
  204. GodotOS._async_cbs.forEach(function (cb) {
  205. promises.push(new Promise(cb));
  206. });
  207. return Promise.all(promises);
  208. }).then(function () {
  209. return GodotFS.sync(); // Final FS sync.
  210. }).then(function (err) {
  211. // Always deferred.
  212. setTimeout(function () {
  213. callback();
  214. }, 0);
  215. });
  216. },
  217. },
  218. godot_js_os_finish_async: function (p_callback) {
  219. const func = GodotRuntime.get_func(p_callback);
  220. GodotOS.finish_async(func);
  221. },
  222. godot_js_os_request_quit_cb: function (p_callback) {
  223. GodotOS.request_quit = GodotRuntime.get_func(p_callback);
  224. },
  225. godot_js_os_fs_is_persistent: function () {
  226. return GodotFS.is_persistent();
  227. },
  228. godot_js_os_fs_sync: function (callback) {
  229. const func = GodotRuntime.get_func(callback);
  230. GodotOS._fs_sync_promise = GodotFS.sync();
  231. GodotOS._fs_sync_promise.then(function (err) {
  232. func();
  233. });
  234. },
  235. godot_js_os_execute: function (p_json) {
  236. const json_args = GodotRuntime.parseString(p_json);
  237. const args = JSON.parse(json_args);
  238. if (GodotConfig.on_execute) {
  239. GodotConfig.on_execute(args);
  240. return 0;
  241. }
  242. return 1;
  243. },
  244. godot_js_os_shell_open: function (p_uri) {
  245. window.open(GodotRuntime.parseString(p_uri), '_blank');
  246. },
  247. };
  248. autoAddDeps(GodotOS, '$GodotOS');
  249. mergeInto(LibraryManager.library, GodotOS);