export_plugin.cpp 27 KB

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