library_godot_os.js 9.2 KB

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