export_plugin.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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_settings.h"
  35. #include "editor/editor_string_names.h"
  36. #include "editor/export/editor_export.h"
  37. #include "editor/import/resource_importer_texture_settings.h"
  38. #include "editor/themes/editor_scale.h"
  39. #include "scene/resources/image_texture.h"
  40. #include "modules/modules_enabled.gen.h" // For mono and svg.
  41. #ifdef MODULE_SVG_ENABLED
  42. #include "modules/svg/image_loader_svg.h"
  43. #endif
  44. Error EditorExportPlatformWeb::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) {
  45. Ref<FileAccess> io_fa;
  46. zlib_filefunc_def io = zipio_create_io(&io_fa);
  47. unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io);
  48. if (!pkg) {
  49. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Could not open template for export: \"%s\"."), p_template));
  50. return ERR_FILE_NOT_FOUND;
  51. }
  52. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  53. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Invalid export template: \"%s\"."), p_template));
  54. unzClose(pkg);
  55. return ERR_FILE_CORRUPT;
  56. }
  57. do {
  58. //get filename
  59. unz_file_info info;
  60. char fname[16384];
  61. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  62. String file = String::utf8(fname);
  63. // Skip folders.
  64. if (file.ends_with("/")) {
  65. continue;
  66. }
  67. // Skip service worker and offline page if not exporting pwa.
  68. if (!pwa && (file == "godot.service.worker.js" || file == "godot.offline.html")) {
  69. continue;
  70. }
  71. Vector<uint8_t> data;
  72. data.resize(info.uncompressed_size);
  73. //read
  74. unzOpenCurrentFile(pkg);
  75. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  76. unzCloseCurrentFile(pkg);
  77. //write
  78. String dst = p_dir.path_join(file.replace("godot", p_name));
  79. Ref<FileAccess> f = FileAccess::open(dst, FileAccess::WRITE);
  80. if (f.is_null()) {
  81. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Could not write file: \"%s\"."), dst));
  82. unzClose(pkg);
  83. return ERR_FILE_CANT_WRITE;
  84. }
  85. f->store_buffer(data.ptr(), data.size());
  86. } while (unzGoToNextFile(pkg) == UNZ_OK);
  87. unzClose(pkg);
  88. return OK;
  89. }
  90. Error EditorExportPlatformWeb::_write_or_error(const uint8_t *p_content, int p_size, String p_path) {
  91. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
  92. if (f.is_null()) {
  93. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), p_path));
  94. return ERR_FILE_CANT_WRITE;
  95. }
  96. f->store_buffer(p_content, p_size);
  97. return OK;
  98. }
  99. void EditorExportPlatformWeb::_replace_strings(const HashMap<String, String> &p_replaces, Vector<uint8_t> &r_template) {
  100. String str_template = String::utf8(reinterpret_cast<const char *>(r_template.ptr()), r_template.size());
  101. String out;
  102. Vector<String> lines = str_template.split("\n");
  103. for (int i = 0; i < lines.size(); i++) {
  104. String current_line = lines[i];
  105. for (const KeyValue<String, String> &E : p_replaces) {
  106. current_line = current_line.replace(E.key, E.value);
  107. }
  108. out += current_line + "\n";
  109. }
  110. CharString cs = out.utf8();
  111. r_template.resize(cs.length());
  112. for (int i = 0; i < cs.length(); i++) {
  113. r_template.write[i] = cs[i];
  114. }
  115. }
  116. void EditorExportPlatformWeb::_fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, BitField<EditorExportPlatform::DebugFlags> p_flags, const Vector<SharedObject> p_shared_objects, const Dictionary &p_file_sizes) {
  117. // Engine.js config
  118. Dictionary config;
  119. Array libs;
  120. for (int i = 0; i < p_shared_objects.size(); i++) {
  121. libs.push_back(p_shared_objects[i].path.get_file());
  122. }
  123. Vector<String> flags = gen_export_flags(p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  124. Array args;
  125. for (int i = 0; i < flags.size(); i++) {
  126. args.push_back(flags[i]);
  127. }
  128. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  129. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  130. config["focusCanvas"] = p_preset->get("html/focus_canvas_on_start");
  131. config["gdextensionLibs"] = libs;
  132. config["executable"] = p_name;
  133. config["args"] = args;
  134. config["fileSizes"] = p_file_sizes;
  135. config["ensureCrossOriginIsolationHeaders"] = (bool)p_preset->get("progressive_web_app/ensure_cross_origin_isolation_headers");
  136. String head_include;
  137. if (p_preset->get("html/export_icon")) {
  138. head_include += "<link id=\"-gd-engine-icon\" rel=\"icon\" type=\"image/png\" href=\"" + p_name + ".icon.png\" />\n";
  139. head_include += "<link rel=\"apple-touch-icon\" href=\"" + p_name + ".apple-touch-icon.png\"/>\n";
  140. }
  141. if (p_preset->get("progressive_web_app/enabled")) {
  142. head_include += "<link rel=\"manifest\" href=\"" + p_name + ".manifest.json\">\n";
  143. config["serviceWorker"] = p_name + ".service.worker.js";
  144. }
  145. // Replaces HTML string
  146. const String str_config = Variant(config).to_json_string();
  147. const String custom_head_include = p_preset->get("html/head_include");
  148. HashMap<String, String> replaces;
  149. replaces["$GODOT_URL"] = p_name + ".js";
  150. replaces["$GODOT_PROJECT_NAME"] = GLOBAL_GET("application/config/name");
  151. replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include;
  152. replaces["$GODOT_CONFIG"] = str_config;
  153. replaces["$GODOT_SPLASH_COLOR"] = "#" + Color(GLOBAL_GET("application/boot_splash/bg_color")).to_html(false);
  154. replaces["$GODOT_SPLASH"] = p_name + ".png";
  155. if (p_preset->get("variant/thread_support")) {
  156. replaces["$GODOT_THREADS_ENABLED"] = "true";
  157. } else {
  158. replaces["$GODOT_THREADS_ENABLED"] = "false";
  159. }
  160. _replace_strings(replaces, p_html);
  161. }
  162. Error EditorExportPlatformWeb::_add_manifest_icon(const String &p_path, const String &p_icon, int p_size, Array &r_arr) {
  163. const String name = p_path.get_file().get_basename();
  164. const String icon_name = vformat("%s.%dx%d.png", name, p_size, p_size);
  165. const String icon_dest = p_path.get_base_dir().path_join(icon_name);
  166. Ref<Image> icon;
  167. if (!p_icon.is_empty()) {
  168. icon.instantiate();
  169. const Error err = ImageLoader::load_image(p_icon, icon);
  170. if (err != OK) {
  171. add_message(EXPORT_MESSAGE_ERROR, TTR("Icon Creation"), vformat(TTR("Could not read file: \"%s\"."), p_icon));
  172. return err;
  173. }
  174. if (icon->get_width() != p_size || icon->get_height() != p_size) {
  175. icon->resize(p_size, p_size);
  176. }
  177. } else {
  178. icon = _get_project_icon();
  179. icon->resize(p_size, p_size);
  180. }
  181. const Error err = icon->save_png(icon_dest);
  182. if (err != OK) {
  183. add_message(EXPORT_MESSAGE_ERROR, TTR("Icon Creation"), vformat(TTR("Could not write file: \"%s\"."), icon_dest));
  184. return err;
  185. }
  186. Dictionary icon_dict;
  187. icon_dict["sizes"] = vformat("%dx%d", p_size, p_size);
  188. icon_dict["type"] = "image/png";
  189. icon_dict["src"] = icon_name;
  190. r_arr.push_back(icon_dict);
  191. return err;
  192. }
  193. Error EditorExportPlatformWeb::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
  194. String proj_name = GLOBAL_GET("application/config/name");
  195. if (proj_name.is_empty()) {
  196. proj_name = "Godot Game";
  197. }
  198. // Service worker
  199. const String dir = p_path.get_base_dir();
  200. const String name = p_path.get_file().get_basename();
  201. bool extensions = (bool)p_preset->get("variant/extensions_support");
  202. bool ensure_crossorigin_isolation_headers = (bool)p_preset->get("progressive_web_app/ensure_cross_origin_isolation_headers");
  203. HashMap<String, String> replaces;
  204. replaces["___GODOT_VERSION___"] = String::num_int64(OS::get_singleton()->get_unix_time()) + "|" + String::num_int64(OS::get_singleton()->get_ticks_usec());
  205. replaces["___GODOT_NAME___"] = proj_name.substr(0, 16);
  206. replaces["___GODOT_OFFLINE_PAGE___"] = name + ".offline.html";
  207. replaces["___GODOT_ENSURE_CROSSORIGIN_ISOLATION_HEADERS___"] = ensure_crossorigin_isolation_headers ? "true" : "false";
  208. // Files cached during worker install.
  209. Array cache_files;
  210. cache_files.push_back(name + ".html");
  211. cache_files.push_back(name + ".js");
  212. cache_files.push_back(name + ".offline.html");
  213. if (p_preset->get("html/export_icon")) {
  214. cache_files.push_back(name + ".icon.png");
  215. cache_files.push_back(name + ".apple-touch-icon.png");
  216. }
  217. cache_files.push_back(name + ".audio.worklet.js");
  218. cache_files.push_back(name + ".audio.position.worklet.js");
  219. replaces["___GODOT_CACHE___"] = Variant(cache_files).to_json_string();
  220. // Heavy files that are cached on demand.
  221. Array opt_cache_files;
  222. opt_cache_files.push_back(name + ".wasm");
  223. opt_cache_files.push_back(name + ".pck");
  224. if (extensions) {
  225. opt_cache_files.push_back(name + ".side.wasm");
  226. for (int i = 0; i < p_shared_objects.size(); i++) {
  227. opt_cache_files.push_back(p_shared_objects[i].path.get_file());
  228. }
  229. }
  230. replaces["___GODOT_OPT_CACHE___"] = Variant(opt_cache_files).to_json_string();
  231. const String sw_path = dir.path_join(name + ".service.worker.js");
  232. Vector<uint8_t> sw;
  233. {
  234. Ref<FileAccess> f = FileAccess::open(sw_path, FileAccess::READ);
  235. if (f.is_null()) {
  236. add_message(EXPORT_MESSAGE_ERROR, TTR("PWA"), vformat(TTR("Could not read file: \"%s\"."), sw_path));
  237. return ERR_FILE_CANT_READ;
  238. }
  239. sw.resize(f->get_length());
  240. f->get_buffer(sw.ptrw(), sw.size());
  241. }
  242. _replace_strings(replaces, sw);
  243. Error err = _write_or_error(sw.ptr(), sw.size(), dir.path_join(name + ".service.worker.js"));
  244. if (err != OK) {
  245. // Message is supplied by the subroutine method.
  246. return err;
  247. }
  248. // Custom offline page
  249. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  250. if (!offline_page.is_empty()) {
  251. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  252. const String offline_dest = dir.path_join(name + ".offline.html");
  253. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  254. if (err != OK) {
  255. add_message(EXPORT_MESSAGE_ERROR, TTR("PWA"), vformat(TTR("Could not read file: \"%s\"."), offline_dest));
  256. return err;
  257. }
  258. }
  259. // Manifest
  260. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  261. const char *orientations[3] = { "any", "landscape", "portrait" };
  262. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  263. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  264. Dictionary manifest;
  265. manifest["name"] = proj_name;
  266. manifest["start_url"] = "./" + name + ".html";
  267. manifest["display"] = String::utf8(modes[display]);
  268. manifest["orientation"] = String::utf8(orientations[orientation]);
  269. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  270. Array icons_arr;
  271. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  272. err = _add_manifest_icon(p_path, icon144_path, 144, icons_arr);
  273. if (err != OK) {
  274. // Message is supplied by the subroutine method.
  275. return err;
  276. }
  277. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  278. err = _add_manifest_icon(p_path, icon180_path, 180, icons_arr);
  279. if (err != OK) {
  280. // Message is supplied by the subroutine method.
  281. return err;
  282. }
  283. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  284. err = _add_manifest_icon(p_path, icon512_path, 512, icons_arr);
  285. if (err != OK) {
  286. // Message is supplied by the subroutine method.
  287. return err;
  288. }
  289. manifest["icons"] = icons_arr;
  290. CharString cs = Variant(manifest).to_json_string().utf8();
  291. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.path_join(name + ".manifest.json"));
  292. if (err != OK) {
  293. // Message is supplied by the subroutine method.
  294. return err;
  295. }
  296. return OK;
  297. }
  298. void EditorExportPlatformWeb::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const {
  299. if (p_preset->get("vram_texture_compression/for_desktop")) {
  300. r_features->push_back("s3tc");
  301. r_features->push_back("bptc");
  302. }
  303. if (p_preset->get("vram_texture_compression/for_mobile")) {
  304. r_features->push_back("etc2");
  305. r_features->push_back("astc");
  306. }
  307. if (p_preset->get("variant/thread_support").operator bool()) {
  308. r_features->push_back("threads");
  309. } else {
  310. r_features->push_back("nothreads");
  311. }
  312. r_features->push_back("wasm32");
  313. }
  314. void EditorExportPlatformWeb::get_export_options(List<ExportOption> *r_options) const {
  315. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  316. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  317. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "variant/extensions_support"), false)); // GDExtension support.
  318. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "variant/thread_support"), false)); // Thread support (i.e. run with or without COEP/COOP headers).
  319. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  320. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  321. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  322. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  323. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  324. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  325. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/focus_canvas_on_start"), true));
  326. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  327. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  328. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/ensure_cross_origin_isolation_headers"), true));
  329. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  330. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal UI,Browser"), 1));
  331. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  332. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  333. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  334. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  335. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  336. }
  337. bool EditorExportPlatformWeb::get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option) const {
  338. bool advanced_options_enabled = p_preset->are_advanced_options_enabled();
  339. if (p_option == "custom_template/debug" ||
  340. p_option == "custom_template/release") {
  341. return advanced_options_enabled;
  342. }
  343. return true;
  344. }
  345. String EditorExportPlatformWeb::get_name() const {
  346. return "Web";
  347. }
  348. String EditorExportPlatformWeb::get_os_name() const {
  349. return "Web";
  350. }
  351. Ref<Texture2D> EditorExportPlatformWeb::get_logo() const {
  352. return logo;
  353. }
  354. bool EditorExportPlatformWeb::has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates, bool p_debug) const {
  355. #ifdef MODULE_MONO_ENABLED
  356. // Don't check for additional errors, as this particular error cannot be resolved.
  357. r_error += 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";
  358. r_error += TTR("If this project does not use C#, use a non-C# editor build to export the project.") + "\n";
  359. return false;
  360. #else
  361. String err;
  362. bool valid = false;
  363. bool extensions = (bool)p_preset->get("variant/extensions_support");
  364. bool thread_support = (bool)p_preset->get("variant/thread_support");
  365. // Look for export templates (first official, and if defined custom templates).
  366. bool dvalid = exists_export_template(_get_template_name(extensions, thread_support, true), &err);
  367. bool rvalid = exists_export_template(_get_template_name(extensions, thread_support, false), &err);
  368. if (p_preset->get("custom_template/debug") != "") {
  369. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  370. if (!dvalid) {
  371. err += TTR("Custom debug template not found.") + "\n";
  372. }
  373. }
  374. if (p_preset->get("custom_template/release") != "") {
  375. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  376. if (!rvalid) {
  377. err += TTR("Custom release template not found.") + "\n";
  378. }
  379. }
  380. valid = dvalid || rvalid;
  381. r_missing_templates = !valid;
  382. if (!err.is_empty()) {
  383. r_error = err;
  384. }
  385. return valid;
  386. #endif // !MODULE_MONO_ENABLED
  387. }
  388. bool EditorExportPlatformWeb::has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const {
  389. String err;
  390. bool valid = true;
  391. // Validate the project configuration.
  392. if (p_preset->get("vram_texture_compression/for_mobile")) {
  393. if (!ResourceImporterTextureSettings::should_import_etc2_astc()) {
  394. valid = false;
  395. }
  396. }
  397. if (!err.is_empty()) {
  398. r_error = err;
  399. }
  400. return valid;
  401. }
  402. List<String> EditorExportPlatformWeb::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  403. List<String> list;
  404. list.push_back("html");
  405. return list;
  406. }
  407. Error EditorExportPlatformWeb::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  408. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  409. const String custom_debug = p_preset->get("custom_template/debug");
  410. const String custom_release = p_preset->get("custom_template/release");
  411. const String custom_html = p_preset->get("html/custom_html_shell");
  412. const bool export_icon = p_preset->get("html/export_icon");
  413. const bool pwa = p_preset->get("progressive_web_app/enabled");
  414. const String base_dir = p_path.get_base_dir();
  415. const String base_path = p_path.get_basename();
  416. const String base_name = p_path.get_file().get_basename();
  417. if (!DirAccess::exists(base_dir)) {
  418. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Target folder does not exist or is inaccessible: \"%s\""), base_dir));
  419. return ERR_FILE_BAD_PATH;
  420. }
  421. // Find the correct template
  422. String template_path = p_debug ? custom_debug : custom_release;
  423. template_path = template_path.strip_edges();
  424. if (template_path.is_empty()) {
  425. bool extensions = (bool)p_preset->get("variant/extensions_support");
  426. bool thread_support = (bool)p_preset->get("variant/thread_support");
  427. template_path = find_export_template(_get_template_name(extensions, thread_support, p_debug));
  428. }
  429. if (!template_path.is_empty() && !FileAccess::exists(template_path)) {
  430. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Template file not found: \"%s\"."), template_path));
  431. return ERR_FILE_NOT_FOUND;
  432. }
  433. // Export pck and shared objects
  434. Vector<SharedObject> shared_objects;
  435. String pck_path = base_path + ".pck";
  436. Error error = save_pack(p_preset, p_debug, pck_path, &shared_objects);
  437. if (error != OK) {
  438. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), pck_path));
  439. return error;
  440. }
  441. {
  442. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  443. for (int i = 0; i < shared_objects.size(); i++) {
  444. String dst = base_dir.path_join(shared_objects[i].path.get_file());
  445. error = da->copy(shared_objects[i].path, dst);
  446. if (error != OK) {
  447. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), shared_objects[i].path.get_file()));
  448. return error;
  449. }
  450. }
  451. }
  452. // Extract templates.
  453. error = _extract_template(template_path, base_dir, base_name, pwa);
  454. if (error) {
  455. // Message is supplied by the subroutine method.
  456. return error;
  457. }
  458. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  459. Dictionary file_sizes;
  460. Ref<FileAccess> f = FileAccess::open(pck_path, FileAccess::READ);
  461. if (f.is_valid()) {
  462. file_sizes[pck_path.get_file()] = (uint64_t)f->get_length();
  463. }
  464. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  465. if (f.is_valid()) {
  466. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length();
  467. }
  468. // Read the HTML shell file (custom or from template).
  469. const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html;
  470. Vector<uint8_t> html;
  471. f = FileAccess::open(html_path, FileAccess::READ);
  472. if (f.is_null()) {
  473. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not read HTML shell: \"%s\"."), html_path));
  474. return ERR_FILE_CANT_READ;
  475. }
  476. html.resize(f->get_length());
  477. f->get_buffer(html.ptrw(), html.size());
  478. f.unref(); // close file.
  479. // Generate HTML file with replaced strings.
  480. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  481. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  482. if (err != OK) {
  483. // Message is supplied by the subroutine method.
  484. return err;
  485. }
  486. html.resize(0);
  487. // Export splash (why?)
  488. Ref<Image> splash = _get_project_splash();
  489. const String splash_png_path = base_path + ".png";
  490. if (splash->save_png(splash_png_path) != OK) {
  491. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), splash_png_path));
  492. return ERR_FILE_CANT_WRITE;
  493. }
  494. // Save a favicon that can be accessed without waiting for the project to finish loading.
  495. // This way, the favicon can be displayed immediately when loading the page.
  496. if (export_icon) {
  497. Ref<Image> favicon = _get_project_icon();
  498. const String favicon_png_path = base_path + ".icon.png";
  499. if (favicon->save_png(favicon_png_path) != OK) {
  500. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), favicon_png_path));
  501. return ERR_FILE_CANT_WRITE;
  502. }
  503. favicon->resize(180, 180);
  504. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  505. if (favicon->save_png(apple_icon_png_path) != OK) {
  506. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), apple_icon_png_path));
  507. return ERR_FILE_CANT_WRITE;
  508. }
  509. }
  510. // Generate the PWA worker and manifest
  511. if (pwa) {
  512. err = _build_pwa(p_preset, p_path, shared_objects);
  513. if (err != OK) {
  514. // Message is supplied by the subroutine method.
  515. return err;
  516. }
  517. }
  518. return OK;
  519. }
  520. bool EditorExportPlatformWeb::poll_export() {
  521. Ref<EditorExportPreset> preset;
  522. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  523. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  524. if (ep->is_runnable() && ep->get_platform() == this) {
  525. preset = ep;
  526. break;
  527. }
  528. }
  529. RemoteDebugState prev_remote_debug_state = remote_debug_state;
  530. remote_debug_state = REMOTE_DEBUG_STATE_UNAVAILABLE;
  531. if (preset.is_valid()) {
  532. const bool debug = true;
  533. // Throwaway variables to pass to `can_export`.
  534. String err;
  535. bool missing_templates;
  536. if (can_export(preset, err, missing_templates, debug)) {
  537. if (server->is_listening()) {
  538. remote_debug_state = REMOTE_DEBUG_STATE_SERVING;
  539. } else {
  540. remote_debug_state = REMOTE_DEBUG_STATE_AVAILABLE;
  541. }
  542. }
  543. }
  544. if (remote_debug_state != REMOTE_DEBUG_STATE_SERVING && server->is_listening()) {
  545. server->stop();
  546. }
  547. return remote_debug_state != prev_remote_debug_state;
  548. }
  549. Ref<ImageTexture> EditorExportPlatformWeb::get_option_icon(int p_index) const {
  550. Ref<ImageTexture> play_icon = EditorExportPlatform::get_option_icon(p_index);
  551. switch (remote_debug_state) {
  552. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  553. return nullptr;
  554. } break;
  555. case REMOTE_DEBUG_STATE_AVAILABLE: {
  556. switch (p_index) {
  557. case 0:
  558. case 1:
  559. return play_icon;
  560. default:
  561. ERR_FAIL_V(nullptr);
  562. }
  563. } break;
  564. case REMOTE_DEBUG_STATE_SERVING: {
  565. switch (p_index) {
  566. case 0:
  567. return play_icon;
  568. case 1:
  569. return restart_icon;
  570. case 2:
  571. return stop_icon;
  572. default:
  573. ERR_FAIL_V(nullptr);
  574. }
  575. } break;
  576. }
  577. return nullptr;
  578. }
  579. int EditorExportPlatformWeb::get_options_count() const {
  580. switch (remote_debug_state) {
  581. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  582. return 0;
  583. } break;
  584. case REMOTE_DEBUG_STATE_AVAILABLE: {
  585. return 2;
  586. } break;
  587. case REMOTE_DEBUG_STATE_SERVING: {
  588. return 3;
  589. } break;
  590. }
  591. return 0;
  592. }
  593. String EditorExportPlatformWeb::get_option_label(int p_index) const {
  594. String run_in_browser = TTR("Run in Browser");
  595. String start_http_server = TTR("Start HTTP Server");
  596. String reexport_project = TTR("Re-export Project");
  597. String stop_http_server = TTR("Stop HTTP Server");
  598. switch (remote_debug_state) {
  599. case REMOTE_DEBUG_STATE_UNAVAILABLE:
  600. return "";
  601. case REMOTE_DEBUG_STATE_AVAILABLE: {
  602. switch (p_index) {
  603. case 0:
  604. return run_in_browser;
  605. case 1:
  606. return start_http_server;
  607. default:
  608. ERR_FAIL_V("");
  609. }
  610. } break;
  611. case REMOTE_DEBUG_STATE_SERVING: {
  612. switch (p_index) {
  613. case 0:
  614. return run_in_browser;
  615. case 1:
  616. return reexport_project;
  617. case 2:
  618. return stop_http_server;
  619. default:
  620. ERR_FAIL_V("");
  621. }
  622. } break;
  623. }
  624. return "";
  625. }
  626. String EditorExportPlatformWeb::get_option_tooltip(int p_index) const {
  627. String run_in_browser = TTR("Run exported HTML in the system's default browser.");
  628. String start_http_server = TTR("Start the HTTP server.");
  629. String reexport_project = TTR("Export project again to account for updates.");
  630. String stop_http_server = TTR("Stop the HTTP server.");
  631. switch (remote_debug_state) {
  632. case REMOTE_DEBUG_STATE_UNAVAILABLE:
  633. return "";
  634. case REMOTE_DEBUG_STATE_AVAILABLE: {
  635. switch (p_index) {
  636. case 0:
  637. return run_in_browser;
  638. case 1:
  639. return start_http_server;
  640. default:
  641. ERR_FAIL_V("");
  642. }
  643. } break;
  644. case REMOTE_DEBUG_STATE_SERVING: {
  645. switch (p_index) {
  646. case 0:
  647. return run_in_browser;
  648. case 1:
  649. return reexport_project;
  650. case 2:
  651. return stop_http_server;
  652. default:
  653. ERR_FAIL_V("");
  654. }
  655. } break;
  656. }
  657. return "";
  658. }
  659. Error EditorExportPlatformWeb::run(const Ref<EditorExportPreset> &p_preset, int p_option, BitField<EditorExportPlatform::DebugFlags> p_debug_flags) {
  660. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  661. // Resolve host if needed.
  662. const String bind_host = EDITOR_GET("export/web/http_host");
  663. const bool use_tls = EDITOR_GET("export/web/use_tls");
  664. switch (remote_debug_state) {
  665. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  666. return FAILED;
  667. } break;
  668. case REMOTE_DEBUG_STATE_AVAILABLE: {
  669. switch (p_option) {
  670. // Run in Browser.
  671. case 0: {
  672. Error err = _export_project(p_preset, p_debug_flags);
  673. if (err != OK) {
  674. return err;
  675. }
  676. err = _start_server(bind_host, bind_port, use_tls);
  677. if (err != OK) {
  678. return err;
  679. }
  680. return _launch_browser(bind_host, bind_port, use_tls);
  681. } break;
  682. // Start HTTP Server.
  683. case 1: {
  684. Error err = _export_project(p_preset, p_debug_flags);
  685. if (err != OK) {
  686. return err;
  687. }
  688. return _start_server(bind_host, bind_port, use_tls);
  689. } break;
  690. default: {
  691. ERR_FAIL_V_MSG(FAILED, vformat(R"(Invalid option "%s" for the current state.)", p_option));
  692. }
  693. }
  694. } break;
  695. case REMOTE_DEBUG_STATE_SERVING: {
  696. switch (p_option) {
  697. // Run in Browser.
  698. case 0: {
  699. Error err = _export_project(p_preset, p_debug_flags);
  700. if (err != OK) {
  701. return err;
  702. }
  703. return _launch_browser(bind_host, bind_port, use_tls);
  704. } break;
  705. // Re-export Project.
  706. case 1: {
  707. return _export_project(p_preset, p_debug_flags);
  708. } break;
  709. // Stop HTTP Server.
  710. case 2: {
  711. return _stop_server();
  712. } break;
  713. default: {
  714. ERR_FAIL_V_MSG(FAILED, vformat(R"(Invalid option "%s" for the current state.)", p_option));
  715. }
  716. }
  717. } break;
  718. }
  719. return FAILED;
  720. }
  721. Error EditorExportPlatformWeb::_export_project(const Ref<EditorExportPreset> &p_preset, int p_debug_flags) {
  722. const String dest = EditorPaths::get_singleton()->get_temp_dir().path_join("web");
  723. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  724. if (!da->dir_exists(dest)) {
  725. Error err = da->make_dir_recursive(dest);
  726. if (err != OK) {
  727. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Could not create HTTP server directory: %s."), dest));
  728. return err;
  729. }
  730. }
  731. const String basepath = dest.path_join("tmp_js_export");
  732. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  733. if (err != OK) {
  734. // Export generates several files, clean them up on failure.
  735. DirAccess::remove_file_or_error(basepath + ".html");
  736. DirAccess::remove_file_or_error(basepath + ".offline.html");
  737. DirAccess::remove_file_or_error(basepath + ".js");
  738. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  739. DirAccess::remove_file_or_error(basepath + ".audio.position.worklet.js");
  740. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  741. DirAccess::remove_file_or_error(basepath + ".pck");
  742. DirAccess::remove_file_or_error(basepath + ".png");
  743. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  744. DirAccess::remove_file_or_error(basepath + ".wasm");
  745. DirAccess::remove_file_or_error(basepath + ".icon.png");
  746. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  747. }
  748. return err;
  749. }
  750. Error EditorExportPlatformWeb::_launch_browser(const String &p_bind_host, const uint16_t p_bind_port, const bool p_use_tls) {
  751. OS::get_singleton()->shell_open(String((p_use_tls ? "https://" : "http://") + p_bind_host + ":" + itos(p_bind_port) + "/tmp_js_export.html"));
  752. // FIXME: Find out how to clean up export files after running the successfully
  753. // exported game. Might not be trivial.
  754. return OK;
  755. }
  756. Error EditorExportPlatformWeb::_start_server(const String &p_bind_host, const uint16_t p_bind_port, const bool p_use_tls) {
  757. IPAddress bind_ip;
  758. if (p_bind_host.is_valid_ip_address()) {
  759. bind_ip = p_bind_host;
  760. } else {
  761. bind_ip = IP::get_singleton()->resolve_hostname(p_bind_host);
  762. }
  763. ERR_FAIL_COND_V_MSG(!bind_ip.is_valid(), ERR_INVALID_PARAMETER, "Invalid editor setting 'export/web/http_host': '" + p_bind_host + "'. Try using '127.0.0.1'.");
  764. const String tls_key = EDITOR_GET("export/web/tls_key");
  765. const String tls_cert = EDITOR_GET("export/web/tls_certificate");
  766. // Restart server.
  767. server->stop();
  768. Error err = server->listen(p_bind_port, bind_ip, p_use_tls, tls_key, tls_cert);
  769. if (err != OK) {
  770. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Error starting HTTP server: %d."), err));
  771. }
  772. return err;
  773. }
  774. Error EditorExportPlatformWeb::_stop_server() {
  775. server->stop();
  776. return OK;
  777. }
  778. Ref<Texture2D> EditorExportPlatformWeb::get_run_icon() const {
  779. return run_icon;
  780. }
  781. EditorExportPlatformWeb::EditorExportPlatformWeb() {
  782. if (EditorNode::get_singleton()) {
  783. server.instantiate();
  784. #ifdef MODULE_SVG_ENABLED
  785. Ref<Image> img = memnew(Image);
  786. const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE);
  787. ImageLoaderSVG::create_image_from_string(img, _web_logo_svg, EDSCALE, upsample, false);
  788. logo = ImageTexture::create_from_image(img);
  789. ImageLoaderSVG::create_image_from_string(img, _web_run_icon_svg, EDSCALE, upsample, false);
  790. run_icon = ImageTexture::create_from_image(img);
  791. #endif
  792. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  793. if (theme.is_valid()) {
  794. stop_icon = theme->get_icon(SNAME("Stop"), EditorStringName(EditorIcons));
  795. restart_icon = theme->get_icon(SNAME("Reload"), EditorStringName(EditorIcons));
  796. } else {
  797. stop_icon.instantiate();
  798. restart_icon.instantiate();
  799. }
  800. }
  801. }
  802. EditorExportPlatformWeb::~EditorExportPlatformWeb() {
  803. }