export.cpp 36 KB

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