export_plugin.cpp 27 KB

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