export.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. /*************************************************************************/
  2. /* export.cpp */
  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. #include "core/io/image_loader.h"
  31. #include "core/io/stream_peer_ssl.h"
  32. #include "core/io/tcp_server.h"
  33. #include "core/io/zip_io.h"
  34. #include "editor/editor_export.h"
  35. #include "editor/editor_node.h"
  36. #include "main/splash.gen.h"
  37. #include "platform/javascript/logo.gen.h"
  38. #include "platform/javascript/run_icon.gen.h"
  39. class EditorHTTPServer : public RefCounted {
  40. private:
  41. Ref<TCPServer> server;
  42. Map<String, String> mimes;
  43. Ref<StreamPeerTCP> tcp;
  44. Ref<StreamPeerSSL> ssl;
  45. Ref<StreamPeer> peer;
  46. Ref<CryptoKey> key;
  47. Ref<X509Certificate> cert;
  48. bool use_ssl = false;
  49. uint64_t time = 0;
  50. uint8_t req_buf[4096];
  51. int req_pos = 0;
  52. void _clear_client() {
  53. peer = Ref<StreamPeer>();
  54. ssl = Ref<StreamPeerSSL>();
  55. tcp = Ref<StreamPeerTCP>();
  56. memset(req_buf, 0, sizeof(req_buf));
  57. time = 0;
  58. req_pos = 0;
  59. }
  60. void _set_internal_certs(Ref<Crypto> p_crypto) {
  61. const String cache_path = EditorPaths::get_singleton()->get_cache_dir();
  62. const String key_path = cache_path.plus_file("html5_server.key");
  63. const String crt_path = cache_path.plus_file("html5_server.crt");
  64. bool regen = !FileAccess::exists(key_path) || !FileAccess::exists(crt_path);
  65. if (!regen) {
  66. key = Ref<CryptoKey>(CryptoKey::create());
  67. cert = Ref<X509Certificate>(X509Certificate::create());
  68. if (key->load(key_path) != OK || cert->load(crt_path) != OK) {
  69. regen = true;
  70. }
  71. }
  72. if (regen) {
  73. key = p_crypto->generate_rsa(2048);
  74. key->save(key_path);
  75. cert = p_crypto->generate_self_signed_certificate(key, "CN=godot-debug.local,O=A Game Dev,C=XXA", "20140101000000", "20340101000000");
  76. cert->save(crt_path);
  77. }
  78. }
  79. public:
  80. EditorHTTPServer() {
  81. mimes["html"] = "text/html";
  82. mimes["js"] = "application/javascript";
  83. mimes["json"] = "application/json";
  84. mimes["pck"] = "application/octet-stream";
  85. mimes["png"] = "image/png";
  86. mimes["svg"] = "image/svg";
  87. mimes["wasm"] = "application/wasm";
  88. server.instance();
  89. stop();
  90. }
  91. void stop() {
  92. server->stop();
  93. _clear_client();
  94. }
  95. Error listen(int p_port, IPAddress p_address, bool p_use_ssl, String p_ssl_key, String p_ssl_cert) {
  96. use_ssl = p_use_ssl;
  97. if (use_ssl) {
  98. Ref<Crypto> crypto = Crypto::create();
  99. if (crypto.is_null()) {
  100. return ERR_UNAVAILABLE;
  101. }
  102. if (!p_ssl_key.is_empty() && !p_ssl_cert.is_empty()) {
  103. key = Ref<CryptoKey>(CryptoKey::create());
  104. Error err = key->load(p_ssl_key);
  105. ERR_FAIL_COND_V(err != OK, err);
  106. cert = Ref<X509Certificate>(X509Certificate::create());
  107. err = cert->load(p_ssl_cert);
  108. ERR_FAIL_COND_V(err != OK, err);
  109. } else {
  110. _set_internal_certs(crypto);
  111. }
  112. }
  113. return server->listen(p_port, p_address);
  114. }
  115. bool is_listening() const {
  116. return server->is_listening();
  117. }
  118. void _send_response() {
  119. Vector<String> psa = String((char *)req_buf).split("\r\n");
  120. int len = psa.size();
  121. ERR_FAIL_COND_MSG(len < 4, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  122. Vector<String> req = psa[0].split(" ", false);
  123. ERR_FAIL_COND_MSG(req.size() < 2, "Invalid protocol or status code.");
  124. // Wrong protocol
  125. ERR_FAIL_COND_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", "Invalid method or HTTP version.");
  126. const String req_file = req[1].get_file();
  127. const String req_ext = req[1].get_extension();
  128. const String cache_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  129. const String filepath = cache_path.plus_file(req_file);
  130. if (!mimes.has(req_ext) || !FileAccess::exists(filepath)) {
  131. String s = "HTTP/1.1 404 Not Found\r\n";
  132. s += "Connection: Close\r\n";
  133. s += "\r\n";
  134. CharString cs = s.utf8();
  135. peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  136. return;
  137. }
  138. const String ctype = mimes[req_ext];
  139. FileAccess *f = FileAccess::open(filepath, FileAccess::READ);
  140. ERR_FAIL_COND(!f);
  141. String s = "HTTP/1.1 200 OK\r\n";
  142. s += "Connection: Close\r\n";
  143. s += "Content-Type: " + ctype + "\r\n";
  144. s += "Access-Control-Allow-Origin: *\r\n";
  145. s += "Cross-Origin-Opener-Policy: same-origin\r\n";
  146. s += "Cross-Origin-Embedder-Policy: require-corp\r\n";
  147. s += "Cache-Control: no-store, max-age=0\r\n";
  148. s += "\r\n";
  149. CharString cs = s.utf8();
  150. Error err = peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  151. if (err != OK) {
  152. memdelete(f);
  153. ERR_FAIL();
  154. }
  155. while (true) {
  156. uint8_t bytes[4096];
  157. uint64_t read = f->get_buffer(bytes, 4096);
  158. if (read == 0) {
  159. break;
  160. }
  161. err = peer->put_data(bytes, read);
  162. if (err != OK) {
  163. memdelete(f);
  164. ERR_FAIL();
  165. }
  166. }
  167. memdelete(f);
  168. }
  169. void poll() {
  170. if (!server->is_listening()) {
  171. return;
  172. }
  173. if (tcp.is_null()) {
  174. if (!server->is_connection_available()) {
  175. return;
  176. }
  177. tcp = server->take_connection();
  178. peer = tcp;
  179. time = OS::get_singleton()->get_ticks_usec();
  180. }
  181. if (OS::get_singleton()->get_ticks_usec() - time > 1000000) {
  182. _clear_client();
  183. return;
  184. }
  185. if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  186. return;
  187. }
  188. if (use_ssl) {
  189. if (ssl.is_null()) {
  190. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  191. peer = ssl;
  192. ssl->set_blocking_handshake_enabled(false);
  193. if (ssl->accept_stream(tcp, key, cert) != OK) {
  194. _clear_client();
  195. return;
  196. }
  197. }
  198. ssl->poll();
  199. if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
  200. // Still handshaking, keep waiting.
  201. return;
  202. }
  203. if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  204. _clear_client();
  205. return;
  206. }
  207. }
  208. while (true) {
  209. char *r = (char *)req_buf;
  210. int l = req_pos - 1;
  211. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  212. _send_response();
  213. _clear_client();
  214. return;
  215. }
  216. int read = 0;
  217. ERR_FAIL_COND(req_pos >= 4096);
  218. Error err = peer->get_partial_data(&req_buf[req_pos], 1, read);
  219. if (err != OK) {
  220. // Got an error
  221. _clear_client();
  222. return;
  223. } else if (read != 1) {
  224. // Busy, wait next poll
  225. return;
  226. }
  227. req_pos += read;
  228. }
  229. }
  230. };
  231. class EditorExportPlatformJavaScript : public EditorExportPlatform {
  232. GDCLASS(EditorExportPlatformJavaScript, EditorExportPlatform);
  233. Ref<ImageTexture> logo;
  234. Ref<ImageTexture> run_icon;
  235. Ref<ImageTexture> stop_icon;
  236. int menu_options = 0;
  237. Ref<EditorHTTPServer> server;
  238. bool server_quit = false;
  239. Mutex server_lock;
  240. Thread server_thread;
  241. enum ExportMode {
  242. EXPORT_MODE_NORMAL = 0,
  243. EXPORT_MODE_THREADS = 1,
  244. EXPORT_MODE_GDNATIVE = 2,
  245. };
  246. String _get_template_name(ExportMode p_mode, bool p_debug) const {
  247. String name = "webassembly";
  248. switch (p_mode) {
  249. case EXPORT_MODE_THREADS:
  250. name += "_threads";
  251. break;
  252. case EXPORT_MODE_GDNATIVE:
  253. name += "_gdnative";
  254. break;
  255. default:
  256. break;
  257. }
  258. if (p_debug) {
  259. name += "_debug.zip";
  260. } else {
  261. name += "_release.zip";
  262. }
  263. return name;
  264. }
  265. Ref<Image> _get_project_icon() const {
  266. Ref<Image> icon;
  267. icon.instance();
  268. const String icon_path = String(GLOBAL_GET("application/config/icon")).strip_edges();
  269. if (icon_path.is_empty() || ImageLoader::load_image(icon_path, icon) != OK) {
  270. return EditorNode::get_singleton()->get_editor_theme()->get_icon("DefaultProjectIcon", "EditorIcons")->get_image();
  271. }
  272. return icon;
  273. }
  274. Ref<Image> _get_project_splash() const {
  275. Ref<Image> splash;
  276. splash.instance();
  277. const String splash_path = String(GLOBAL_GET("application/boot_splash/image")).strip_edges();
  278. if (splash_path.is_empty() || ImageLoader::load_image(splash_path, splash) != OK) {
  279. return Ref<Image>(memnew(Image(boot_splash_png)));
  280. }
  281. return splash;
  282. }
  283. Error _extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa);
  284. void _replace_strings(Map<String, String> p_replaces, Vector<uint8_t> &r_template);
  285. void _fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, int p_flags, const Vector<SharedObject> p_shared_objects, const Dictionary &p_file_sizes);
  286. Error _add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr);
  287. Error _build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects);
  288. Error _write_or_error(const uint8_t *p_content, int p_len, String p_path);
  289. static void _server_thread_poll(void *data);
  290. public:
  291. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) override;
  292. virtual void get_export_options(List<ExportOption> *r_options) override;
  293. virtual String get_name() const override;
  294. virtual String get_os_name() const override;
  295. virtual Ref<Texture2D> get_logo() const override;
  296. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const override;
  297. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override;
  298. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override;
  299. virtual bool poll_export() override;
  300. virtual int get_options_count() const override;
  301. virtual String get_option_label(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run in Browser"); }
  302. virtual String get_option_tooltip(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run exported HTML in the system's default browser."); }
  303. virtual Ref<ImageTexture> get_option_icon(int p_index) const override;
  304. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) override;
  305. virtual Ref<Texture2D> get_run_icon() const override;
  306. virtual void get_platform_features(List<String> *r_features) override {
  307. r_features->push_back("web");
  308. r_features->push_back(get_os_name());
  309. }
  310. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) override {
  311. }
  312. String get_debug_protocol() const override { return "ws://"; }
  313. EditorExportPlatformJavaScript();
  314. ~EditorExportPlatformJavaScript();
  315. };
  316. Error EditorExportPlatformJavaScript::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) {
  317. FileAccess *src_f = nullptr;
  318. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  319. unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io);
  320. if (!pkg) {
  321. EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + p_template);
  322. return ERR_FILE_NOT_FOUND;
  323. }
  324. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  325. EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + p_template);
  326. unzClose(pkg);
  327. return ERR_FILE_CORRUPT;
  328. }
  329. do {
  330. //get filename
  331. unz_file_info info;
  332. char fname[16384];
  333. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  334. String file = fname;
  335. // Skip service worker and offline page if not exporting pwa.
  336. if (!pwa && (file == "godot.service.worker.js" || file == "godot.offline.html")) {
  337. continue;
  338. }
  339. Vector<uint8_t> data;
  340. data.resize(info.uncompressed_size);
  341. //read
  342. unzOpenCurrentFile(pkg);
  343. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  344. unzCloseCurrentFile(pkg);
  345. //write
  346. String dst = p_dir.plus_file(file.replace("godot", p_name));
  347. FileAccess *f = FileAccess::open(dst, FileAccess::WRITE);
  348. if (!f) {
  349. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst);
  350. unzClose(pkg);
  351. return ERR_FILE_CANT_WRITE;
  352. }
  353. f->store_buffer(data.ptr(), data.size());
  354. memdelete(f);
  355. } while (unzGoToNextFile(pkg) == UNZ_OK);
  356. unzClose(pkg);
  357. return OK;
  358. }
  359. Error EditorExportPlatformJavaScript::_write_or_error(const uint8_t *p_content, int p_size, String p_path) {
  360. FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
  361. if (!f) {
  362. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path);
  363. return ERR_FILE_CANT_WRITE;
  364. }
  365. f->store_buffer(p_content, p_size);
  366. memdelete(f);
  367. return OK;
  368. }
  369. void EditorExportPlatformJavaScript::_replace_strings(Map<String, String> p_replaces, Vector<uint8_t> &r_template) {
  370. String str_template = String::utf8(reinterpret_cast<const char *>(r_template.ptr()), r_template.size());
  371. String out;
  372. Vector<String> lines = str_template.split("\n");
  373. for (int i = 0; i < lines.size(); i++) {
  374. String current_line = lines[i];
  375. for (Map<String, String>::Element *E = p_replaces.front(); E; E = E->next()) {
  376. current_line = current_line.replace(E->key(), E->get());
  377. }
  378. out += current_line + "\n";
  379. }
  380. CharString cs = out.utf8();
  381. r_template.resize(cs.length());
  382. for (int i = 0; i < cs.length(); i++) {
  383. r_template.write[i] = cs[i];
  384. }
  385. }
  386. void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, int p_flags, const Vector<SharedObject> p_shared_objects, const Dictionary &p_file_sizes) {
  387. // Engine.js config
  388. Dictionary config;
  389. Array libs;
  390. for (int i = 0; i < p_shared_objects.size(); i++) {
  391. libs.push_back(p_shared_objects[i].path.get_file());
  392. }
  393. Vector<String> flags;
  394. gen_export_flags(flags, p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  395. Array args;
  396. for (int i = 0; i < flags.size(); i++) {
  397. args.push_back(flags[i]);
  398. }
  399. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  400. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  401. config["gdnativeLibs"] = libs;
  402. config["executable"] = p_name;
  403. config["args"] = args;
  404. config["fileSizes"] = p_file_sizes;
  405. String head_include;
  406. if (p_preset->get("html/export_icon")) {
  407. head_include += "<link id='-gd-engine-icon' rel='icon' type='image/png' href='" + p_name + ".icon.png' />\n";
  408. head_include += "<link rel='apple-touch-icon' href='" + p_name + ".apple-touch-icon.png'/>\n";
  409. }
  410. if (p_preset->get("progressive_web_app/enabled")) {
  411. head_include += "<link rel='manifest' href='" + p_name + ".manifest.json'>\n";
  412. head_include += "<script type='application/javascript'>window.addEventListener('load', () => {if ('serviceWorker' in navigator) {navigator.serviceWorker.register('" +
  413. p_name + ".service.worker.js');}});</script>\n";
  414. }
  415. // Replaces HTML string
  416. const String str_config = Variant(config).to_json_string();
  417. const String custom_head_include = p_preset->get("html/head_include");
  418. Map<String, String> replaces;
  419. replaces["$GODOT_URL"] = p_name + ".js";
  420. replaces["$GODOT_PROJECT_NAME"] = ProjectSettings::get_singleton()->get_setting("application/config/name");
  421. replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include;
  422. replaces["$GODOT_CONFIG"] = str_config;
  423. _replace_strings(replaces, p_html);
  424. }
  425. Error EditorExportPlatformJavaScript::_add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr) {
  426. const String name = p_path.get_file().get_basename();
  427. const String icon_name = vformat("%s.%dx%d.png", name, p_size, p_size);
  428. const String icon_dest = p_path.get_base_dir().plus_file(icon_name);
  429. Ref<Image> icon;
  430. if (!p_icon.is_empty()) {
  431. icon.instance();
  432. const Error err = ImageLoader::load_image(p_icon, icon);
  433. if (err != OK) {
  434. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + p_icon);
  435. return err;
  436. }
  437. if (icon->get_width() != p_size || icon->get_height() != p_size) {
  438. icon->resize(p_size, p_size);
  439. }
  440. } else {
  441. icon = _get_project_icon();
  442. icon->resize(p_size, p_size);
  443. }
  444. const Error err = icon->save_png(icon_dest);
  445. if (err != OK) {
  446. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + icon_dest);
  447. return err;
  448. }
  449. Dictionary icon_dict;
  450. icon_dict["sizes"] = vformat("%dx%d", p_size, p_size);
  451. icon_dict["type"] = "image/png";
  452. icon_dict["src"] = icon_name;
  453. r_arr.push_back(icon_dict);
  454. return err;
  455. }
  456. Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
  457. // Service worker
  458. const String dir = p_path.get_base_dir();
  459. const String name = p_path.get_file().get_basename();
  460. const ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  461. Map<String, String> replaces;
  462. replaces["@GODOT_VERSION@"] = "1";
  463. replaces["@GODOT_NAME@"] = name;
  464. replaces["@GODOT_OFFLINE_PAGE@"] = name + ".offline.html";
  465. Array files;
  466. replaces["@GODOT_OPT_CACHE@"] = Variant(files).to_json_string();
  467. files.push_back(name + ".html");
  468. files.push_back(name + ".js");
  469. files.push_back(name + ".wasm");
  470. files.push_back(name + ".pck");
  471. files.push_back(name + ".offline.html");
  472. if (p_preset->get("html/export_icon")) {
  473. files.push_back(name + ".icon.png");
  474. files.push_back(name + ".apple-touch-icon.png");
  475. }
  476. if (mode == EXPORT_MODE_THREADS) {
  477. files.push_back(name + ".worker.js");
  478. files.push_back(name + ".audio.worklet.js");
  479. } else if (mode == EXPORT_MODE_GDNATIVE) {
  480. files.push_back(name + ".side.wasm");
  481. for (int i = 0; i < p_shared_objects.size(); i++) {
  482. files.push_back(p_shared_objects[i].path.get_file());
  483. }
  484. }
  485. replaces["@GODOT_CACHE@"] = Variant(files).to_json_string();
  486. const String sw_path = dir.plus_file(name + ".service.worker.js");
  487. Vector<uint8_t> sw;
  488. {
  489. FileAccess *f = FileAccess::open(sw_path, FileAccess::READ);
  490. if (!f) {
  491. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + sw_path);
  492. return ERR_FILE_CANT_READ;
  493. }
  494. sw.resize(f->get_length());
  495. f->get_buffer(sw.ptrw(), sw.size());
  496. memdelete(f);
  497. f = nullptr;
  498. }
  499. _replace_strings(replaces, sw);
  500. Error err = _write_or_error(sw.ptr(), sw.size(), dir.plus_file(name + ".service.worker.js"));
  501. if (err != OK) {
  502. return err;
  503. }
  504. // Custom offline page
  505. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  506. if (!offline_page.is_empty()) {
  507. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  508. const String offline_dest = dir.plus_file(name + ".offline.html");
  509. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  510. if (err != OK) {
  511. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + offline_dest);
  512. return err;
  513. }
  514. }
  515. // Manifest
  516. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  517. const char *orientations[3] = { "any", "landscape", "portrait" };
  518. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  519. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  520. Dictionary manifest;
  521. String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
  522. if (proj_name.is_empty()) {
  523. proj_name = "Godot Game";
  524. }
  525. manifest["name"] = proj_name;
  526. manifest["start_url"] = "./" + name + ".html";
  527. manifest["display"] = String::utf8(modes[display]);
  528. manifest["orientation"] = String::utf8(orientations[orientation]);
  529. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  530. Array icons_arr;
  531. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  532. err = _add_manifest_icon(p_path, icon144_path, 144, icons_arr);
  533. if (err != OK) {
  534. return err;
  535. }
  536. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  537. err = _add_manifest_icon(p_path, icon180_path, 180, icons_arr);
  538. if (err != OK) {
  539. return err;
  540. }
  541. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  542. err = _add_manifest_icon(p_path, icon512_path, 512, icons_arr);
  543. if (err != OK) {
  544. return err;
  545. }
  546. manifest["icons"] = icons_arr;
  547. CharString cs = Variant(manifest).to_json_string().utf8();
  548. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.plus_file(name + ".manifest.json"));
  549. if (err != OK) {
  550. return err;
  551. }
  552. return OK;
  553. }
  554. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  555. if (p_preset->get("vram_texture_compression/for_desktop")) {
  556. r_features->push_back("s3tc");
  557. }
  558. if (p_preset->get("vram_texture_compression/for_mobile")) {
  559. String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name");
  560. if (driver == "GLES2") {
  561. r_features->push_back("etc");
  562. } else if (driver == "Vulkan") {
  563. // FIXME: Review if this is correct.
  564. r_features->push_back("etc2");
  565. }
  566. }
  567. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  568. if (mode == EXPORT_MODE_THREADS) {
  569. r_features->push_back("threads");
  570. } else if (mode == EXPORT_MODE_GDNATIVE) {
  571. r_features->push_back("wasm32");
  572. }
  573. }
  574. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  575. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  576. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  577. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type.
  578. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  579. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  580. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  581. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  582. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  583. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  584. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  585. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  586. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  587. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal UI,Browser"), 1));
  588. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  589. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  590. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  591. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  592. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  593. }
  594. String EditorExportPlatformJavaScript::get_name() const {
  595. return "HTML5";
  596. }
  597. String EditorExportPlatformJavaScript::get_os_name() const {
  598. return "HTML5";
  599. }
  600. Ref<Texture2D> EditorExportPlatformJavaScript::get_logo() const {
  601. return logo;
  602. }
  603. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  604. String err;
  605. bool valid = false;
  606. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  607. // Look for export templates (first official, and if defined custom templates).
  608. bool dvalid = exists_export_template(_get_template_name(mode, true), &err);
  609. bool rvalid = exists_export_template(_get_template_name(mode, false), &err);
  610. if (p_preset->get("custom_template/debug") != "") {
  611. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  612. if (!dvalid) {
  613. err += TTR("Custom debug template not found.") + "\n";
  614. }
  615. }
  616. if (p_preset->get("custom_template/release") != "") {
  617. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  618. if (!rvalid) {
  619. err += TTR("Custom release template not found.") + "\n";
  620. }
  621. }
  622. valid = dvalid || rvalid;
  623. r_missing_templates = !valid;
  624. // Validate the rest of the configuration.
  625. if (p_preset->get("vram_texture_compression/for_mobile")) {
  626. String etc_error = test_etc2();
  627. if (etc_error != String()) {
  628. valid = false;
  629. err += etc_error;
  630. }
  631. }
  632. if (!err.is_empty()) {
  633. r_error = err;
  634. }
  635. return valid;
  636. }
  637. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  638. List<String> list;
  639. list.push_back("html");
  640. return list;
  641. }
  642. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  643. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  644. const String custom_debug = p_preset->get("custom_template/debug");
  645. const String custom_release = p_preset->get("custom_template/release");
  646. const String custom_html = p_preset->get("html/custom_html_shell");
  647. const bool export_icon = p_preset->get("html/export_icon");
  648. const bool pwa = p_preset->get("progressive_web_app/enabled");
  649. const String base_dir = p_path.get_base_dir();
  650. const String base_path = p_path.get_basename();
  651. const String base_name = p_path.get_file().get_basename();
  652. // Find the correct template
  653. String template_path = p_debug ? custom_debug : custom_release;
  654. template_path = template_path.strip_edges();
  655. if (template_path == String()) {
  656. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  657. template_path = find_export_template(_get_template_name(mode, p_debug));
  658. }
  659. if (!DirAccess::exists(base_dir)) {
  660. return ERR_FILE_BAD_PATH;
  661. }
  662. if (template_path != String() && !FileAccess::exists(template_path)) {
  663. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  664. return ERR_FILE_NOT_FOUND;
  665. }
  666. // Export pck and shared objects
  667. Vector<SharedObject> shared_objects;
  668. String pck_path = base_path + ".pck";
  669. Error error = save_pack(p_preset, pck_path, &shared_objects);
  670. if (error != OK) {
  671. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  672. return error;
  673. }
  674. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  675. for (int i = 0; i < shared_objects.size(); i++) {
  676. String dst = base_dir.plus_file(shared_objects[i].path.get_file());
  677. error = da->copy(shared_objects[i].path, dst);
  678. if (error != OK) {
  679. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  680. memdelete(da);
  681. return error;
  682. }
  683. }
  684. memdelete(da);
  685. da = nullptr;
  686. // Extract templates.
  687. error = _extract_template(template_path, base_dir, base_name, pwa);
  688. if (error) {
  689. return error;
  690. }
  691. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  692. Dictionary file_sizes;
  693. FileAccess *f = nullptr;
  694. f = FileAccess::open(pck_path, FileAccess::READ);
  695. if (f) {
  696. file_sizes[pck_path.get_file()] = (uint64_t)f->get_length();
  697. memdelete(f);
  698. f = nullptr;
  699. }
  700. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  701. if (f) {
  702. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length();
  703. memdelete(f);
  704. f = nullptr;
  705. }
  706. // Read the HTML shell file (custom or from template).
  707. const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html;
  708. Vector<uint8_t> html;
  709. f = FileAccess::open(html_path, FileAccess::READ);
  710. if (!f) {
  711. EditorNode::get_singleton()->show_warning(TTR("Could not read HTML shell:") + "\n" + html_path);
  712. return ERR_FILE_CANT_READ;
  713. }
  714. html.resize(f->get_length());
  715. f->get_buffer(html.ptrw(), html.size());
  716. memdelete(f);
  717. f = nullptr;
  718. // Generate HTML file with replaced strings.
  719. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  720. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  721. if (err != OK) {
  722. return err;
  723. }
  724. html.resize(0);
  725. // Export splash (why?)
  726. Ref<Image> splash = _get_project_splash();
  727. const String splash_png_path = base_path + ".png";
  728. if (splash->save_png(splash_png_path) != OK) {
  729. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  730. return ERR_FILE_CANT_WRITE;
  731. }
  732. // Save a favicon that can be accessed without waiting for the project to finish loading.
  733. // This way, the favicon can be displayed immediately when loading the page.
  734. if (export_icon) {
  735. Ref<Image> favicon = _get_project_icon();
  736. const String favicon_png_path = base_path + ".icon.png";
  737. if (favicon->save_png(favicon_png_path) != OK) {
  738. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  739. return ERR_FILE_CANT_WRITE;
  740. }
  741. favicon->resize(180, 180);
  742. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  743. if (favicon->save_png(apple_icon_png_path) != OK) {
  744. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + apple_icon_png_path);
  745. return ERR_FILE_CANT_WRITE;
  746. }
  747. }
  748. // Generate the PWA worker and manifest
  749. if (pwa) {
  750. err = _build_pwa(p_preset, p_path, shared_objects);
  751. if (err != OK) {
  752. return err;
  753. }
  754. }
  755. return OK;
  756. }
  757. bool EditorExportPlatformJavaScript::poll_export() {
  758. Ref<EditorExportPreset> preset;
  759. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  760. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  761. if (ep->is_runnable() && ep->get_platform() == this) {
  762. preset = ep;
  763. break;
  764. }
  765. }
  766. int prev = menu_options;
  767. menu_options = preset.is_valid();
  768. if (server->is_listening()) {
  769. if (menu_options == 0) {
  770. MutexLock lock(server_lock);
  771. server->stop();
  772. } else {
  773. menu_options += 1;
  774. }
  775. }
  776. return menu_options != prev;
  777. }
  778. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  779. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  780. }
  781. int EditorExportPlatformJavaScript::get_options_count() const {
  782. return menu_options;
  783. }
  784. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  785. if (p_option == 1) {
  786. MutexLock lock(server_lock);
  787. server->stop();
  788. return OK;
  789. }
  790. const String dest = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  791. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  792. if (!da->dir_exists(dest)) {
  793. Error err = da->make_dir_recursive(dest);
  794. if (err != OK) {
  795. EditorNode::get_singleton()->show_warning(TTR("Could not create HTTP server directory:") + "\n" + dest);
  796. return err;
  797. }
  798. }
  799. const String basepath = dest.plus_file("tmp_js_export");
  800. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  801. if (err != OK) {
  802. // Export generates several files, clean them up on failure.
  803. DirAccess::remove_file_or_error(basepath + ".html");
  804. DirAccess::remove_file_or_error(basepath + ".offline.html");
  805. DirAccess::remove_file_or_error(basepath + ".js");
  806. DirAccess::remove_file_or_error(basepath + ".worker.js");
  807. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  808. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  809. DirAccess::remove_file_or_error(basepath + ".pck");
  810. DirAccess::remove_file_or_error(basepath + ".png");
  811. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  812. DirAccess::remove_file_or_error(basepath + ".wasm");
  813. DirAccess::remove_file_or_error(basepath + ".icon.png");
  814. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  815. return err;
  816. }
  817. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  818. // Resolve host if needed.
  819. const String bind_host = EDITOR_GET("export/web/http_host");
  820. IPAddress bind_ip;
  821. if (bind_host.is_valid_ip_address()) {
  822. bind_ip = bind_host;
  823. } else {
  824. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  825. }
  826. ERR_FAIL_COND_V_MSG(!bind_ip.is_valid(), ERR_INVALID_PARAMETER, "Invalid editor setting 'export/web/http_host': '" + bind_host + "'. Try using '127.0.0.1'.");
  827. const bool use_ssl = EDITOR_GET("export/web/use_ssl");
  828. const String ssl_key = EDITOR_GET("export/web/ssl_key");
  829. const String ssl_cert = EDITOR_GET("export/web/ssl_certificate");
  830. // Restart server.
  831. {
  832. MutexLock lock(server_lock);
  833. server->stop();
  834. err = server->listen(bind_port, bind_ip, use_ssl, ssl_key, ssl_cert);
  835. }
  836. if (err != OK) {
  837. EditorNode::get_singleton()->show_warning(TTR("Error starting HTTP server:") + "\n" + itos(err));
  838. return err;
  839. }
  840. OS::get_singleton()->shell_open(String((use_ssl ? "https://" : "http://") + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  841. // FIXME: Find out how to clean up export files after running the successfully
  842. // exported game. Might not be trivial.
  843. return OK;
  844. }
  845. Ref<Texture2D> EditorExportPlatformJavaScript::get_run_icon() const {
  846. return run_icon;
  847. }
  848. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  849. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  850. while (!ej->server_quit) {
  851. OS::get_singleton()->delay_usec(1000);
  852. {
  853. MutexLock lock(ej->server_lock);
  854. ej->server->poll();
  855. }
  856. }
  857. }
  858. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  859. server.instance();
  860. server_thread.start(_server_thread_poll, this);
  861. Ref<Image> img = memnew(Image(_javascript_logo));
  862. logo.instance();
  863. logo->create_from_image(img);
  864. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  865. run_icon.instance();
  866. run_icon->create_from_image(img);
  867. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  868. if (theme.is_valid()) {
  869. stop_icon = theme->get_icon("Stop", "EditorIcons");
  870. } else {
  871. stop_icon.instance();
  872. }
  873. }
  874. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  875. server->stop();
  876. server_quit = true;
  877. server_thread.wait_to_finish();
  878. }
  879. void register_javascript_exporter() {
  880. EDITOR_DEF("export/web/http_host", "localhost");
  881. EDITOR_DEF("export/web/http_port", 8060);
  882. EDITOR_DEF("export/web/use_ssl", false);
  883. EDITOR_DEF("export/web/ssl_key", "");
  884. EDITOR_DEF("export/web/ssl_certificate", "");
  885. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1"));
  886. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_key", PROPERTY_HINT_GLOBAL_FILE, "*.key"));
  887. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_certificate", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"));
  888. Ref<EditorExportPlatformJavaScript> platform;
  889. platform.instance();
  890. EditorExport::get_singleton()->add_export_platform(platform);
  891. }