export_plugin.cpp 26 KB

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