export_plugin.cpp 26 KB

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