export.cpp 36 KB

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