export_plugin.cpp 33 KB

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