export_plugin.cpp 26 KB

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