2
0

export.cpp 24 KB

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