export.cpp 25 KB

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