export.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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.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. 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);
  267. static void _server_thread_poll(void *data);
  268. public:
  269. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) override;
  270. virtual void get_export_options(List<ExportOption> *r_options) override;
  271. virtual String get_name() const override;
  272. virtual String get_os_name() const override;
  273. virtual Ref<Texture2D> get_logo() const override;
  274. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const override;
  275. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override;
  276. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override;
  277. virtual bool poll_export() override;
  278. virtual int get_options_count() const override;
  279. virtual String get_option_label(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run in Browser"); }
  280. 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."); }
  281. virtual Ref<ImageTexture> get_option_icon(int p_index) const override;
  282. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) override;
  283. virtual Ref<Texture2D> get_run_icon() const override;
  284. virtual void get_platform_features(List<String> *r_features) override {
  285. r_features->push_back("web");
  286. r_features->push_back(get_os_name());
  287. }
  288. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) override {
  289. }
  290. String get_debug_protocol() const override { return "ws://"; }
  291. EditorExportPlatformJavaScript();
  292. ~EditorExportPlatformJavaScript();
  293. };
  294. 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) {
  295. String str_template = String::utf8(reinterpret_cast<const char *>(p_html.ptr()), p_html.size());
  296. String str_export;
  297. Vector<String> lines = str_template.split("\n");
  298. Array libs;
  299. for (int i = 0; i < p_shared_objects.size(); i++) {
  300. libs.push_back(p_shared_objects[i].path.get_file());
  301. }
  302. Vector<String> flags;
  303. gen_export_flags(flags, p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  304. Array args;
  305. for (int i = 0; i < flags.size(); i++) {
  306. args.push_back(flags[i]);
  307. }
  308. Dictionary config;
  309. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  310. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  311. config["gdnativeLibs"] = libs;
  312. config["executable"] = p_name;
  313. config["args"] = args;
  314. config["fileSizes"] = p_file_sizes;
  315. const String str_config = JSON::print(config);
  316. String head_include;
  317. if (p_preset->get("html/export_icon")) {
  318. head_include += "<link id='-gd-engine-icon' rel='icon' type='image/png' href='" + p_name + ".icon.png' />\n";
  319. }
  320. head_include += static_cast<String>(p_preset->get("html/head_include"));
  321. for (int i = 0; i < lines.size(); i++) {
  322. String current_line = lines[i];
  323. current_line = current_line.replace("$GODOT_URL", p_name + ".js");
  324. current_line = current_line.replace("$GODOT_PROJECT_NAME", ProjectSettings::get_singleton()->get_setting("application/config/name"));
  325. current_line = current_line.replace("$GODOT_HEAD_INCLUDE", head_include);
  326. current_line = current_line.replace("$GODOT_CONFIG", str_config);
  327. str_export += current_line + "\n";
  328. }
  329. CharString cs = str_export.utf8();
  330. p_html.resize(cs.length());
  331. for (int i = 0; i < cs.length(); i++) {
  332. p_html.write[i] = cs[i];
  333. }
  334. }
  335. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  336. if (p_preset->get("vram_texture_compression/for_desktop")) {
  337. r_features->push_back("s3tc");
  338. }
  339. if (p_preset->get("vram_texture_compression/for_mobile")) {
  340. String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name");
  341. if (driver == "GLES2") {
  342. r_features->push_back("etc");
  343. } else if (driver == "Vulkan") {
  344. // FIXME: Review if this is correct.
  345. r_features->push_back("etc2");
  346. }
  347. }
  348. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  349. if (mode == EXPORT_MODE_THREADS) {
  350. r_features->push_back("threads");
  351. } else if (mode == EXPORT_MODE_GDNATIVE) {
  352. r_features->push_back("wasm32");
  353. }
  354. }
  355. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  356. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  357. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  358. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type.
  359. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  360. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  361. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  362. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  363. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  364. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  365. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  366. }
  367. String EditorExportPlatformJavaScript::get_name() const {
  368. return "HTML5";
  369. }
  370. String EditorExportPlatformJavaScript::get_os_name() const {
  371. return "HTML5";
  372. }
  373. Ref<Texture2D> EditorExportPlatformJavaScript::get_logo() const {
  374. return logo;
  375. }
  376. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  377. String err;
  378. bool valid = false;
  379. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  380. // Look for export templates (first official, and if defined custom templates).
  381. bool dvalid = exists_export_template(_get_template_name(mode, true), &err);
  382. bool rvalid = exists_export_template(_get_template_name(mode, false), &err);
  383. if (p_preset->get("custom_template/debug") != "") {
  384. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  385. if (!dvalid) {
  386. err += TTR("Custom debug template not found.") + "\n";
  387. }
  388. }
  389. if (p_preset->get("custom_template/release") != "") {
  390. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  391. if (!rvalid) {
  392. err += TTR("Custom release template not found.") + "\n";
  393. }
  394. }
  395. valid = dvalid || rvalid;
  396. r_missing_templates = !valid;
  397. // Validate the rest of the configuration.
  398. if (p_preset->get("vram_texture_compression/for_mobile")) {
  399. String etc_error = test_etc2();
  400. if (etc_error != String()) {
  401. valid = false;
  402. err += etc_error;
  403. }
  404. }
  405. if (!err.is_empty()) {
  406. r_error = err;
  407. }
  408. return valid;
  409. }
  410. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  411. List<String> list;
  412. list.push_back("html");
  413. return list;
  414. }
  415. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  416. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  417. String custom_debug = p_preset->get("custom_template/debug");
  418. String custom_release = p_preset->get("custom_template/release");
  419. String custom_html = p_preset->get("html/custom_html_shell");
  420. bool export_icon = p_preset->get("html/export_icon");
  421. String template_path = p_debug ? custom_debug : custom_release;
  422. template_path = template_path.strip_edges();
  423. if (template_path == String()) {
  424. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  425. template_path = find_export_template(_get_template_name(mode, p_debug));
  426. }
  427. if (!DirAccess::exists(p_path.get_base_dir())) {
  428. return ERR_FILE_BAD_PATH;
  429. }
  430. if (template_path != String() && !FileAccess::exists(template_path)) {
  431. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  432. return ERR_FILE_NOT_FOUND;
  433. }
  434. Vector<SharedObject> shared_objects;
  435. String pck_path = p_path.get_basename() + ".pck";
  436. Error error = save_pack(p_preset, pck_path, &shared_objects);
  437. if (error != OK) {
  438. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  439. return error;
  440. }
  441. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  442. for (int i = 0; i < shared_objects.size(); i++) {
  443. String dst = p_path.get_base_dir().plus_file(shared_objects[i].path.get_file());
  444. error = da->copy(shared_objects[i].path, dst);
  445. if (error != OK) {
  446. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  447. memdelete(da);
  448. return error;
  449. }
  450. }
  451. memdelete(da);
  452. FileAccess *src_f = nullptr;
  453. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  454. unzFile pkg = unzOpen2(template_path.utf8().get_data(), &io);
  455. if (!pkg) {
  456. EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + template_path);
  457. return ERR_FILE_NOT_FOUND;
  458. }
  459. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  460. EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + template_path);
  461. unzClose(pkg);
  462. return ERR_FILE_CORRUPT;
  463. }
  464. Vector<uint8_t> html;
  465. Dictionary file_sizes;
  466. do {
  467. //get filename
  468. unz_file_info info;
  469. char fname[16384];
  470. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  471. String file = fname;
  472. // HTML is handled later
  473. if (file == "godot.html") {
  474. if (custom_html.is_empty()) {
  475. html.resize(info.uncompressed_size);
  476. unzOpenCurrentFile(pkg);
  477. unzReadCurrentFile(pkg, html.ptrw(), html.size());
  478. unzCloseCurrentFile(pkg);
  479. }
  480. continue;
  481. }
  482. Vector<uint8_t> data;
  483. data.resize(info.uncompressed_size);
  484. //read
  485. unzOpenCurrentFile(pkg);
  486. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  487. unzCloseCurrentFile(pkg);
  488. //write
  489. if (file == "godot.js") {
  490. file = p_path.get_file().get_basename() + ".js";
  491. } else if (file == "godot.worker.js") {
  492. file = p_path.get_file().get_basename() + ".worker.js";
  493. } else if (file == "godot.side.wasm") {
  494. file = p_path.get_file().get_basename() + ".side.wasm";
  495. } else if (file == "godot.audio.worklet.js") {
  496. file = p_path.get_file().get_basename() + ".audio.worklet.js";
  497. } else if (file == "godot.wasm") {
  498. file = p_path.get_file().get_basename() + ".wasm";
  499. file_sizes[file.get_file()] = (uint64_t)info.uncompressed_size;
  500. }
  501. String dst = p_path.get_base_dir().plus_file(file);
  502. FileAccess *f = FileAccess::open(dst, FileAccess::WRITE);
  503. if (!f) {
  504. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst);
  505. unzClose(pkg);
  506. return ERR_FILE_CANT_WRITE;
  507. }
  508. f->store_buffer(data.ptr(), data.size());
  509. memdelete(f);
  510. } while (unzGoToNextFile(pkg) == UNZ_OK);
  511. unzClose(pkg);
  512. if (!custom_html.is_empty()) {
  513. FileAccess *f = FileAccess::open(custom_html, FileAccess::READ);
  514. if (!f) {
  515. EditorNode::get_singleton()->show_warning(TTR("Could not read custom HTML shell:") + "\n" + custom_html);
  516. return ERR_FILE_CANT_READ;
  517. }
  518. html.resize(f->get_len());
  519. f->get_buffer(html.ptrw(), html.size());
  520. memdelete(f);
  521. }
  522. {
  523. FileAccess *f = FileAccess::open(pck_path, FileAccess::READ);
  524. if (f) {
  525. file_sizes[pck_path.get_file()] = (uint64_t)f->get_len();
  526. memdelete(f);
  527. f = nullptr;
  528. }
  529. _fix_html(html, p_preset, p_path.get_file().get_basename(), p_debug, p_flags, shared_objects, file_sizes);
  530. f = FileAccess::open(p_path, FileAccess::WRITE);
  531. if (!f) {
  532. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path);
  533. return ERR_FILE_CANT_WRITE;
  534. }
  535. f->store_buffer(html.ptr(), html.size());
  536. memdelete(f);
  537. html.resize(0);
  538. }
  539. Ref<Image> splash;
  540. const String splash_path = String(GLOBAL_GET("application/boot_splash/image")).strip_edges();
  541. if (!splash_path.is_empty()) {
  542. splash.instance();
  543. const Error err = ImageLoader::load_image(splash_path, splash);
  544. if (err) {
  545. EditorNode::get_singleton()->show_warning(TTR("Could not read boot splash image file:") + "\n" + splash_path + "\n" + TTR("Using default boot splash image."));
  546. splash.unref();
  547. }
  548. }
  549. if (splash.is_null()) {
  550. splash = Ref<Image>(memnew(Image(boot_splash_png)));
  551. }
  552. const String splash_png_path = p_path.get_base_dir().plus_file(p_path.get_file().get_basename() + ".png");
  553. if (splash->save_png(splash_png_path) != OK) {
  554. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  555. return ERR_FILE_CANT_WRITE;
  556. }
  557. // Save a favicon that can be accessed without waiting for the project to finish loading.
  558. // This way, the favicon can be displayed immediately when loading the page.
  559. if (export_icon) {
  560. Ref<Image> favicon;
  561. const String favicon_path = String(GLOBAL_GET("application/config/icon")).strip_edges();
  562. if (!favicon_path.is_empty()) {
  563. favicon.instance();
  564. const Error err = ImageLoader::load_image(favicon_path, favicon);
  565. if (err) {
  566. favicon.unref();
  567. }
  568. }
  569. if (favicon.is_null()) {
  570. favicon = EditorNode::get_singleton()->get_editor_theme()->get_icon("DefaultProjectIcon", "EditorIcons")->get_image();
  571. }
  572. const String favicon_png_path = p_path.get_base_dir().plus_file(p_path.get_file().get_basename() + ".icon.png");
  573. if (favicon->save_png(favicon_png_path) != OK) {
  574. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  575. return ERR_FILE_CANT_WRITE;
  576. }
  577. }
  578. return OK;
  579. }
  580. bool EditorExportPlatformJavaScript::poll_export() {
  581. Ref<EditorExportPreset> preset;
  582. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  583. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  584. if (ep->is_runnable() && ep->get_platform() == this) {
  585. preset = ep;
  586. break;
  587. }
  588. }
  589. int prev = menu_options;
  590. menu_options = preset.is_valid();
  591. if (server->is_listening()) {
  592. if (menu_options == 0) {
  593. MutexLock lock(server_lock);
  594. server->stop();
  595. } else {
  596. menu_options += 1;
  597. }
  598. }
  599. return menu_options != prev;
  600. }
  601. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  602. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  603. }
  604. int EditorExportPlatformJavaScript::get_options_count() const {
  605. return menu_options;
  606. }
  607. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  608. if (p_option == 1) {
  609. MutexLock lock(server_lock);
  610. server->stop();
  611. return OK;
  612. }
  613. const String dest = EditorSettings::get_singleton()->get_cache_dir().plus_file("web");
  614. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  615. if (!da->dir_exists(dest)) {
  616. Error err = da->make_dir_recursive(dest);
  617. if (err != OK) {
  618. EditorNode::get_singleton()->show_warning(TTR("Could not create HTTP server directory:") + "\n" + dest);
  619. return err;
  620. }
  621. }
  622. const String basepath = dest.plus_file("tmp_js_export");
  623. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  624. if (err != OK) {
  625. // Export generates several files, clean them up on failure.
  626. DirAccess::remove_file_or_error(basepath + ".html");
  627. DirAccess::remove_file_or_error(basepath + ".js");
  628. DirAccess::remove_file_or_error(basepath + ".worker.js");
  629. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  630. DirAccess::remove_file_or_error(basepath + ".pck");
  631. DirAccess::remove_file_or_error(basepath + ".png");
  632. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  633. DirAccess::remove_file_or_error(basepath + ".wasm");
  634. DirAccess::remove_file_or_error(basepath + ".icon.png");
  635. return err;
  636. }
  637. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  638. // Resolve host if needed.
  639. const String bind_host = EDITOR_GET("export/web/http_host");
  640. IP_Address bind_ip;
  641. if (bind_host.is_valid_ip_address()) {
  642. bind_ip = bind_host;
  643. } else {
  644. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  645. }
  646. 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'.");
  647. const bool use_ssl = EDITOR_GET("export/web/use_ssl");
  648. const String ssl_key = EDITOR_GET("export/web/ssl_key");
  649. const String ssl_cert = EDITOR_GET("export/web/ssl_certificate");
  650. // Restart server.
  651. {
  652. MutexLock lock(server_lock);
  653. server->stop();
  654. err = server->listen(bind_port, bind_ip, use_ssl, ssl_key, ssl_cert);
  655. }
  656. if (err != OK) {
  657. EditorNode::get_singleton()->show_warning(TTR("Error starting HTTP server:") + "\n" + itos(err));
  658. return err;
  659. }
  660. OS::get_singleton()->shell_open(String((use_ssl ? "https://" : "http://") + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  661. // FIXME: Find out how to clean up export files after running the successfully
  662. // exported game. Might not be trivial.
  663. return OK;
  664. }
  665. Ref<Texture2D> EditorExportPlatformJavaScript::get_run_icon() const {
  666. return run_icon;
  667. }
  668. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  669. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  670. while (!ej->server_quit) {
  671. OS::get_singleton()->delay_usec(1000);
  672. {
  673. MutexLock lock(ej->server_lock);
  674. ej->server->poll();
  675. }
  676. }
  677. }
  678. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  679. server.instance();
  680. server_thread.start(_server_thread_poll, this);
  681. Ref<Image> img = memnew(Image(_javascript_logo));
  682. logo.instance();
  683. logo->create_from_image(img);
  684. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  685. run_icon.instance();
  686. run_icon->create_from_image(img);
  687. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  688. if (theme.is_valid()) {
  689. stop_icon = theme->get_icon("Stop", "EditorIcons");
  690. } else {
  691. stop_icon.instance();
  692. }
  693. }
  694. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  695. server->stop();
  696. server_quit = true;
  697. server_thread.wait_to_finish();
  698. }
  699. void register_javascript_exporter() {
  700. EDITOR_DEF("export/web/http_host", "localhost");
  701. EDITOR_DEF("export/web/http_port", 8060);
  702. EDITOR_DEF("export/web/use_ssl", false);
  703. EDITOR_DEF("export/web/ssl_key", "");
  704. EDITOR_DEF("export/web/ssl_certificate", "");
  705. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1"));
  706. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_key", PROPERTY_HINT_GLOBAL_FILE, "*.key"));
  707. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_certificate", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"));
  708. Ref<EditorExportPlatformJavaScript> platform;
  709. platform.instance();
  710. EditorExport::get_singleton()->add_export_platform(platform);
  711. }