export.cpp 25 KB

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