export.cpp 36 KB

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