export.cpp 25 KB

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