export.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. config["serviceWorker"] = p_name + ".service.worker.js";
  417. }
  418. // Replaces HTML string
  419. const String str_config = JSON::print(config);
  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.empty()) {
  434. icon.instance();
  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. String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
  461. if (proj_name.empty()) {
  462. proj_name = "Godot Game";
  463. }
  464. // Service worker
  465. const String dir = p_path.get_base_dir();
  466. const String name = p_path.get_file().get_basename();
  467. const ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  468. Map<String, String> replaces;
  469. replaces["@GODOT_VERSION@"] = String::num_int64(OS::get_singleton()->get_unix_time()) + "|" + String::num_int64(OS::get_singleton()->get_ticks_usec());
  470. replaces["@GODOT_NAME@"] = proj_name.substr(0, 16);
  471. replaces["@GODOT_OFFLINE_PAGE@"] = name + ".offline.html";
  472. // Files cached during worker install.
  473. Array cache_files;
  474. cache_files.push_back(name + ".html");
  475. cache_files.push_back(name + ".js");
  476. cache_files.push_back(name + ".offline.html");
  477. if (p_preset->get("html/export_icon")) {
  478. cache_files.push_back(name + ".icon.png");
  479. cache_files.push_back(name + ".apple-touch-icon.png");
  480. }
  481. if (mode == EXPORT_MODE_THREADS) {
  482. cache_files.push_back(name + ".worker.js");
  483. cache_files.push_back(name + ".audio.worklet.js");
  484. }
  485. replaces["@GODOT_CACHE@"] = JSON::print(cache_files);
  486. // Heavy files that are cached on demand.
  487. Array opt_cache_files;
  488. opt_cache_files.push_back(name + ".wasm");
  489. opt_cache_files.push_back(name + ".pck");
  490. if (mode == EXPORT_MODE_GDNATIVE) {
  491. opt_cache_files.push_back(name + ".side.wasm");
  492. for (int i = 0; i < p_shared_objects.size(); i++) {
  493. opt_cache_files.push_back(p_shared_objects[i].path.get_file());
  494. }
  495. }
  496. replaces["@GODOT_OPT_CACHE@"] = JSON::print(opt_cache_files);
  497. const String sw_path = dir.plus_file(name + ".service.worker.js");
  498. Vector<uint8_t> sw;
  499. {
  500. FileAccess *f = FileAccess::open(sw_path, FileAccess::READ);
  501. if (!f) {
  502. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + sw_path);
  503. return ERR_FILE_CANT_READ;
  504. }
  505. sw.resize(f->get_len());
  506. f->get_buffer(sw.ptrw(), sw.size());
  507. memdelete(f);
  508. f = nullptr;
  509. }
  510. _replace_strings(replaces, sw);
  511. Error err = _write_or_error(sw.ptr(), sw.size(), dir.plus_file(name + ".service.worker.js"));
  512. if (err != OK) {
  513. return err;
  514. }
  515. // Custom offline page
  516. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  517. if (!offline_page.empty()) {
  518. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  519. const String offline_dest = dir.plus_file(name + ".offline.html");
  520. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  521. if (err != OK) {
  522. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + offline_dest);
  523. return err;
  524. }
  525. }
  526. // Manifest
  527. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  528. const char *orientations[3] = { "any", "landscape", "portrait" };
  529. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  530. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  531. Dictionary manifest;
  532. manifest["name"] = proj_name;
  533. manifest["start_url"] = "./" + name + ".html";
  534. manifest["display"] = String::utf8(modes[display]);
  535. manifest["orientation"] = String::utf8(orientations[orientation]);
  536. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  537. Array icons_arr;
  538. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  539. err = _add_manifest_icon(p_path, icon144_path, 144, icons_arr);
  540. if (err != OK) {
  541. return err;
  542. }
  543. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  544. err = _add_manifest_icon(p_path, icon180_path, 180, icons_arr);
  545. if (err != OK) {
  546. return err;
  547. }
  548. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  549. err = _add_manifest_icon(p_path, icon512_path, 512, icons_arr);
  550. if (err != OK) {
  551. return err;
  552. }
  553. manifest["icons"] = icons_arr;
  554. CharString cs = JSON::print(manifest).utf8();
  555. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.plus_file(name + ".manifest.json"));
  556. if (err != OK) {
  557. return err;
  558. }
  559. return OK;
  560. }
  561. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  562. if (p_preset->get("vram_texture_compression/for_desktop")) {
  563. r_features->push_back("s3tc");
  564. }
  565. if (p_preset->get("vram_texture_compression/for_mobile")) {
  566. String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
  567. if (driver == "GLES2") {
  568. r_features->push_back("etc");
  569. } else if (driver == "GLES3") {
  570. r_features->push_back("etc2");
  571. if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
  572. r_features->push_back("etc");
  573. }
  574. }
  575. }
  576. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  577. if (mode == EXPORT_MODE_THREADS) {
  578. r_features->push_back("threads");
  579. } else if (mode == EXPORT_MODE_GDNATIVE) {
  580. r_features->push_back("wasm32");
  581. }
  582. }
  583. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  584. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  585. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  586. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type.
  587. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  588. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  589. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  590. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  591. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  592. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  593. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/focus_canvas_on_start"), true));
  594. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  595. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  596. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  597. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal Ui,Browser"), 1));
  598. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  599. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  600. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  601. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  602. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  603. }
  604. String EditorExportPlatformJavaScript::get_name() const {
  605. return "HTML5";
  606. }
  607. String EditorExportPlatformJavaScript::get_os_name() const {
  608. return "HTML5";
  609. }
  610. Ref<Texture> EditorExportPlatformJavaScript::get_logo() const {
  611. return logo;
  612. }
  613. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  614. String err;
  615. bool valid = false;
  616. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  617. // Look for export templates (first official, and if defined custom templates).
  618. bool dvalid = exists_export_template(_get_template_name(mode, true), &err);
  619. bool rvalid = exists_export_template(_get_template_name(mode, false), &err);
  620. if (p_preset->get("custom_template/debug") != "") {
  621. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  622. if (!dvalid) {
  623. err += TTR("Custom debug template not found.") + "\n";
  624. }
  625. }
  626. if (p_preset->get("custom_template/release") != "") {
  627. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  628. if (!rvalid) {
  629. err += TTR("Custom release template not found.") + "\n";
  630. }
  631. }
  632. valid = dvalid || rvalid;
  633. r_missing_templates = !valid;
  634. // Validate the rest of the configuration.
  635. if (p_preset->get("vram_texture_compression/for_mobile")) {
  636. String etc_error = test_etc2();
  637. if (etc_error != String()) {
  638. valid = false;
  639. err += etc_error;
  640. }
  641. }
  642. if (!err.empty()) {
  643. r_error = err;
  644. }
  645. return valid;
  646. }
  647. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  648. List<String> list;
  649. list.push_back("html");
  650. return list;
  651. }
  652. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  653. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  654. const String custom_debug = p_preset->get("custom_template/debug");
  655. const String custom_release = p_preset->get("custom_template/release");
  656. const String custom_html = p_preset->get("html/custom_html_shell");
  657. const bool export_icon = p_preset->get("html/export_icon");
  658. const bool pwa = p_preset->get("progressive_web_app/enabled");
  659. const String base_dir = p_path.get_base_dir();
  660. const String base_path = p_path.get_basename();
  661. const String base_name = p_path.get_file().get_basename();
  662. // Find the correct template
  663. String template_path = p_debug ? custom_debug : custom_release;
  664. template_path = template_path.strip_edges();
  665. if (template_path == String()) {
  666. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  667. template_path = find_export_template(_get_template_name(mode, p_debug));
  668. }
  669. if (!DirAccess::exists(base_dir)) {
  670. return ERR_FILE_BAD_PATH;
  671. }
  672. if (template_path != String() && !FileAccess::exists(template_path)) {
  673. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  674. return ERR_FILE_NOT_FOUND;
  675. }
  676. // Export pck and shared objects
  677. Vector<SharedObject> shared_objects;
  678. String pck_path = base_path + ".pck";
  679. Error error = save_pack(p_preset, pck_path, &shared_objects);
  680. if (error != OK) {
  681. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  682. return error;
  683. }
  684. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  685. for (int i = 0; i < shared_objects.size(); i++) {
  686. String dst = base_dir.plus_file(shared_objects[i].path.get_file());
  687. error = da->copy(shared_objects[i].path, dst);
  688. if (error != OK) {
  689. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  690. memdelete(da);
  691. return error;
  692. }
  693. }
  694. memdelete(da);
  695. da = nullptr;
  696. // Extract templates.
  697. error = _extract_template(template_path, base_dir, base_name, pwa);
  698. if (error) {
  699. return error;
  700. }
  701. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  702. Dictionary file_sizes;
  703. FileAccess *f = nullptr;
  704. f = FileAccess::open(pck_path, FileAccess::READ);
  705. if (f) {
  706. file_sizes[pck_path.get_file()] = (uint64_t)f->get_len();
  707. memdelete(f);
  708. f = nullptr;
  709. }
  710. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  711. if (f) {
  712. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_len();
  713. memdelete(f);
  714. f = nullptr;
  715. }
  716. // Read the HTML shell file (custom or from template).
  717. const String html_path = custom_html.empty() ? base_path + ".html" : custom_html;
  718. Vector<uint8_t> html;
  719. f = FileAccess::open(html_path, FileAccess::READ);
  720. if (!f) {
  721. EditorNode::get_singleton()->show_warning(TTR("Could not read HTML shell:") + "\n" + html_path);
  722. return ERR_FILE_CANT_READ;
  723. }
  724. html.resize(f->get_len());
  725. f->get_buffer(html.ptrw(), html.size());
  726. memdelete(f);
  727. f = nullptr;
  728. // Generate HTML file with replaced strings.
  729. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  730. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  731. if (err != OK) {
  732. return err;
  733. }
  734. html.resize(0);
  735. // Export splash (why?)
  736. Ref<Image> splash = _get_project_splash();
  737. const String splash_png_path = base_path + ".png";
  738. if (splash->save_png(splash_png_path) != OK) {
  739. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  740. return ERR_FILE_CANT_WRITE;
  741. }
  742. // Save a favicon that can be accessed without waiting for the project to finish loading.
  743. // This way, the favicon can be displayed immediately when loading the page.
  744. if (export_icon) {
  745. Ref<Image> favicon = _get_project_icon();
  746. const String favicon_png_path = base_path + ".icon.png";
  747. if (favicon->save_png(favicon_png_path) != OK) {
  748. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  749. return ERR_FILE_CANT_WRITE;
  750. }
  751. favicon->resize(180, 180);
  752. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  753. if (favicon->save_png(apple_icon_png_path) != OK) {
  754. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + apple_icon_png_path);
  755. return ERR_FILE_CANT_WRITE;
  756. }
  757. }
  758. // Generate the PWA worker and manifest
  759. if (pwa) {
  760. err = _build_pwa(p_preset, p_path, shared_objects);
  761. if (err != OK) {
  762. return err;
  763. }
  764. }
  765. return OK;
  766. }
  767. bool EditorExportPlatformJavaScript::poll_export() {
  768. Ref<EditorExportPreset> preset;
  769. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  770. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  771. if (ep->is_runnable() && ep->get_platform() == this) {
  772. preset = ep;
  773. break;
  774. }
  775. }
  776. int prev = menu_options;
  777. menu_options = preset.is_valid();
  778. if (server->is_listening()) {
  779. if (menu_options == 0) {
  780. MutexLock lock(server_lock);
  781. server->stop();
  782. } else {
  783. menu_options += 1;
  784. }
  785. }
  786. return menu_options != prev;
  787. }
  788. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  789. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  790. }
  791. int EditorExportPlatformJavaScript::get_options_count() const {
  792. return menu_options;
  793. }
  794. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  795. if (p_option == 1) {
  796. MutexLock lock(server_lock);
  797. server->stop();
  798. return OK;
  799. }
  800. const String dest = EditorSettings::get_singleton()->get_cache_dir().plus_file("web");
  801. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  802. if (!da->dir_exists(dest)) {
  803. Error err = da->make_dir_recursive(dest);
  804. if (err != OK) {
  805. EditorNode::get_singleton()->show_warning(TTR("Could not create HTTP server directory:") + "\n" + dest);
  806. return err;
  807. }
  808. }
  809. const String basepath = dest.plus_file("tmp_js_export");
  810. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  811. if (err != OK) {
  812. // Export generates several files, clean them up on failure.
  813. DirAccess::remove_file_or_error(basepath + ".html");
  814. DirAccess::remove_file_or_error(basepath + ".offline.html");
  815. DirAccess::remove_file_or_error(basepath + ".js");
  816. DirAccess::remove_file_or_error(basepath + ".worker.js");
  817. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  818. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  819. DirAccess::remove_file_or_error(basepath + ".pck");
  820. DirAccess::remove_file_or_error(basepath + ".png");
  821. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  822. DirAccess::remove_file_or_error(basepath + ".wasm");
  823. DirAccess::remove_file_or_error(basepath + ".icon.png");
  824. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  825. return err;
  826. }
  827. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  828. // Resolve host if needed.
  829. const String bind_host = EDITOR_GET("export/web/http_host");
  830. IP_Address bind_ip;
  831. if (bind_host.is_valid_ip_address()) {
  832. bind_ip = bind_host;
  833. } else {
  834. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  835. }
  836. 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'.");
  837. const bool use_ssl = EDITOR_GET("export/web/use_ssl");
  838. const String ssl_key = EDITOR_GET("export/web/ssl_key");
  839. const String ssl_cert = EDITOR_GET("export/web/ssl_certificate");
  840. // Restart server.
  841. {
  842. MutexLock lock(server_lock);
  843. server->stop();
  844. err = server->listen(bind_port, bind_ip, use_ssl, ssl_key, ssl_cert);
  845. }
  846. if (err != OK) {
  847. EditorNode::get_singleton()->show_warning(TTR("Error starting HTTP server:") + "\n" + itos(err));
  848. return err;
  849. }
  850. OS::get_singleton()->shell_open(String((use_ssl ? "https://" : "http://") + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  851. // FIXME: Find out how to clean up export files after running the successfully
  852. // exported game. Might not be trivial.
  853. return OK;
  854. }
  855. Ref<Texture> EditorExportPlatformJavaScript::get_run_icon() const {
  856. return run_icon;
  857. }
  858. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  859. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  860. while (!ej->server_quit) {
  861. OS::get_singleton()->delay_usec(1000);
  862. {
  863. MutexLock lock(ej->server_lock);
  864. ej->server->poll();
  865. }
  866. }
  867. }
  868. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  869. server.instance();
  870. server_thread.start(_server_thread_poll, this);
  871. Ref<Image> img = memnew(Image(_javascript_logo));
  872. logo.instance();
  873. logo->create_from_image(img);
  874. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  875. run_icon.instance();
  876. run_icon->create_from_image(img);
  877. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  878. if (theme.is_valid()) {
  879. stop_icon = theme->get_icon("Stop", "EditorIcons");
  880. } else {
  881. stop_icon.instance();
  882. }
  883. }
  884. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  885. server->stop();
  886. server_quit = true;
  887. server_thread.wait_to_finish();
  888. }
  889. void register_javascript_exporter() {
  890. EDITOR_DEF("export/web/http_host", "localhost");
  891. EDITOR_DEF("export/web/http_port", 8060);
  892. EDITOR_DEF("export/web/use_ssl", false);
  893. EDITOR_DEF("export/web/ssl_key", "");
  894. EDITOR_DEF("export/web/ssl_certificate", "");
  895. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1"));
  896. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_key", PROPERTY_HINT_GLOBAL_FILE, "*.key"));
  897. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/ssl_certificate", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem"));
  898. Ref<EditorExportPlatformJavaScript> platform;
  899. platform.instance();
  900. EditorExport::get_singleton()->add_export_platform(platform);
  901. }