export.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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/stream_peer_ssl.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 RefCounted {
  40. private:
  41. Ref<TCPServer> server;
  42. Map<String, String> mimes;
  43. Ref<StreamPeerTCP> tcp;
  44. Ref<StreamPeerSSL> ssl;
  45. Ref<StreamPeer> peer;
  46. Ref<CryptoKey> key;
  47. Ref<X509Certificate> cert;
  48. bool use_ssl = false;
  49. uint64_t time = 0;
  50. uint8_t req_buf[4096];
  51. int req_pos = 0;
  52. void _clear_client() {
  53. peer = Ref<StreamPeer>();
  54. ssl = Ref<StreamPeerSSL>();
  55. tcp = Ref<StreamPeerTCP>();
  56. memset(req_buf, 0, sizeof(req_buf));
  57. time = 0;
  58. req_pos = 0;
  59. }
  60. void _set_internal_certs(Ref<Crypto> p_crypto) {
  61. const String cache_path = EditorPaths::get_singleton()->get_cache_dir();
  62. const String key_path = cache_path.plus_file("html5_server.key");
  63. const String crt_path = cache_path.plus_file("html5_server.crt");
  64. bool regen = !FileAccess::exists(key_path) || !FileAccess::exists(crt_path);
  65. if (!regen) {
  66. key = Ref<CryptoKey>(CryptoKey::create());
  67. cert = Ref<X509Certificate>(X509Certificate::create());
  68. if (key->load(key_path) != OK || cert->load(crt_path) != OK) {
  69. regen = true;
  70. }
  71. }
  72. if (regen) {
  73. key = p_crypto->generate_rsa(2048);
  74. key->save(key_path);
  75. cert = p_crypto->generate_self_signed_certificate(key, "CN=godot-debug.local,O=A Game Dev,C=XXA", "20140101000000", "20340101000000");
  76. cert->save(crt_path);
  77. }
  78. }
  79. public:
  80. EditorHTTPServer() {
  81. mimes["html"] = "text/html";
  82. mimes["js"] = "application/javascript";
  83. mimes["json"] = "application/json";
  84. mimes["pck"] = "application/octet-stream";
  85. mimes["png"] = "image/png";
  86. mimes["svg"] = "image/svg";
  87. mimes["wasm"] = "application/wasm";
  88. server.instantiate();
  89. stop();
  90. }
  91. void stop() {
  92. server->stop();
  93. _clear_client();
  94. }
  95. Error listen(int p_port, IPAddress p_address, bool p_use_ssl, String p_ssl_key, String p_ssl_cert) {
  96. use_ssl = p_use_ssl;
  97. if (use_ssl) {
  98. Ref<Crypto> crypto = Crypto::create();
  99. if (crypto.is_null()) {
  100. return ERR_UNAVAILABLE;
  101. }
  102. if (!p_ssl_key.is_empty() && !p_ssl_cert.is_empty()) {
  103. key = Ref<CryptoKey>(CryptoKey::create());
  104. Error err = key->load(p_ssl_key);
  105. ERR_FAIL_COND_V(err != OK, err);
  106. cert = Ref<X509Certificate>(X509Certificate::create());
  107. err = cert->load(p_ssl_cert);
  108. ERR_FAIL_COND_V(err != OK, err);
  109. } else {
  110. _set_internal_certs(crypto);
  111. }
  112. }
  113. return server->listen(p_port, p_address);
  114. }
  115. bool is_listening() const {
  116. return server->is_listening();
  117. }
  118. void _send_response() {
  119. Vector<String> psa = String((char *)req_buf).split("\r\n");
  120. int len = psa.size();
  121. ERR_FAIL_COND_MSG(len < 4, "Not enough response headers, got: " + itos(len) + ", expected >= 4.");
  122. Vector<String> req = psa[0].split(" ", false);
  123. ERR_FAIL_COND_MSG(req.size() < 2, "Invalid protocol or status code.");
  124. // Wrong protocol
  125. ERR_FAIL_COND_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", "Invalid method or HTTP version.");
  126. const int query_index = req[1].find_char('?');
  127. const String path = (query_index == -1) ? req[1] : req[1].substr(0, query_index);
  128. const String req_file = path.get_file();
  129. const String req_ext = path.get_extension();
  130. const String cache_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  131. const String filepath = cache_path.plus_file(req_file);
  132. if (!mimes.has(req_ext) || !FileAccess::exists(filepath)) {
  133. String s = "HTTP/1.1 404 Not Found\r\n";
  134. s += "Connection: Close\r\n";
  135. s += "\r\n";
  136. CharString cs = s.utf8();
  137. peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  138. return;
  139. }
  140. const String ctype = mimes[req_ext];
  141. FileAccess *f = FileAccess::open(filepath, FileAccess::READ);
  142. ERR_FAIL_COND(!f);
  143. String s = "HTTP/1.1 200 OK\r\n";
  144. s += "Connection: Close\r\n";
  145. s += "Content-Type: " + ctype + "\r\n";
  146. s += "Access-Control-Allow-Origin: *\r\n";
  147. s += "Cross-Origin-Opener-Policy: same-origin\r\n";
  148. s += "Cross-Origin-Embedder-Policy: require-corp\r\n";
  149. s += "Cache-Control: no-store, max-age=0\r\n";
  150. s += "\r\n";
  151. CharString cs = s.utf8();
  152. Error err = peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1);
  153. if (err != OK) {
  154. memdelete(f);
  155. ERR_FAIL();
  156. }
  157. while (true) {
  158. uint8_t bytes[4096];
  159. uint64_t read = f->get_buffer(bytes, 4096);
  160. if (read == 0) {
  161. break;
  162. }
  163. err = peer->put_data(bytes, read);
  164. if (err != OK) {
  165. memdelete(f);
  166. ERR_FAIL();
  167. }
  168. }
  169. memdelete(f);
  170. }
  171. void poll() {
  172. if (!server->is_listening()) {
  173. return;
  174. }
  175. if (tcp.is_null()) {
  176. if (!server->is_connection_available()) {
  177. return;
  178. }
  179. tcp = server->take_connection();
  180. peer = tcp;
  181. time = OS::get_singleton()->get_ticks_usec();
  182. }
  183. if (OS::get_singleton()->get_ticks_usec() - time > 1000000) {
  184. _clear_client();
  185. return;
  186. }
  187. if (tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  188. return;
  189. }
  190. if (use_ssl) {
  191. if (ssl.is_null()) {
  192. ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
  193. peer = ssl;
  194. ssl->set_blocking_handshake_enabled(false);
  195. if (ssl->accept_stream(tcp, key, cert) != OK) {
  196. _clear_client();
  197. return;
  198. }
  199. }
  200. ssl->poll();
  201. if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
  202. // Still handshaking, keep waiting.
  203. return;
  204. }
  205. if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
  206. _clear_client();
  207. return;
  208. }
  209. }
  210. while (true) {
  211. char *r = (char *)req_buf;
  212. int l = req_pos - 1;
  213. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  214. _send_response();
  215. _clear_client();
  216. return;
  217. }
  218. int read = 0;
  219. ERR_FAIL_COND(req_pos >= 4096);
  220. Error err = peer->get_partial_data(&req_buf[req_pos], 1, read);
  221. if (err != OK) {
  222. // Got an error
  223. _clear_client();
  224. return;
  225. } else if (read != 1) {
  226. // Busy, wait next poll
  227. return;
  228. }
  229. req_pos += read;
  230. }
  231. }
  232. };
  233. class EditorExportPlatformJavaScript : public EditorExportPlatform {
  234. GDCLASS(EditorExportPlatformJavaScript, EditorExportPlatform);
  235. Ref<ImageTexture> logo;
  236. Ref<ImageTexture> run_icon;
  237. Ref<ImageTexture> stop_icon;
  238. int menu_options = 0;
  239. Ref<EditorHTTPServer> server;
  240. bool server_quit = false;
  241. Mutex server_lock;
  242. Thread server_thread;
  243. enum ExportMode {
  244. EXPORT_MODE_NORMAL = 0,
  245. EXPORT_MODE_THREADS = 1,
  246. EXPORT_MODE_GDNATIVE = 2,
  247. };
  248. String _get_template_name(ExportMode p_mode, bool p_debug) const {
  249. String name = "webassembly";
  250. switch (p_mode) {
  251. case EXPORT_MODE_THREADS:
  252. name += "_threads";
  253. break;
  254. case EXPORT_MODE_GDNATIVE:
  255. name += "_gdnative";
  256. break;
  257. default:
  258. break;
  259. }
  260. if (p_debug) {
  261. name += "_debug.zip";
  262. } else {
  263. name += "_release.zip";
  264. }
  265. return name;
  266. }
  267. Ref<Image> _get_project_icon() const {
  268. Ref<Image> icon;
  269. icon.instantiate();
  270. const String icon_path = String(GLOBAL_GET("application/config/icon")).strip_edges();
  271. if (icon_path.is_empty() || ImageLoader::load_image(icon_path, icon) != OK) {
  272. return EditorNode::get_singleton()->get_editor_theme()->get_icon("DefaultProjectIcon", "EditorIcons")->get_image();
  273. }
  274. return icon;
  275. }
  276. Ref<Image> _get_project_splash() const {
  277. Ref<Image> splash;
  278. splash.instantiate();
  279. const String splash_path = String(GLOBAL_GET("application/boot_splash/image")).strip_edges();
  280. if (splash_path.is_empty() || ImageLoader::load_image(splash_path, splash) != OK) {
  281. return Ref<Image>(memnew(Image(boot_splash_png)));
  282. }
  283. return splash;
  284. }
  285. Error _extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa);
  286. void _replace_strings(Map<String, String> p_replaces, Vector<uint8_t> &r_template);
  287. 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);
  288. Error _add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr);
  289. Error _build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects);
  290. Error _write_or_error(const uint8_t *p_content, int p_len, String p_path);
  291. static void _server_thread_poll(void *data);
  292. public:
  293. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) override;
  294. virtual void get_export_options(List<ExportOption> *r_options) override;
  295. virtual String get_name() const override;
  296. virtual String get_os_name() const override;
  297. virtual Ref<Texture2D> get_logo() const override;
  298. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const override;
  299. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override;
  300. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override;
  301. virtual bool poll_export() override;
  302. virtual int get_options_count() const override;
  303. virtual String get_option_label(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run in Browser"); }
  304. 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."); }
  305. virtual Ref<ImageTexture> get_option_icon(int p_index) const override;
  306. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) override;
  307. virtual Ref<Texture2D> get_run_icon() const override;
  308. virtual void get_platform_features(List<String> *r_features) override {
  309. r_features->push_back("web");
  310. r_features->push_back(get_os_name());
  311. }
  312. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) override {
  313. }
  314. String get_debug_protocol() const override { return "ws://"; }
  315. EditorExportPlatformJavaScript();
  316. ~EditorExportPlatformJavaScript();
  317. };
  318. Error EditorExportPlatformJavaScript::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) {
  319. FileAccess *src_f = nullptr;
  320. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  321. unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io);
  322. if (!pkg) {
  323. EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + p_template);
  324. return ERR_FILE_NOT_FOUND;
  325. }
  326. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  327. EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + p_template);
  328. unzClose(pkg);
  329. return ERR_FILE_CORRUPT;
  330. }
  331. do {
  332. //get filename
  333. unz_file_info info;
  334. char fname[16384];
  335. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  336. String file = fname;
  337. // Skip service worker and offline page if not exporting pwa.
  338. if (!pwa && (file == "godot.service.worker.js" || file == "godot.offline.html")) {
  339. continue;
  340. }
  341. Vector<uint8_t> data;
  342. data.resize(info.uncompressed_size);
  343. //read
  344. unzOpenCurrentFile(pkg);
  345. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  346. unzCloseCurrentFile(pkg);
  347. //write
  348. String dst = p_dir.plus_file(file.replace("godot", p_name));
  349. FileAccess *f = FileAccess::open(dst, FileAccess::WRITE);
  350. if (!f) {
  351. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst);
  352. unzClose(pkg);
  353. return ERR_FILE_CANT_WRITE;
  354. }
  355. f->store_buffer(data.ptr(), data.size());
  356. memdelete(f);
  357. } while (unzGoToNextFile(pkg) == UNZ_OK);
  358. unzClose(pkg);
  359. return OK;
  360. }
  361. Error EditorExportPlatformJavaScript::_write_or_error(const uint8_t *p_content, int p_size, String p_path) {
  362. FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
  363. if (!f) {
  364. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path);
  365. return ERR_FILE_CANT_WRITE;
  366. }
  367. f->store_buffer(p_content, p_size);
  368. memdelete(f);
  369. return OK;
  370. }
  371. void EditorExportPlatformJavaScript::_replace_strings(Map<String, String> p_replaces, Vector<uint8_t> &r_template) {
  372. String str_template = String::utf8(reinterpret_cast<const char *>(r_template.ptr()), r_template.size());
  373. String out;
  374. Vector<String> lines = str_template.split("\n");
  375. for (int i = 0; i < lines.size(); i++) {
  376. String current_line = lines[i];
  377. for (Map<String, String>::Element *E = p_replaces.front(); E; E = E->next()) {
  378. current_line = current_line.replace(E->key(), E->get());
  379. }
  380. out += current_line + "\n";
  381. }
  382. CharString cs = out.utf8();
  383. r_template.resize(cs.length());
  384. for (int i = 0; i < cs.length(); i++) {
  385. r_template.write[i] = cs[i];
  386. }
  387. }
  388. 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) {
  389. // Engine.js config
  390. Dictionary config;
  391. Array libs;
  392. for (int i = 0; i < p_shared_objects.size(); i++) {
  393. libs.push_back(p_shared_objects[i].path.get_file());
  394. }
  395. Vector<String> flags;
  396. gen_export_flags(flags, p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  397. Array args;
  398. for (int i = 0; i < flags.size(); i++) {
  399. args.push_back(flags[i]);
  400. }
  401. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  402. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  403. config["focusCanvas"] = p_preset->get("html/focus_canvas_on_start");
  404. config["gdnativeLibs"] = libs;
  405. config["executable"] = p_name;
  406. config["args"] = args;
  407. config["fileSizes"] = p_file_sizes;
  408. String head_include;
  409. if (p_preset->get("html/export_icon")) {
  410. head_include += "<link id='-gd-engine-icon' rel='icon' type='image/png' href='" + p_name + ".icon.png' />\n";
  411. head_include += "<link rel='apple-touch-icon' href='" + p_name + ".apple-touch-icon.png'/>\n";
  412. }
  413. if (p_preset->get("progressive_web_app/enabled")) {
  414. head_include += "<link rel='manifest' href='" + p_name + ".manifest.json'>\n";
  415. head_include += "<script type='application/javascript'>window.addEventListener('load', () => {if ('serviceWorker' in navigator) {navigator.serviceWorker.register('" +
  416. p_name + ".service.worker.js');}});</script>\n";
  417. }
  418. // Replaces HTML string
  419. const String str_config = Variant(config).to_json_string();
  420. const String custom_head_include = p_preset->get("html/head_include");
  421. Map<String, String> replaces;
  422. replaces["$GODOT_URL"] = p_name + ".js";
  423. replaces["$GODOT_PROJECT_NAME"] = ProjectSettings::get_singleton()->get_setting("application/config/name");
  424. replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include;
  425. replaces["$GODOT_CONFIG"] = str_config;
  426. _replace_strings(replaces, p_html);
  427. }
  428. Error EditorExportPlatformJavaScript::_add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr) {
  429. const String name = p_path.get_file().get_basename();
  430. const String icon_name = vformat("%s.%dx%d.png", name, p_size, p_size);
  431. const String icon_dest = p_path.get_base_dir().plus_file(icon_name);
  432. Ref<Image> icon;
  433. if (!p_icon.is_empty()) {
  434. icon.instantiate();
  435. const Error err = ImageLoader::load_image(p_icon, icon);
  436. if (err != OK) {
  437. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + p_icon);
  438. return err;
  439. }
  440. if (icon->get_width() != p_size || icon->get_height() != p_size) {
  441. icon->resize(p_size, p_size);
  442. }
  443. } else {
  444. icon = _get_project_icon();
  445. icon->resize(p_size, p_size);
  446. }
  447. const Error err = icon->save_png(icon_dest);
  448. if (err != OK) {
  449. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + icon_dest);
  450. return err;
  451. }
  452. Dictionary icon_dict;
  453. icon_dict["sizes"] = vformat("%dx%d", p_size, p_size);
  454. icon_dict["type"] = "image/png";
  455. icon_dict["src"] = icon_name;
  456. r_arr.push_back(icon_dict);
  457. return err;
  458. }
  459. Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
  460. // Service worker
  461. const String dir = p_path.get_base_dir();
  462. const String name = p_path.get_file().get_basename();
  463. const ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  464. Map<String, String> replaces;
  465. replaces["@GODOT_VERSION@"] = "1";
  466. replaces["@GODOT_NAME@"] = name;
  467. replaces["@GODOT_OFFLINE_PAGE@"] = name + ".offline.html";
  468. Array files;
  469. replaces["@GODOT_OPT_CACHE@"] = Variant(files).to_json_string();
  470. files.push_back(name + ".html");
  471. files.push_back(name + ".js");
  472. files.push_back(name + ".wasm");
  473. files.push_back(name + ".pck");
  474. files.push_back(name + ".offline.html");
  475. if (p_preset->get("html/export_icon")) {
  476. files.push_back(name + ".icon.png");
  477. files.push_back(name + ".apple-touch-icon.png");
  478. }
  479. if (mode == EXPORT_MODE_THREADS) {
  480. files.push_back(name + ".worker.js");
  481. files.push_back(name + ".audio.worklet.js");
  482. } else if (mode == EXPORT_MODE_GDNATIVE) {
  483. files.push_back(name + ".side.wasm");
  484. for (int i = 0; i < p_shared_objects.size(); i++) {
  485. files.push_back(p_shared_objects[i].path.get_file());
  486. }
  487. }
  488. replaces["@GODOT_CACHE@"] = Variant(files).to_json_string();
  489. const String sw_path = dir.plus_file(name + ".service.worker.js");
  490. Vector<uint8_t> sw;
  491. {
  492. FileAccess *f = FileAccess::open(sw_path, FileAccess::READ);
  493. if (!f) {
  494. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + sw_path);
  495. return ERR_FILE_CANT_READ;
  496. }
  497. sw.resize(f->get_length());
  498. f->get_buffer(sw.ptrw(), sw.size());
  499. memdelete(f);
  500. f = nullptr;
  501. }
  502. _replace_strings(replaces, sw);
  503. Error err = _write_or_error(sw.ptr(), sw.size(), dir.plus_file(name + ".service.worker.js"));
  504. if (err != OK) {
  505. return err;
  506. }
  507. // Custom offline page
  508. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  509. if (!offline_page.is_empty()) {
  510. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  511. const String offline_dest = dir.plus_file(name + ".offline.html");
  512. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  513. if (err != OK) {
  514. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + offline_dest);
  515. return err;
  516. }
  517. }
  518. // Manifest
  519. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  520. const char *orientations[3] = { "any", "landscape", "portrait" };
  521. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  522. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  523. Dictionary manifest;
  524. String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
  525. if (proj_name.is_empty()) {
  526. proj_name = "Godot Game";
  527. }
  528. manifest["name"] = proj_name;
  529. manifest["start_url"] = "./" + name + ".html";
  530. manifest["display"] = String::utf8(modes[display]);
  531. manifest["orientation"] = String::utf8(orientations[orientation]);
  532. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  533. Array icons_arr;
  534. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  535. err = _add_manifest_icon(p_path, icon144_path, 144, icons_arr);
  536. if (err != OK) {
  537. return err;
  538. }
  539. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  540. err = _add_manifest_icon(p_path, icon180_path, 180, icons_arr);
  541. if (err != OK) {
  542. return err;
  543. }
  544. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  545. err = _add_manifest_icon(p_path, icon512_path, 512, icons_arr);
  546. if (err != OK) {
  547. return err;
  548. }
  549. manifest["icons"] = icons_arr;
  550. CharString cs = Variant(manifest).to_json_string().utf8();
  551. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.plus_file(name + ".manifest.json"));
  552. if (err != OK) {
  553. return err;
  554. }
  555. return OK;
  556. }
  557. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  558. if (p_preset->get("vram_texture_compression/for_desktop")) {
  559. r_features->push_back("s3tc");
  560. }
  561. if (p_preset->get("vram_texture_compression/for_mobile")) {
  562. String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name");
  563. if (driver == "GLES2") {
  564. r_features->push_back("etc");
  565. } else if (driver == "Vulkan") {
  566. // FIXME: Review if this is correct.
  567. r_features->push_back("etc2");
  568. }
  569. }
  570. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  571. if (mode == EXPORT_MODE_THREADS) {
  572. r_features->push_back("threads");
  573. } else if (mode == EXPORT_MODE_GDNATIVE) {
  574. r_features->push_back("wasm32");
  575. }
  576. }
  577. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  578. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  579. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  580. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type.
  581. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  582. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  583. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  584. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  585. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  586. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  587. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/focus_canvas_on_start"), true));
  588. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  589. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  590. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  591. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal UI,Browser"), 1));
  592. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  593. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  594. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  595. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg,*.svgz"), ""));
  596. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  597. }
  598. String EditorExportPlatformJavaScript::get_name() const {
  599. return "HTML5";
  600. }
  601. String EditorExportPlatformJavaScript::get_os_name() const {
  602. return "HTML5";
  603. }
  604. Ref<Texture2D> EditorExportPlatformJavaScript::get_logo() const {
  605. return logo;
  606. }
  607. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  608. String err;
  609. bool valid = false;
  610. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  611. // Look for export templates (first official, and if defined custom templates).
  612. bool dvalid = exists_export_template(_get_template_name(mode, true), &err);
  613. bool rvalid = exists_export_template(_get_template_name(mode, false), &err);
  614. if (p_preset->get("custom_template/debug") != "") {
  615. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  616. if (!dvalid) {
  617. err += TTR("Custom debug template not found.") + "\n";
  618. }
  619. }
  620. if (p_preset->get("custom_template/release") != "") {
  621. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  622. if (!rvalid) {
  623. err += TTR("Custom release template not found.") + "\n";
  624. }
  625. }
  626. valid = dvalid || rvalid;
  627. r_missing_templates = !valid;
  628. // Validate the rest of the configuration.
  629. if (p_preset->get("vram_texture_compression/for_mobile")) {
  630. String etc_error = test_etc2();
  631. if (etc_error != String()) {
  632. valid = false;
  633. err += etc_error;
  634. }
  635. }
  636. if (!err.is_empty()) {
  637. r_error = err;
  638. }
  639. return valid;
  640. }
  641. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  642. List<String> list;
  643. list.push_back("html");
  644. return list;
  645. }
  646. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  647. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  648. const String custom_debug = p_preset->get("custom_template/debug");
  649. const String custom_release = p_preset->get("custom_template/release");
  650. const String custom_html = p_preset->get("html/custom_html_shell");
  651. const bool export_icon = p_preset->get("html/export_icon");
  652. const bool pwa = p_preset->get("progressive_web_app/enabled");
  653. const String base_dir = p_path.get_base_dir();
  654. const String base_path = p_path.get_basename();
  655. const String base_name = p_path.get_file().get_basename();
  656. // Find the correct template
  657. String template_path = p_debug ? custom_debug : custom_release;
  658. template_path = template_path.strip_edges();
  659. if (template_path == String()) {
  660. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  661. template_path = find_export_template(_get_template_name(mode, p_debug));
  662. }
  663. if (!DirAccess::exists(base_dir)) {
  664. return ERR_FILE_BAD_PATH;
  665. }
  666. if (template_path != String() && !FileAccess::exists(template_path)) {
  667. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  668. return ERR_FILE_NOT_FOUND;
  669. }
  670. // Export pck and shared objects
  671. Vector<SharedObject> shared_objects;
  672. String pck_path = base_path + ".pck";
  673. Error error = save_pack(p_preset, pck_path, &shared_objects);
  674. if (error != OK) {
  675. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  676. return error;
  677. }
  678. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  679. for (int i = 0; i < shared_objects.size(); i++) {
  680. String dst = base_dir.plus_file(shared_objects[i].path.get_file());
  681. error = da->copy(shared_objects[i].path, dst);
  682. if (error != OK) {
  683. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  684. memdelete(da);
  685. return error;
  686. }
  687. }
  688. memdelete(da);
  689. da = nullptr;
  690. // Extract templates.
  691. error = _extract_template(template_path, base_dir, base_name, pwa);
  692. if (error) {
  693. return error;
  694. }
  695. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  696. Dictionary file_sizes;
  697. FileAccess *f = nullptr;
  698. f = FileAccess::open(pck_path, FileAccess::READ);
  699. if (f) {
  700. file_sizes[pck_path.get_file()] = (uint64_t)f->get_length();
  701. memdelete(f);
  702. f = nullptr;
  703. }
  704. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  705. if (f) {
  706. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length();
  707. memdelete(f);
  708. f = nullptr;
  709. }
  710. // Read the HTML shell file (custom or from template).
  711. const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html;
  712. Vector<uint8_t> html;
  713. f = FileAccess::open(html_path, FileAccess::READ);
  714. if (!f) {
  715. EditorNode::get_singleton()->show_warning(TTR("Could not read HTML shell:") + "\n" + html_path);
  716. return ERR_FILE_CANT_READ;
  717. }
  718. html.resize(f->get_length());
  719. f->get_buffer(html.ptrw(), html.size());
  720. memdelete(f);
  721. f = nullptr;
  722. // Generate HTML file with replaced strings.
  723. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  724. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  725. if (err != OK) {
  726. return err;
  727. }
  728. html.resize(0);
  729. // Export splash (why?)
  730. Ref<Image> splash = _get_project_splash();
  731. const String splash_png_path = base_path + ".png";
  732. if (splash->save_png(splash_png_path) != OK) {
  733. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  734. return ERR_FILE_CANT_WRITE;
  735. }
  736. // Save a favicon that can be accessed without waiting for the project to finish loading.
  737. // This way, the favicon can be displayed immediately when loading the page.
  738. if (export_icon) {
  739. Ref<Image> favicon = _get_project_icon();
  740. const String favicon_png_path = base_path + ".icon.png";
  741. if (favicon->save_png(favicon_png_path) != OK) {
  742. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  743. return ERR_FILE_CANT_WRITE;
  744. }
  745. favicon->resize(180, 180);
  746. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  747. if (favicon->save_png(apple_icon_png_path) != OK) {
  748. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + apple_icon_png_path);
  749. return ERR_FILE_CANT_WRITE;
  750. }
  751. }
  752. // Generate the PWA worker and manifest
  753. if (pwa) {
  754. err = _build_pwa(p_preset, p_path, shared_objects);
  755. if (err != OK) {
  756. return err;
  757. }
  758. }
  759. return OK;
  760. }
  761. bool EditorExportPlatformJavaScript::poll_export() {
  762. Ref<EditorExportPreset> preset;
  763. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  764. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  765. if (ep->is_runnable() && ep->get_platform() == this) {
  766. preset = ep;
  767. break;
  768. }
  769. }
  770. int prev = menu_options;
  771. menu_options = preset.is_valid();
  772. if (server->is_listening()) {
  773. if (menu_options == 0) {
  774. MutexLock lock(server_lock);
  775. server->stop();
  776. } else {
  777. menu_options += 1;
  778. }
  779. }
  780. return menu_options != prev;
  781. }
  782. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  783. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  784. }
  785. int EditorExportPlatformJavaScript::get_options_count() const {
  786. return menu_options;
  787. }
  788. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  789. if (p_option == 1) {
  790. MutexLock lock(server_lock);
  791. server->stop();
  792. return OK;
  793. }
  794. const String dest = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  795. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  796. if (!da->dir_exists(dest)) {
  797. Error err = da->make_dir_recursive(dest);
  798. if (err != OK) {
  799. EditorNode::get_singleton()->show_warning(TTR("Could not create HTTP server directory:") + "\n" + dest);
  800. return err;
  801. }
  802. }
  803. const String basepath = dest.plus_file("tmp_js_export");
  804. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  805. if (err != OK) {
  806. // Export generates several files, clean them up on failure.
  807. DirAccess::remove_file_or_error(basepath + ".html");
  808. DirAccess::remove_file_or_error(basepath + ".offline.html");
  809. DirAccess::remove_file_or_error(basepath + ".js");
  810. DirAccess::remove_file_or_error(basepath + ".worker.js");
  811. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  812. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  813. DirAccess::remove_file_or_error(basepath + ".pck");
  814. DirAccess::remove_file_or_error(basepath + ".png");
  815. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  816. DirAccess::remove_file_or_error(basepath + ".wasm");
  817. DirAccess::remove_file_or_error(basepath + ".icon.png");
  818. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  819. return err;
  820. }
  821. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  822. // Resolve host if needed.
  823. const String bind_host = EDITOR_GET("export/web/http_host");
  824. IPAddress bind_ip;
  825. if (bind_host.is_valid_ip_address()) {
  826. bind_ip = bind_host;
  827. } else {
  828. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  829. }
  830. 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'.");
  831. const bool use_ssl = EDITOR_GET("export/web/use_ssl");
  832. const String ssl_key = EDITOR_GET("export/web/ssl_key");
  833. const String ssl_cert = EDITOR_GET("export/web/ssl_certificate");
  834. // Restart server.
  835. {
  836. MutexLock lock(server_lock);
  837. server->stop();
  838. err = server->listen(bind_port, bind_ip, use_ssl, ssl_key, ssl_cert);
  839. }
  840. if (err != OK) {
  841. EditorNode::get_singleton()->show_warning(TTR("Error starting HTTP server:") + "\n" + itos(err));
  842. return err;
  843. }
  844. OS::get_singleton()->shell_open(String((use_ssl ? "https://" : "http://") + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  845. // FIXME: Find out how to clean up export files after running the successfully
  846. // exported game. Might not be trivial.
  847. return OK;
  848. }
  849. Ref<Texture2D> EditorExportPlatformJavaScript::get_run_icon() const {
  850. return run_icon;
  851. }
  852. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  853. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  854. while (!ej->server_quit) {
  855. OS::get_singleton()->delay_usec(1000);
  856. {
  857. MutexLock lock(ej->server_lock);
  858. ej->server->poll();
  859. }
  860. }
  861. }
  862. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  863. server.instantiate();
  864. server_thread.start(_server_thread_poll, this);
  865. Ref<Image> img = memnew(Image(_javascript_logo));
  866. logo.instantiate();
  867. logo->create_from_image(img);
  868. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  869. run_icon.instantiate();
  870. run_icon->create_from_image(img);
  871. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  872. if (theme.is_valid()) {
  873. stop_icon = theme->get_icon("Stop", "EditorIcons");
  874. } else {
  875. stop_icon.instantiate();
  876. }
  877. }
  878. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  879. server->stop();
  880. server_quit = true;
  881. server_thread.wait_to_finish();
  882. }
  883. void register_javascript_exporter() {
  884. EDITOR_DEF("export/web/http_host", "localhost");
  885. EDITOR_DEF("export/web/http_port", 8060);
  886. EDITOR_DEF("export/web/use_ssl", false);
  887. EDITOR_DEF("export/web/ssl_key", "");
  888. EDITOR_DEF("export/web/ssl_certificate", "");
  889. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1"));
  890. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_key", PROPERTY_HINT_GLOBAL_FILE, "*.key"));
  891. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_certificate", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"));
  892. Ref<EditorExportPlatformJavaScript> platform;
  893. platform.instantiate();
  894. EditorExport::get_singleton()->add_export_platform(platform);
  895. }