library_godot_os.js 9.0 KB

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