export.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /*************************************************************************/
  2. /* export.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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/tcp_server.h"
  31. #include "core/io/zip_io.h"
  32. #include "editor/editor_export.h"
  33. #include "editor/editor_node.h"
  34. #include "main/splash.gen.h"
  35. #include "platform/javascript/logo.gen.h"
  36. #include "platform/javascript/run_icon.gen.h"
  37. #define EXPORT_TEMPLATE_WEBASSEMBLY_RELEASE "webassembly_release.zip"
  38. #define EXPORT_TEMPLATE_WEBASSEMBLY_DEBUG "webassembly_debug.zip"
  39. class EditorHTTPServer : public Reference {
  40. private:
  41. Ref<TCP_Server> server;
  42. Ref<StreamPeerTCP> connection;
  43. uint64_t time;
  44. uint8_t req_buf[4096];
  45. int req_pos;
  46. void _clear_client() {
  47. connection = Ref<StreamPeerTCP>();
  48. memset(req_buf, 0, sizeof(req_buf));
  49. time = 0;
  50. req_pos = 0;
  51. }
  52. public:
  53. EditorHTTPServer() {
  54. server.instance();
  55. stop();
  56. }
  57. void stop() {
  58. server->stop();
  59. _clear_client();
  60. }
  61. Error listen(int p_port, IP_Address p_address) {
  62. return server->listen(p_port, p_address);
  63. }
  64. bool is_listening() const {
  65. return server->is_listening();
  66. }
  67. void _send_response() {
  68. Vector<String> psa = String((char *)req_buf).split("\r\n");
  69. int len = psa.size();
  70. ERR_FAIL_COND_MSG(len < 4, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  71. Vector<String> req = psa[0].split(" ", false);
  72. ERR_FAIL_COND_MSG(req.size() < 2, "Invalid protocol or status code.");
  73. // Wrong protocol
  74. ERR_FAIL_COND_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", "Invalid method or HTTP version.");
  75. const String cache_path = EditorSettings::get_singleton()->get_cache_dir();
  76. const String basereq = "/tmp_js_export";
  77. String filepath;
  78. String ctype;
  79. if (req[1] == basereq + ".html") {
  80. filepath = cache_path.plus_file(req[1].get_file());
  81. ctype = "text/html";
  82. } else if (req[1] == basereq + ".js") {
  83. filepath = cache_path.plus_file(req[1].get_file());
  84. ctype = "application/javascript";
  85. } else if (req[1] == basereq + ".audio.worklet.js") {
  86. filepath = cache_path.plus_file(req[1].get_file());
  87. ctype = "application/javascript";
  88. } else if (req[1] == basereq + ".worker.js") {
  89. filepath = cache_path.plus_file(req[1].get_file());
  90. ctype = "application/javascript";
  91. } else if (req[1] == basereq + ".pck") {
  92. filepath = cache_path.plus_file(req[1].get_file());
  93. ctype = "application/octet-stream";
  94. } else if (req[1] == basereq + ".png" || req[1] == "/favicon.png") {
  95. // Also allow serving the generated favicon for a smoother loading experience.
  96. if (req[1] == "/favicon.png") {
  97. filepath = EditorSettings::get_singleton()->get_cache_dir().plus_file("favicon.png");
  98. } else {
  99. filepath = basereq + ".png";
  100. }
  101. ctype = "image/png";
  102. } else if (req[1] == basereq + ".side.wasm") {
  103. filepath = cache_path.plus_file(req[1].get_file());
  104. ctype = "application/wasm";
  105. } else if (req[1] == basereq + ".wasm") {
  106. filepath = cache_path.plus_file(req[1].get_file());
  107. ctype = "application/wasm";
  108. } else if (req[1].ends_with(".wasm")) {
  109. filepath = cache_path.plus_file(req[1].get_file()); // TODO dangerous?
  110. ctype = "application/wasm";
  111. }
  112. if (filepath.empty() || !FileAccess::exists(filepath)) {
  113. String s = "HTTP/1.1 404 Not Found\r\n";
  114. s += "Connection: Close\r\n";
  115. s += "\r\n";
  116. CharString cs = s.utf8();
  117. connection->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  118. return;
  119. }
  120. FileAccess *f = FileAccess::open(filepath, FileAccess::READ);
  121. ERR_FAIL_COND(!f);
  122. String s = "HTTP/1.1 200 OK\r\n";
  123. s += "Connection: Close\r\n";
  124. s += "Content-Type: " + ctype + "\r\n";
  125. s += "Access-Control-Allow-Origin: *\r\n";
  126. s += "Cross-Origin-Opener-Policy: same-origin\r\n";
  127. s += "Cross-Origin-Embedder-Policy: require-corp\r\n";
  128. s += "\r\n";
  129. CharString cs = s.utf8();
  130. Error err = connection->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  131. if (err != OK) {
  132. memdelete(f);
  133. ERR_FAIL();
  134. }
  135. while (true) {
  136. uint8_t bytes[4096];
  137. int read = f->get_buffer(bytes, 4096);
  138. if (read < 1) {
  139. break;
  140. }
  141. err = connection->put_data(bytes, read);
  142. if (err != OK) {
  143. memdelete(f);
  144. ERR_FAIL();
  145. }
  146. }
  147. memdelete(f);
  148. }
  149. void poll() {
  150. if (!server->is_listening())
  151. return;
  152. if (connection.is_null()) {
  153. if (!server->is_connection_available())
  154. return;
  155. connection = server->take_connection();
  156. time = OS::get_singleton()->get_ticks_usec();
  157. }
  158. if (OS::get_singleton()->get_ticks_usec() - time > 1000000) {
  159. _clear_client();
  160. return;
  161. }
  162. if (connection->get_status() != StreamPeerTCP::STATUS_CONNECTED)
  163. return;
  164. while (true) {
  165. char *r = (char *)req_buf;
  166. int l = req_pos - 1;
  167. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  168. _send_response();
  169. _clear_client();
  170. return;
  171. }
  172. int read = 0;
  173. ERR_FAIL_COND(req_pos >= 4096);
  174. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  175. if (err != OK) {
  176. // Got an error
  177. _clear_client();
  178. return;
  179. } else if (read != 1) {
  180. // Busy, wait next poll
  181. return;
  182. }
  183. req_pos += read;
  184. }
  185. }
  186. };
  187. class EditorExportPlatformJavaScript : public EditorExportPlatform {
  188. GDCLASS(EditorExportPlatformJavaScript, EditorExportPlatform);
  189. Ref<ImageTexture> logo;
  190. Ref<ImageTexture> run_icon;
  191. Ref<ImageTexture> stop_icon;
  192. int menu_options;
  193. void _fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, const Vector<SharedObject> p_shared_objects);
  194. private:
  195. Ref<EditorHTTPServer> server;
  196. bool server_quit;
  197. Mutex *server_lock;
  198. Thread *server_thread;
  199. static void _server_thread_poll(void *data);
  200. public:
  201. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features);
  202. virtual void get_export_options(List<ExportOption> *r_options);
  203. virtual String get_name() const;
  204. virtual String get_os_name() const;
  205. virtual Ref<Texture> get_logo() const;
  206. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const;
  207. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const;
  208. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0);
  209. virtual bool poll_export();
  210. virtual int get_options_count() const;
  211. virtual String get_option_label(int p_index) const { return p_index ? TTR("Stop HTTP Server") : TTR("Run in Browser"); }
  212. 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."); }
  213. virtual Ref<ImageTexture> get_option_icon(int p_index) const;
  214. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags);
  215. virtual Ref<Texture> get_run_icon() const;
  216. virtual void get_platform_features(List<String> *r_features) {
  217. r_features->push_back("web");
  218. r_features->push_back(get_os_name());
  219. }
  220. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) {
  221. }
  222. EditorExportPlatformJavaScript();
  223. ~EditorExportPlatformJavaScript();
  224. };
  225. void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, const Vector<SharedObject> p_shared_objects) {
  226. String str_template = String::utf8(reinterpret_cast<const char *>(p_html.ptr()), p_html.size());
  227. String str_export;
  228. Vector<String> lines = str_template.split("\n");
  229. String libs;
  230. for (int i = 0; i < p_shared_objects.size(); i++) {
  231. libs += "\"" + p_shared_objects[i].path.get_file() + "\",";
  232. }
  233. for (int i = 0; i < lines.size(); i++) {
  234. String current_line = lines[i];
  235. current_line = current_line.replace("$GODOT_BASENAME", p_name);
  236. current_line = current_line.replace("$GODOT_PROJECT_NAME", ProjectSettings::get_singleton()->get_setting("application/config/name"));
  237. current_line = current_line.replace("$GODOT_HEAD_INCLUDE", p_preset->get("html/head_include"));
  238. current_line = current_line.replace("$GODOT_FULL_WINDOW", p_preset->get("html/full_window_size") ? "true" : "false");
  239. current_line = current_line.replace("$GODOT_GDNATIVE_LIBS", libs);
  240. current_line = current_line.replace("$GODOT_DEBUG_ENABLED", p_debug ? "true" : "false");
  241. str_export += current_line + "\n";
  242. }
  243. CharString cs = str_export.utf8();
  244. p_html.resize(cs.length());
  245. for (int i = 0; i < cs.length(); i++) {
  246. p_html.write[i] = cs[i];
  247. }
  248. }
  249. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  250. if (p_preset->get("vram_texture_compression/for_desktop")) {
  251. r_features->push_back("s3tc");
  252. }
  253. if (p_preset->get("vram_texture_compression/for_mobile")) {
  254. String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
  255. if (driver == "GLES2") {
  256. r_features->push_back("etc");
  257. } else if (driver == "GLES3") {
  258. r_features->push_back("etc2");
  259. if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
  260. r_features->push_back("etc");
  261. }
  262. }
  263. }
  264. }
  265. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  266. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  267. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  268. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  269. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  270. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  271. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  272. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/full_window_size"), true));
  273. }
  274. String EditorExportPlatformJavaScript::get_name() const {
  275. return "HTML5";
  276. }
  277. String EditorExportPlatformJavaScript::get_os_name() const {
  278. return "HTML5";
  279. }
  280. Ref<Texture> EditorExportPlatformJavaScript::get_logo() const {
  281. return logo;
  282. }
  283. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  284. String err;
  285. bool valid = false;
  286. // Look for export templates (first official, and if defined custom templates).
  287. bool dvalid = exists_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_DEBUG, &err);
  288. bool rvalid = exists_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_RELEASE, &err);
  289. if (p_preset->get("custom_template/debug") != "") {
  290. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  291. if (!dvalid) {
  292. err += TTR("Custom debug template not found.") + "\n";
  293. }
  294. }
  295. if (p_preset->get("custom_template/release") != "") {
  296. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  297. if (!rvalid) {
  298. err += TTR("Custom release template not found.") + "\n";
  299. }
  300. }
  301. valid = dvalid || rvalid;
  302. r_missing_templates = !valid;
  303. // Validate the rest of the configuration.
  304. if (p_preset->get("vram_texture_compression/for_mobile")) {
  305. String etc_error = test_etc2();
  306. if (etc_error != String()) {
  307. valid = false;
  308. err += etc_error;
  309. }
  310. }
  311. if (!err.empty())
  312. r_error = err;
  313. return valid;
  314. }
  315. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  316. List<String> list;
  317. list.push_back("html");
  318. return list;
  319. }
  320. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  321. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  322. String custom_debug = p_preset->get("custom_template/debug");
  323. String custom_release = p_preset->get("custom_template/release");
  324. String custom_html = p_preset->get("html/custom_html_shell");
  325. String template_path = p_debug ? custom_debug : custom_release;
  326. template_path = template_path.strip_edges();
  327. if (template_path == String()) {
  328. if (p_debug)
  329. template_path = find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_DEBUG);
  330. else
  331. template_path = find_export_template(EXPORT_TEMPLATE_WEBASSEMBLY_RELEASE);
  332. }
  333. if (!DirAccess::exists(p_path.get_base_dir())) {
  334. return ERR_FILE_BAD_PATH;
  335. }
  336. if (template_path != String() && !FileAccess::exists(template_path)) {
  337. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  338. return ERR_FILE_NOT_FOUND;
  339. }
  340. Vector<SharedObject> shared_objects;
  341. String pck_path = p_path.get_basename() + ".pck";
  342. Error error = save_pack(p_preset, pck_path, &shared_objects);
  343. if (error != OK) {
  344. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  345. return error;
  346. }
  347. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  348. for (int i = 0; i < shared_objects.size(); i++) {
  349. String dst = p_path.get_base_dir().plus_file(shared_objects[i].path.get_file());
  350. error = da->copy(shared_objects[i].path, dst);
  351. if (error != OK) {
  352. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  353. memdelete(da);
  354. return error;
  355. }
  356. }
  357. memdelete(da);
  358. FileAccess *src_f = NULL;
  359. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  360. unzFile pkg = unzOpen2(template_path.utf8().get_data(), &io);
  361. if (!pkg) {
  362. EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + template_path);
  363. return ERR_FILE_NOT_FOUND;
  364. }
  365. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  366. EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + template_path);
  367. unzClose(pkg);
  368. return ERR_FILE_CORRUPT;
  369. }
  370. do {
  371. //get filename
  372. unz_file_info info;
  373. char fname[16384];
  374. unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
  375. String file = fname;
  376. Vector<uint8_t> data;
  377. data.resize(info.uncompressed_size);
  378. //read
  379. unzOpenCurrentFile(pkg);
  380. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  381. unzCloseCurrentFile(pkg);
  382. //write
  383. if (file == "godot.html") {
  384. if (!custom_html.empty()) {
  385. continue;
  386. }
  387. _fix_html(data, p_preset, p_path.get_file().get_basename(), p_debug, shared_objects);
  388. file = p_path.get_file();
  389. } else if (file == "godot.js") {
  390. file = p_path.get_file().get_basename() + ".js";
  391. } else if (file == "godot.worker.js") {
  392. file = p_path.get_file().get_basename() + ".worker.js";
  393. } else if (file == "godot.side.wasm") {
  394. file = p_path.get_file().get_basename() + ".side.wasm";
  395. } else if (file == "godot.audio.worklet.js") {
  396. file = p_path.get_file().get_basename() + ".audio.worklet.js";
  397. } else if (file == "godot.wasm") {
  398. file = p_path.get_file().get_basename() + ".wasm";
  399. }
  400. String dst = p_path.get_base_dir().plus_file(file);
  401. FileAccess *f = FileAccess::open(dst, FileAccess::WRITE);
  402. if (!f) {
  403. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst);
  404. unzClose(pkg);
  405. return ERR_FILE_CANT_WRITE;
  406. }
  407. f->store_buffer(data.ptr(), data.size());
  408. memdelete(f);
  409. } while (unzGoToNextFile(pkg) == UNZ_OK);
  410. unzClose(pkg);
  411. if (!custom_html.empty()) {
  412. FileAccess *f = FileAccess::open(custom_html, FileAccess::READ);
  413. if (!f) {
  414. EditorNode::get_singleton()->show_warning(TTR("Could not read custom HTML shell:") + "\n" + custom_html);
  415. return ERR_FILE_CANT_READ;
  416. }
  417. Vector<uint8_t> buf;
  418. buf.resize(f->get_len());
  419. f->get_buffer(buf.ptrw(), buf.size());
  420. memdelete(f);
  421. _fix_html(buf, p_preset, p_path.get_file().get_basename(), p_debug, shared_objects);
  422. f = FileAccess::open(p_path, FileAccess::WRITE);
  423. if (!f) {
  424. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path);
  425. return ERR_FILE_CANT_WRITE;
  426. }
  427. f->store_buffer(buf.ptr(), buf.size());
  428. memdelete(f);
  429. }
  430. Ref<Image> splash;
  431. const String splash_path = String(GLOBAL_GET("application/boot_splash/image")).strip_edges();
  432. if (!splash_path.empty()) {
  433. splash.instance();
  434. const Error err = splash->load(splash_path);
  435. if (err) {
  436. EditorNode::get_singleton()->show_warning(TTR("Could not read boot splash image file:") + "\n" + splash_path + "\n" + TTR("Using default boot splash image."));
  437. splash.unref();
  438. }
  439. }
  440. if (splash.is_null()) {
  441. splash = Ref<Image>(memnew(Image(boot_splash_png)));
  442. }
  443. const String splash_png_path = p_path.get_base_dir().plus_file(p_path.get_file().get_basename() + ".png");
  444. if (splash->save_png(splash_png_path) != OK) {
  445. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  446. return ERR_FILE_CANT_WRITE;
  447. }
  448. // Save a favicon that can be accessed without waiting for the project to finish loading.
  449. // This way, the favicon can be displayed immediately when loading the page.
  450. Ref<Image> favicon;
  451. const String favicon_path = String(GLOBAL_GET("application/config/icon")).strip_edges();
  452. if (!favicon_path.empty()) {
  453. favicon.instance();
  454. const Error err = favicon->load(favicon_path);
  455. if (err) {
  456. favicon.unref();
  457. }
  458. }
  459. if (favicon.is_valid()) {
  460. const String favicon_png_path = p_path.get_base_dir().plus_file("favicon.png");
  461. if (favicon->save_png(favicon_png_path) != OK) {
  462. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  463. return ERR_FILE_CANT_WRITE;
  464. }
  465. }
  466. return OK;
  467. }
  468. bool EditorExportPlatformJavaScript::poll_export() {
  469. Ref<EditorExportPreset> preset;
  470. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  471. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  472. if (ep->is_runnable() && ep->get_platform() == this) {
  473. preset = ep;
  474. break;
  475. }
  476. }
  477. int prev = menu_options;
  478. menu_options = preset.is_valid();
  479. if (server->is_listening()) {
  480. if (menu_options == 0) {
  481. server_lock->lock();
  482. server->stop();
  483. server_lock->unlock();
  484. } else {
  485. menu_options += 1;
  486. }
  487. }
  488. return menu_options != prev;
  489. }
  490. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  491. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  492. }
  493. int EditorExportPlatformJavaScript::get_options_count() const {
  494. return menu_options;
  495. }
  496. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  497. if (p_option == 1) {
  498. server_lock->lock();
  499. server->stop();
  500. server_lock->unlock();
  501. return OK;
  502. }
  503. const String basepath = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmp_js_export");
  504. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  505. if (err != OK) {
  506. // Export generates several files, clean them up on failure.
  507. DirAccess::remove_file_or_error(basepath + ".html");
  508. DirAccess::remove_file_or_error(basepath + ".js");
  509. DirAccess::remove_file_or_error(basepath + ".worker.js");
  510. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  511. DirAccess::remove_file_or_error(basepath + ".pck");
  512. DirAccess::remove_file_or_error(basepath + ".png");
  513. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  514. DirAccess::remove_file_or_error(basepath + ".wasm");
  515. DirAccess::remove_file_or_error(EditorSettings::get_singleton()->get_cache_dir().plus_file("favicon.png"));
  516. return err;
  517. }
  518. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  519. // Resolve host if needed.
  520. const String bind_host = EDITOR_GET("export/web/http_host");
  521. IP_Address bind_ip;
  522. if (bind_host.is_valid_ip_address()) {
  523. bind_ip = bind_host;
  524. } else {
  525. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  526. }
  527. 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'.");
  528. // Restart server.
  529. server_lock->lock();
  530. server->stop();
  531. err = server->listen(bind_port, bind_ip);
  532. server_lock->unlock();
  533. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to start HTTP server.");
  534. OS::get_singleton()->shell_open(String("http://" + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  535. // FIXME: Find out how to clean up export files after running the successfully
  536. // exported game. Might not be trivial.
  537. return OK;
  538. }
  539. Ref<Texture> EditorExportPlatformJavaScript::get_run_icon() const {
  540. return run_icon;
  541. }
  542. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  543. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  544. while (!ej->server_quit) {
  545. OS::get_singleton()->delay_usec(1000);
  546. ej->server_lock->lock();
  547. ej->server->poll();
  548. ej->server_lock->unlock();
  549. }
  550. }
  551. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  552. server.instance();
  553. server_quit = false;
  554. server_lock = Mutex::create();
  555. server_thread = Thread::create(_server_thread_poll, this);
  556. Ref<Image> img = memnew(Image(_javascript_logo));
  557. logo.instance();
  558. logo->create_from_image(img);
  559. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  560. run_icon.instance();
  561. run_icon->create_from_image(img);
  562. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  563. if (theme.is_valid())
  564. stop_icon = theme->get_icon("Stop", "EditorIcons");
  565. else
  566. stop_icon.instance();
  567. menu_options = 0;
  568. }
  569. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  570. server->stop();
  571. server_quit = true;
  572. Thread::wait_to_finish(server_thread);
  573. memdelete(server_lock);
  574. memdelete(server_thread);
  575. }
  576. void register_javascript_exporter() {
  577. EDITOR_DEF("export/web/http_host", "localhost");
  578. EDITOR_DEF("export/web/http_port", 8060);
  579. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1"));
  580. Ref<EditorExportPlatformJavaScript> platform;
  581. platform.instance();
  582. EditorExport::get_singleton()->add_export_platform(platform);
  583. }