library_godot_os.js 8.9 KB

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