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