export_plugin.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*************************************************************************/
  2. /* export_plugin.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_plugin.h"
  31. Error EditorExportPlatformJavaScript::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) {
  32. FileAccess *src_f = nullptr;
  33. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  34. unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io);
  35. if (!pkg) {
  36. EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + p_template);
  37. return ERR_FILE_NOT_FOUND;
  38. }
  39. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  40. EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + p_template);
  41. unzClose(pkg);
  42. return ERR_FILE_CORRUPT;
  43. }
  44. do {
  45. //get filename
  46. unz_file_info info;
  47. char fname[16384];
  48. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  49. String file = String::utf8(fname);
  50. // Skip service worker and offline page if not exporting pwa.
  51. if (!pwa && (file == "godot.service.worker.js" || file == "godot.offline.html")) {
  52. continue;
  53. }
  54. Vector<uint8_t> data;
  55. data.resize(info.uncompressed_size);
  56. //read
  57. unzOpenCurrentFile(pkg);
  58. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  59. unzCloseCurrentFile(pkg);
  60. //write
  61. String dst = p_dir.plus_file(file.replace("godot", p_name));
  62. FileAccess *f = FileAccess::open(dst, FileAccess::WRITE);
  63. if (!f) {
  64. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst);
  65. unzClose(pkg);
  66. return ERR_FILE_CANT_WRITE;
  67. }
  68. f->store_buffer(data.ptr(), data.size());
  69. memdelete(f);
  70. } while (unzGoToNextFile(pkg) == UNZ_OK);
  71. unzClose(pkg);
  72. return OK;
  73. }
  74. Error EditorExportPlatformJavaScript::_write_or_error(const uint8_t *p_content, int p_size, String p_path) {
  75. FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
  76. if (!f) {
  77. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path);
  78. return ERR_FILE_CANT_WRITE;
  79. }
  80. f->store_buffer(p_content, p_size);
  81. memdelete(f);
  82. return OK;
  83. }
  84. void EditorExportPlatformJavaScript::_replace_strings(Map<String, String> p_replaces, Vector<uint8_t> &r_template) {
  85. String str_template = String::utf8(reinterpret_cast<const char *>(r_template.ptr()), r_template.size());
  86. String out;
  87. Vector<String> lines = str_template.split("\n");
  88. for (int i = 0; i < lines.size(); i++) {
  89. String current_line = lines[i];
  90. for (const KeyValue<String, String> &E : p_replaces) {
  91. current_line = current_line.replace(E.key, E.value);
  92. }
  93. out += current_line + "\n";
  94. }
  95. CharString cs = out.utf8();
  96. r_template.resize(cs.length());
  97. for (int i = 0; i < cs.length(); i++) {
  98. r_template.write[i] = cs[i];
  99. }
  100. }
  101. 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) {
  102. // Engine.js config
  103. Dictionary config;
  104. Array libs;
  105. for (int i = 0; i < p_shared_objects.size(); i++) {
  106. libs.push_back(p_shared_objects[i].path.get_file());
  107. }
  108. Vector<String> flags;
  109. gen_export_flags(flags, p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  110. Array args;
  111. for (int i = 0; i < flags.size(); i++) {
  112. args.push_back(flags[i]);
  113. }
  114. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  115. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  116. config["focusCanvas"] = p_preset->get("html/focus_canvas_on_start");
  117. config["gdnativeLibs"] = libs;
  118. config["executable"] = p_name;
  119. config["args"] = args;
  120. config["fileSizes"] = p_file_sizes;
  121. String head_include;
  122. if (p_preset->get("html/export_icon")) {
  123. head_include += "<link id='-gd-engine-icon' rel='icon' type='image/png' href='" + p_name + ".icon.png' />\n";
  124. head_include += "<link rel='apple-touch-icon' href='" + p_name + ".apple-touch-icon.png'/>\n";
  125. }
  126. if (p_preset->get("progressive_web_app/enabled")) {
  127. head_include += "<link rel='manifest' href='" + p_name + ".manifest.json'>\n";
  128. config["serviceWorker"] = p_name + ".service.worker.js";
  129. }
  130. // Replaces HTML string
  131. const String str_config = Variant(config).to_json_string();
  132. const String custom_head_include = p_preset->get("html/head_include");
  133. Map<String, String> replaces;
  134. replaces["$GODOT_URL"] = p_name + ".js";
  135. replaces["$GODOT_PROJECT_NAME"] = ProjectSettings::get_singleton()->get_setting("application/config/name");
  136. replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include;
  137. replaces["$GODOT_CONFIG"] = str_config;
  138. _replace_strings(replaces, p_html);
  139. }
  140. Error EditorExportPlatformJavaScript::_add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr) {
  141. const String name = p_path.get_file().get_basename();
  142. const String icon_name = vformat("%s.%dx%d.png", name, p_size, p_size);
  143. const String icon_dest = p_path.get_base_dir().plus_file(icon_name);
  144. Ref<Image> icon;
  145. if (!p_icon.is_empty()) {
  146. icon.instantiate();
  147. const Error err = ImageLoader::load_image(p_icon, icon);
  148. if (err != OK) {
  149. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + p_icon);
  150. return err;
  151. }
  152. if (icon->get_width() != p_size || icon->get_height() != p_size) {
  153. icon->resize(p_size, p_size);
  154. }
  155. } else {
  156. icon = _get_project_icon();
  157. icon->resize(p_size, p_size);
  158. }
  159. const Error err = icon->save_png(icon_dest);
  160. if (err != OK) {
  161. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + icon_dest);
  162. return err;
  163. }
  164. Dictionary icon_dict;
  165. icon_dict["sizes"] = vformat("%dx%d", p_size, p_size);
  166. icon_dict["type"] = "image/png";
  167. icon_dict["src"] = icon_name;
  168. r_arr.push_back(icon_dict);
  169. return err;
  170. }
  171. Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
  172. String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
  173. if (proj_name.is_empty()) {
  174. proj_name = "Godot Game";
  175. }
  176. // Service worker
  177. const String dir = p_path.get_base_dir();
  178. const String name = p_path.get_file().get_basename();
  179. const ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  180. Map<String, String> replaces;
  181. replaces["@GODOT_VERSION@"] = String::num_int64(OS::get_singleton()->get_unix_time()) + "|" + String::num_int64(OS::get_singleton()->get_ticks_usec());
  182. replaces["@GODOT_NAME@"] = proj_name.substr(0, 16);
  183. replaces["@GODOT_OFFLINE_PAGE@"] = name + ".offline.html";
  184. // Files cached during worker install.
  185. Array cache_files;
  186. cache_files.push_back(name + ".html");
  187. cache_files.push_back(name + ".js");
  188. cache_files.push_back(name + ".offline.html");
  189. if (p_preset->get("html/export_icon")) {
  190. cache_files.push_back(name + ".icon.png");
  191. cache_files.push_back(name + ".apple-touch-icon.png");
  192. }
  193. if (mode == EXPORT_MODE_THREADS) {
  194. cache_files.push_back(name + ".worker.js");
  195. cache_files.push_back(name + ".audio.worklet.js");
  196. }
  197. replaces["@GODOT_CACHE@"] = Variant(cache_files).to_json_string();
  198. // Heavy files that are cached on demand.
  199. Array opt_cache_files;
  200. opt_cache_files.push_back(name + ".wasm");
  201. opt_cache_files.push_back(name + ".pck");
  202. if (mode == EXPORT_MODE_GDNATIVE) {
  203. opt_cache_files.push_back(name + ".side.wasm");
  204. for (int i = 0; i < p_shared_objects.size(); i++) {
  205. opt_cache_files.push_back(p_shared_objects[i].path.get_file());
  206. }
  207. }
  208. replaces["@GODOT_OPT_CACHE@"] = Variant(opt_cache_files).to_json_string();
  209. const String sw_path = dir.plus_file(name + ".service.worker.js");
  210. Vector<uint8_t> sw;
  211. {
  212. FileAccess *f = FileAccess::open(sw_path, FileAccess::READ);
  213. if (!f) {
  214. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + sw_path);
  215. return ERR_FILE_CANT_READ;
  216. }
  217. sw.resize(f->get_length());
  218. f->get_buffer(sw.ptrw(), sw.size());
  219. memdelete(f);
  220. f = nullptr;
  221. }
  222. _replace_strings(replaces, sw);
  223. Error err = _write_or_error(sw.ptr(), sw.size(), dir.plus_file(name + ".service.worker.js"));
  224. if (err != OK) {
  225. return err;
  226. }
  227. // Custom offline page
  228. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  229. if (!offline_page.is_empty()) {
  230. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  231. const String offline_dest = dir.plus_file(name + ".offline.html");
  232. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  233. if (err != OK) {
  234. EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + offline_dest);
  235. return err;
  236. }
  237. }
  238. // Manifest
  239. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  240. const char *orientations[3] = { "any", "landscape", "portrait" };
  241. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  242. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  243. Dictionary manifest;
  244. manifest["name"] = proj_name;
  245. manifest["start_url"] = "./" + name + ".html";
  246. manifest["display"] = String::utf8(modes[display]);
  247. manifest["orientation"] = String::utf8(orientations[orientation]);
  248. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  249. Array icons_arr;
  250. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  251. err = _add_manifest_icon(p_path, icon144_path, 144, icons_arr);
  252. if (err != OK) {
  253. return err;
  254. }
  255. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  256. err = _add_manifest_icon(p_path, icon180_path, 180, icons_arr);
  257. if (err != OK) {
  258. return err;
  259. }
  260. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  261. err = _add_manifest_icon(p_path, icon512_path, 512, icons_arr);
  262. if (err != OK) {
  263. return err;
  264. }
  265. manifest["icons"] = icons_arr;
  266. CharString cs = Variant(manifest).to_json_string().utf8();
  267. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.plus_file(name + ".manifest.json"));
  268. if (err != OK) {
  269. return err;
  270. }
  271. return OK;
  272. }
  273. void EditorExportPlatformJavaScript::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  274. if (p_preset->get("vram_texture_compression/for_desktop")) {
  275. r_features->push_back("s3tc");
  276. }
  277. if (p_preset->get("vram_texture_compression/for_mobile")) {
  278. String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name");
  279. if (driver == "opengl3") {
  280. r_features->push_back("etc");
  281. } else if (driver == "vulkan") {
  282. // FIXME: Review if this is correct.
  283. r_features->push_back("etc2");
  284. }
  285. }
  286. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  287. if (mode == EXPORT_MODE_THREADS) {
  288. r_features->push_back("threads");
  289. } else if (mode == EXPORT_MODE_GDNATIVE) {
  290. r_features->push_back("wasm32");
  291. }
  292. }
  293. void EditorExportPlatformJavaScript::get_export_options(List<ExportOption> *r_options) {
  294. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  295. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  296. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type.
  297. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  298. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  299. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  300. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  301. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  302. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  303. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/focus_canvas_on_start"), true));
  304. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  305. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  306. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  307. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal UI,Browser"), 1));
  308. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  309. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  310. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  311. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  312. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  313. }
  314. String EditorExportPlatformJavaScript::get_name() const {
  315. return "HTML5";
  316. }
  317. String EditorExportPlatformJavaScript::get_os_name() const {
  318. return "HTML5";
  319. }
  320. Ref<Texture2D> EditorExportPlatformJavaScript::get_logo() const {
  321. return logo;
  322. }
  323. bool EditorExportPlatformJavaScript::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  324. String err;
  325. bool valid = false;
  326. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  327. // Look for export templates (first official, and if defined custom templates).
  328. bool dvalid = exists_export_template(_get_template_name(mode, true), &err);
  329. bool rvalid = exists_export_template(_get_template_name(mode, false), &err);
  330. if (p_preset->get("custom_template/debug") != "") {
  331. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  332. if (!dvalid) {
  333. err += TTR("Custom debug template not found.") + "\n";
  334. }
  335. }
  336. if (p_preset->get("custom_template/release") != "") {
  337. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  338. if (!rvalid) {
  339. err += TTR("Custom release template not found.") + "\n";
  340. }
  341. }
  342. valid = dvalid || rvalid;
  343. r_missing_templates = !valid;
  344. // Validate the rest of the configuration.
  345. if (p_preset->get("vram_texture_compression/for_mobile")) {
  346. String etc_error = test_etc2();
  347. if (!etc_error.is_empty()) {
  348. valid = false;
  349. err += etc_error;
  350. }
  351. }
  352. if (!err.is_empty()) {
  353. r_error = err;
  354. }
  355. return valid;
  356. }
  357. List<String> EditorExportPlatformJavaScript::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  358. List<String> list;
  359. list.push_back("html");
  360. return list;
  361. }
  362. Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  363. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  364. const String custom_debug = p_preset->get("custom_template/debug");
  365. const String custom_release = p_preset->get("custom_template/release");
  366. const String custom_html = p_preset->get("html/custom_html_shell");
  367. const bool export_icon = p_preset->get("html/export_icon");
  368. const bool pwa = p_preset->get("progressive_web_app/enabled");
  369. const String base_dir = p_path.get_base_dir();
  370. const String base_path = p_path.get_basename();
  371. const String base_name = p_path.get_file().get_basename();
  372. // Find the correct template
  373. String template_path = p_debug ? custom_debug : custom_release;
  374. template_path = template_path.strip_edges();
  375. if (template_path.is_empty()) {
  376. ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
  377. template_path = find_export_template(_get_template_name(mode, p_debug));
  378. }
  379. if (!DirAccess::exists(base_dir)) {
  380. return ERR_FILE_BAD_PATH;
  381. }
  382. if (!template_path.is_empty() && !FileAccess::exists(template_path)) {
  383. EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path);
  384. return ERR_FILE_NOT_FOUND;
  385. }
  386. // Export pck and shared objects
  387. Vector<SharedObject> shared_objects;
  388. String pck_path = base_path + ".pck";
  389. Error error = save_pack(p_preset, pck_path, &shared_objects);
  390. if (error != OK) {
  391. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path);
  392. return error;
  393. }
  394. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  395. for (int i = 0; i < shared_objects.size(); i++) {
  396. String dst = base_dir.plus_file(shared_objects[i].path.get_file());
  397. error = da->copy(shared_objects[i].path, dst);
  398. if (error != OK) {
  399. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file());
  400. memdelete(da);
  401. return error;
  402. }
  403. }
  404. memdelete(da);
  405. da = nullptr;
  406. // Extract templates.
  407. error = _extract_template(template_path, base_dir, base_name, pwa);
  408. if (error) {
  409. return error;
  410. }
  411. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  412. Dictionary file_sizes;
  413. FileAccess *f = nullptr;
  414. f = FileAccess::open(pck_path, FileAccess::READ);
  415. if (f) {
  416. file_sizes[pck_path.get_file()] = (uint64_t)f->get_length();
  417. memdelete(f);
  418. f = nullptr;
  419. }
  420. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  421. if (f) {
  422. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length();
  423. memdelete(f);
  424. f = nullptr;
  425. }
  426. // Read the HTML shell file (custom or from template).
  427. const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html;
  428. Vector<uint8_t> html;
  429. f = FileAccess::open(html_path, FileAccess::READ);
  430. if (!f) {
  431. EditorNode::get_singleton()->show_warning(TTR("Could not read HTML shell:") + "\n" + html_path);
  432. return ERR_FILE_CANT_READ;
  433. }
  434. html.resize(f->get_length());
  435. f->get_buffer(html.ptrw(), html.size());
  436. memdelete(f);
  437. f = nullptr;
  438. // Generate HTML file with replaced strings.
  439. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  440. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  441. if (err != OK) {
  442. return err;
  443. }
  444. html.resize(0);
  445. // Export splash (why?)
  446. Ref<Image> splash = _get_project_splash();
  447. const String splash_png_path = base_path + ".png";
  448. if (splash->save_png(splash_png_path) != OK) {
  449. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path);
  450. return ERR_FILE_CANT_WRITE;
  451. }
  452. // Save a favicon that can be accessed without waiting for the project to finish loading.
  453. // This way, the favicon can be displayed immediately when loading the page.
  454. if (export_icon) {
  455. Ref<Image> favicon = _get_project_icon();
  456. const String favicon_png_path = base_path + ".icon.png";
  457. if (favicon->save_png(favicon_png_path) != OK) {
  458. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path);
  459. return ERR_FILE_CANT_WRITE;
  460. }
  461. favicon->resize(180, 180);
  462. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  463. if (favicon->save_png(apple_icon_png_path) != OK) {
  464. EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + apple_icon_png_path);
  465. return ERR_FILE_CANT_WRITE;
  466. }
  467. }
  468. // Generate the PWA worker and manifest
  469. if (pwa) {
  470. err = _build_pwa(p_preset, p_path, shared_objects);
  471. if (err != OK) {
  472. return err;
  473. }
  474. }
  475. return OK;
  476. }
  477. bool EditorExportPlatformJavaScript::poll_export() {
  478. Ref<EditorExportPreset> preset;
  479. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  480. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  481. if (ep->is_runnable() && ep->get_platform() == this) {
  482. preset = ep;
  483. break;
  484. }
  485. }
  486. int prev = menu_options;
  487. menu_options = preset.is_valid();
  488. if (server->is_listening()) {
  489. if (menu_options == 0) {
  490. MutexLock lock(server_lock);
  491. server->stop();
  492. } else {
  493. menu_options += 1;
  494. }
  495. }
  496. return menu_options != prev;
  497. }
  498. Ref<ImageTexture> EditorExportPlatformJavaScript::get_option_icon(int p_index) const {
  499. return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index);
  500. }
  501. int EditorExportPlatformJavaScript::get_options_count() const {
  502. return menu_options;
  503. }
  504. Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_preset, int p_option, int p_debug_flags) {
  505. if (p_option == 1) {
  506. MutexLock lock(server_lock);
  507. server->stop();
  508. return OK;
  509. }
  510. const String dest = EditorPaths::get_singleton()->get_cache_dir().plus_file("web");
  511. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  512. if (!da->dir_exists(dest)) {
  513. Error err = da->make_dir_recursive(dest);
  514. if (err != OK) {
  515. EditorNode::get_singleton()->show_warning(TTR("Could not create HTTP server directory:") + "\n" + dest);
  516. return err;
  517. }
  518. }
  519. const String basepath = dest.plus_file("tmp_js_export");
  520. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  521. if (err != OK) {
  522. // Export generates several files, clean them up on failure.
  523. DirAccess::remove_file_or_error(basepath + ".html");
  524. DirAccess::remove_file_or_error(basepath + ".offline.html");
  525. DirAccess::remove_file_or_error(basepath + ".js");
  526. DirAccess::remove_file_or_error(basepath + ".worker.js");
  527. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  528. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  529. DirAccess::remove_file_or_error(basepath + ".pck");
  530. DirAccess::remove_file_or_error(basepath + ".png");
  531. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  532. DirAccess::remove_file_or_error(basepath + ".wasm");
  533. DirAccess::remove_file_or_error(basepath + ".icon.png");
  534. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  535. return err;
  536. }
  537. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  538. // Resolve host if needed.
  539. const String bind_host = EDITOR_GET("export/web/http_host");
  540. IPAddress bind_ip;
  541. if (bind_host.is_valid_ip_address()) {
  542. bind_ip = bind_host;
  543. } else {
  544. bind_ip = IP::get_singleton()->resolve_hostname(bind_host);
  545. }
  546. 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'.");
  547. const bool use_ssl = EDITOR_GET("export/web/use_ssl");
  548. const String ssl_key = EDITOR_GET("export/web/ssl_key");
  549. const String ssl_cert = EDITOR_GET("export/web/ssl_certificate");
  550. // Restart server.
  551. {
  552. MutexLock lock(server_lock);
  553. server->stop();
  554. err = server->listen(bind_port, bind_ip, use_ssl, ssl_key, ssl_cert);
  555. }
  556. if (err != OK) {
  557. EditorNode::get_singleton()->show_warning(TTR("Error starting HTTP server:") + "\n" + itos(err));
  558. return err;
  559. }
  560. OS::get_singleton()->shell_open(String((use_ssl ? "https://" : "http://") + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html"));
  561. // FIXME: Find out how to clean up export files after running the successfully
  562. // exported game. Might not be trivial.
  563. return OK;
  564. }
  565. Ref<Texture2D> EditorExportPlatformJavaScript::get_run_icon() const {
  566. return run_icon;
  567. }
  568. void EditorExportPlatformJavaScript::_server_thread_poll(void *data) {
  569. EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data;
  570. while (!ej->server_quit) {
  571. OS::get_singleton()->delay_usec(1000);
  572. {
  573. MutexLock lock(ej->server_lock);
  574. ej->server->poll();
  575. }
  576. }
  577. }
  578. EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() {
  579. server.instantiate();
  580. server_thread.start(_server_thread_poll, this);
  581. Ref<Image> img = memnew(Image(_javascript_logo));
  582. logo.instantiate();
  583. logo->create_from_image(img);
  584. img = Ref<Image>(memnew(Image(_javascript_run_icon)));
  585. run_icon.instantiate();
  586. run_icon->create_from_image(img);
  587. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  588. if (theme.is_valid()) {
  589. stop_icon = theme->get_icon(SNAME("Stop"), SNAME("EditorIcons"));
  590. } else {
  591. stop_icon.instantiate();
  592. }
  593. }
  594. EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
  595. server->stop();
  596. server_quit = true;
  597. server_thread.wait_to_finish();
  598. }