export.cpp 25 KB

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