library_godot_os.js 9.2 KB

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