export.cpp 25 KB

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