Path: blob/master/editor/export/export_template_manager.cpp
9903 views
/**************************************************************************/1/* export_template_manager.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "export_template_manager.h"3132#include "core/io/dir_access.h"33#include "core/io/json.h"34#include "core/io/zip_io.h"35#include "core/version.h"36#include "editor/editor_node.h"37#include "editor/editor_string_names.h"38#include "editor/export/editor_export_preset.h"39#include "editor/file_system/editor_file_system.h"40#include "editor/file_system/editor_paths.h"41#include "editor/gui/progress_dialog.h"42#include "editor/settings/editor_settings.h"43#include "editor/themes/editor_scale.h"44#include "scene/gui/file_dialog.h"45#include "scene/gui/line_edit.h"46#include "scene/gui/link_button.h"47#include "scene/gui/menu_button.h"48#include "scene/gui/option_button.h"49#include "scene/gui/separator.h"50#include "scene/gui/tree.h"51#include "scene/main/http_request.h"5253enum DownloadsAvailability {54DOWNLOADS_AVAILABLE,55DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE,56DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS,57DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS,58};5960static DownloadsAvailability _get_downloads_availability() {61const int network_mode = EDITOR_GET("network/connection/network_mode");6263// Downloadable export templates are only available for stable and official alpha/beta/RC builds64// (which always have a number following their status, e.g. "alpha1").65// Therefore, don't display download-related features when using a development version66// (whose builds aren't numbered).67if (String(GODOT_VERSION_STATUS) == String("dev") ||68String(GODOT_VERSION_STATUS) == String("alpha") ||69String(GODOT_VERSION_STATUS) == String("beta") ||70String(GODOT_VERSION_STATUS) == String("rc")) {71return DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS;72}7374#ifdef REAL_T_IS_DOUBLE75return DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS;76#endif7778if (network_mode == EditorSettings::NETWORK_OFFLINE) {79return DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE;80}8182return DOWNLOADS_AVAILABLE;83}8485void ExportTemplateManager::_update_template_status() {86// Fetch installed templates from the file system.87Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);88const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();8990Error err = da->change_dir(templates_dir);91ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir + "'.");9293RBSet<String> templates;94da->list_dir_begin();95if (err == OK) {96String c = da->get_next();97while (!c.is_empty()) {98if (da->current_is_dir() && !c.begins_with(".")) {99templates.insert(c);100}101c = da->get_next();102}103}104da->list_dir_end();105106// Update the state of the current version.107String current_version = GODOT_VERSION_FULL_CONFIG;108current_value->set_text(current_version);109110if (templates.has(current_version)) {111current_missing_label->hide();112current_installed_label->show();113114current_installed_hb->show();115current_version_exists = true;116} else {117current_installed_label->hide();118current_missing_label->show();119120current_installed_hb->hide();121current_version_exists = false;122}123124if (is_downloading_templates) {125install_options_vb->hide();126download_progress_hb->show();127} else {128download_progress_hb->hide();129install_options_vb->show();130131if (templates.has(current_version)) {132current_installed_path->set_text(templates_dir.path_join(current_version));133}134}135136// Update the list of other installed versions.137installed_table->clear();138TreeItem *installed_root = installed_table->create_item();139140for (RBSet<String>::Element *E = templates.back(); E; E = E->prev()) {141String version_string = E->get();142if (version_string == current_version) {143continue;144}145146TreeItem *ti = installed_table->create_item(installed_root);147ti->set_text(0, version_string);148149#ifndef ANDROID_ENABLED150ti->add_button(0, get_editor_theme_icon(SNAME("Folder")), OPEN_TEMPLATE_FOLDER, false, TTR("Open the folder containing these templates."));151#endif152ti->add_button(0, get_editor_theme_icon(SNAME("Remove")), UNINSTALL_TEMPLATE, false, TTR("Uninstall these templates."));153}154}155156void ExportTemplateManager::_download_current() {157if (is_downloading_templates) {158return;159}160is_downloading_templates = true;161162install_options_vb->hide();163download_progress_hb->show();164165if (mirrors_available) {166String mirror_url = _get_selected_mirror();167if (mirror_url.is_empty()) {168_set_current_progress_status(TTR("There are no mirrors available."), true);169return;170}171172_download_template(mirror_url, true);173} else if (!is_refreshing_mirrors) {174_set_current_progress_status(TTR("Retrieving the mirror list..."));175_refresh_mirrors();176}177}178179void ExportTemplateManager::_download_template(const String &p_url, bool p_skip_check) {180if (!p_skip_check && is_downloading_templates) {181return;182}183is_downloading_templates = true;184185install_options_vb->hide();186download_progress_hb->show();187download_progress_bar->show();188download_progress_bar->set_indeterminate(true);189190_set_current_progress_status(TTR("Starting the download..."));191192download_templates->set_download_file(EditorPaths::get_singleton()->get_cache_dir().path_join("tmp_templates.tpz"));193download_templates->set_use_threads(true);194195const String proxy_host = EDITOR_GET("network/http_proxy/host");196const int proxy_port = EDITOR_GET("network/http_proxy/port");197download_templates->set_http_proxy(proxy_host, proxy_port);198download_templates->set_https_proxy(proxy_host, proxy_port);199200Error err = download_templates->request(p_url);201if (err != OK) {202_set_current_progress_status(TTR("Error requesting URL:") + " " + p_url, true);203download_progress_hb->hide();204return;205}206207set_process(true);208_set_current_progress_status(TTR("Connecting to the mirror..."));209}210211void ExportTemplateManager::_download_template_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {212switch (p_status) {213case HTTPRequest::RESULT_CANT_RESOLVE: {214_set_current_progress_status(TTR("Can't resolve the requested address."), true);215} break;216case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:217case HTTPRequest::RESULT_CONNECTION_ERROR:218case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH:219case HTTPRequest::RESULT_TLS_HANDSHAKE_ERROR:220case HTTPRequest::RESULT_CANT_CONNECT: {221_set_current_progress_status(TTR("Can't connect to the mirror."), true);222} break;223case HTTPRequest::RESULT_NO_RESPONSE: {224_set_current_progress_status(TTR("No response from the mirror."), true);225} break;226case HTTPRequest::RESULT_REQUEST_FAILED: {227_set_current_progress_status(TTR("Request failed."), true);228} break;229case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {230_set_current_progress_status(TTR("Request ended up in a redirect loop."), true);231} break;232default: {233if (p_code != 200) {234_set_current_progress_status(TTR("Request failed:") + " " + itos(p_code), true);235} else {236_set_current_progress_status(TTR("Download complete; extracting templates..."));237String path = download_templates->get_download_file();238239is_downloading_templates = false;240bool ret = _install_file_selected(path, true);241if (ret) {242// Clean up downloaded file.243Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);244Error err = da->remove(path);245if (err != OK) {246EditorNode::get_singleton()->add_io_error(TTR("Cannot remove temporary file:") + "\n" + path + "\n");247}248} else {249EditorNode::get_singleton()->add_io_error(vformat(TTR("Templates installation failed.\nThe problematic templates archives can be found at '%s'."), path));250}251}252} break;253}254255set_process(false);256}257258void ExportTemplateManager::_cancel_template_download() {259if (!is_downloading_templates) {260return;261}262263download_templates->cancel_request();264download_progress_hb->hide();265install_options_vb->show();266is_downloading_templates = false;267}268269void ExportTemplateManager::_refresh_mirrors() {270if (is_refreshing_mirrors) {271return;272}273is_refreshing_mirrors = true;274275String current_version = GODOT_VERSION_FULL_CONFIG;276const String mirrors_metadata_url = "https://godotengine.org/mirrorlist/" + current_version + ".json";277request_mirrors->request(mirrors_metadata_url);278}279280void ExportTemplateManager::_refresh_mirrors_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {281if (p_status != HTTPRequest::RESULT_SUCCESS || p_code != 200) {282EditorNode::get_singleton()->show_warning(TTR("Error getting the list of mirrors."));283is_refreshing_mirrors = false;284if (is_downloading_templates) {285_cancel_template_download();286}287return;288}289290String response_json = String::utf8((const char *)p_data.ptr(), p_data.size());291292JSON json;293Error err = json.parse(response_json);294if (err != OK) {295EditorNode::get_singleton()->show_warning(TTR("Error parsing JSON with the list of mirrors. Please report this issue!"));296is_refreshing_mirrors = false;297if (is_downloading_templates) {298_cancel_template_download();299}300return;301}302303mirrors_list->clear();304mirrors_list->add_item(TTR("Best available mirror"), 0);305306mirrors_available = false;307308Dictionary mirror_data = json.get_data();309if (mirror_data.has("mirrors")) {310Array mirrors = mirror_data["mirrors"];311312for (int i = 0; i < mirrors.size(); i++) {313Dictionary m = mirrors[i];314ERR_CONTINUE(!m.has("url") || !m.has("name"));315316mirrors_list->add_item(m["name"]);317mirrors_list->set_item_metadata(i + 1, m["url"]);318319mirrors_available = true;320}321}322if (!mirrors_available) {323EditorNode::get_singleton()->show_warning(TTR("No download links found for this version. Direct download is only available for official releases."));324if (is_downloading_templates) {325_cancel_template_download();326}327}328329is_refreshing_mirrors = false;330331if (is_downloading_templates) {332String mirror_url = _get_selected_mirror();333if (mirror_url.is_empty()) {334_set_current_progress_status(TTR("There are no mirrors available."), true);335return;336}337338_download_template(mirror_url, true);339}340}341342void ExportTemplateManager::_force_online_mode() {343EditorSettings::get_singleton()->set_setting("network/connection/network_mode", EditorSettings::NETWORK_ONLINE);344EditorSettings::get_singleton()->notify_changes();345EditorSettings::get_singleton()->save();346347popup_manager();348}349350bool ExportTemplateManager::_humanize_http_status(HTTPRequest *p_request, String *r_status, int *r_downloaded_bytes, int *r_total_bytes) {351*r_status = "";352*r_downloaded_bytes = -1;353*r_total_bytes = -1;354bool success = true;355356switch (p_request->get_http_client_status()) {357case HTTPClient::STATUS_DISCONNECTED:358*r_status = TTR("Disconnected");359success = false;360break;361case HTTPClient::STATUS_RESOLVING:362*r_status = TTR("Resolving");363break;364case HTTPClient::STATUS_CANT_RESOLVE:365*r_status = TTR("Can't Resolve");366success = false;367break;368case HTTPClient::STATUS_CONNECTING:369*r_status = TTR("Connecting...");370break;371case HTTPClient::STATUS_CANT_CONNECT:372*r_status = TTR("Can't Connect");373success = false;374break;375case HTTPClient::STATUS_CONNECTED:376*r_status = TTR("Connected");377break;378case HTTPClient::STATUS_REQUESTING:379*r_status = TTR("Requesting...");380break;381case HTTPClient::STATUS_BODY:382*r_status = TTR("Downloading");383*r_downloaded_bytes = p_request->get_downloaded_bytes();384*r_total_bytes = p_request->get_body_size();385386if (p_request->get_body_size() > 0) {387*r_status += " " + String::humanize_size(p_request->get_downloaded_bytes()) + "/" + String::humanize_size(p_request->get_body_size());388} else {389*r_status += " " + String::humanize_size(p_request->get_downloaded_bytes());390}391break;392case HTTPClient::STATUS_CONNECTION_ERROR:393*r_status = TTR("Connection Error");394success = false;395break;396case HTTPClient::STATUS_TLS_HANDSHAKE_ERROR:397*r_status = TTR("TLS Handshake Error");398success = false;399break;400}401402return success;403}404405void ExportTemplateManager::_set_current_progress_status(const String &p_status, bool p_error) {406download_progress_label->set_text(p_status);407408if (p_error) {409download_progress_bar->hide();410download_progress_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("error_color"), EditorStringName(Editor)));411} else {412download_progress_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SceneStringName(font_color), SNAME("Label")));413}414}415416void ExportTemplateManager::_set_current_progress_value(float p_value, const String &p_status) {417download_progress_bar->show();418download_progress_bar->set_indeterminate(false);419download_progress_bar->set_value(p_value);420download_progress_label->set_text(p_status);421}422423void ExportTemplateManager::_install_file() {424install_file_dialog->popup_file_dialog();425}426427bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_skip_progress) {428Ref<FileAccess> io_fa;429zlib_filefunc_def io = zipio_create_io(&io_fa);430431unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);432if (!pkg) {433EditorNode::get_singleton()->show_warning(TTR("Can't open the export templates file."));434return false;435}436int ret = unzGoToFirstFile(pkg);437438// Count them and find version.439int fc = 0;440String version;441String contents_dir;442443while (ret == UNZ_OK) {444unz_file_info info;445char fname[16384];446ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);447if (ret != UNZ_OK) {448break;449}450451String file = String::utf8(fname);452453// Skip the __MACOSX directory created by macOS's built-in file zipper.454if (file.begins_with("__MACOSX")) {455ret = unzGoToNextFile(pkg);456continue;457}458459if (file.ends_with("version.txt")) {460Vector<uint8_t> uncomp_data;461uncomp_data.resize(info.uncompressed_size);462463// Read.464unzOpenCurrentFile(pkg);465ret = unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());466ERR_BREAK_MSG(ret < 0, vformat("An error occurred while attempting to read from file: %s. This file will not be used.", file));467unzCloseCurrentFile(pkg);468469String data_str = String::utf8((const char *)uncomp_data.ptr(), uncomp_data.size());470data_str = data_str.strip_edges();471472// Version number should be of the form major.minor[.patch].status[.module_config]473// so it can in theory have 3 or more slices.474if (data_str.get_slice_count(".") < 3) {475EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside the export templates file: %s."), data_str));476unzClose(pkg);477return false;478}479480version = data_str;481contents_dir = file.get_base_dir().trim_suffix("/").trim_suffix("\\");482}483484if (file.get_file().size() != 0) {485fc++;486}487488ret = unzGoToNextFile(pkg);489}490491if (version.is_empty()) {492EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside the export templates file."));493unzClose(pkg);494return false;495}496497Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);498String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(version);499Error err = d->make_dir_recursive(template_path);500if (err != OK) {501EditorNode::get_singleton()->show_warning(TTR("Error creating path for extracting templates:") + "\n" + template_path);502unzClose(pkg);503return false;504}505506EditorProgress *p = nullptr;507if (!p_skip_progress) {508p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));509}510511fc = 0;512ret = unzGoToFirstFile(pkg);513while (ret == UNZ_OK) {514// Get filename.515unz_file_info info;516char fname[16384];517ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);518if (ret != UNZ_OK) {519break;520}521522if (String::utf8(fname).ends_with("/")) {523// File is a directory, ignore it.524// Directories will be created when extracting each file.525ret = unzGoToNextFile(pkg);526continue;527}528529String file_path(String::utf8(fname).simplify_path());530531String file = file_path.get_file();532533// Skip the __MACOSX directory created by macOS's built-in file zipper.534if (file.is_empty() || file.begins_with("__MACOSX")) {535ret = unzGoToNextFile(pkg);536continue;537}538539Vector<uint8_t> uncomp_data;540uncomp_data.resize(info.uncompressed_size);541542// Read543unzOpenCurrentFile(pkg);544ret = unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());545ERR_BREAK_MSG(ret < 0, vformat("An error occurred while attempting to read from file: %s. This file will not be used.", file));546unzCloseCurrentFile(pkg);547548String base_dir = file_path.get_base_dir().trim_suffix("/");549550if (base_dir != contents_dir && base_dir.begins_with(contents_dir)) {551base_dir = base_dir.substr(contents_dir.length(), file_path.length()).trim_prefix("/");552file = base_dir.path_join(file);553554Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);555ERR_CONTINUE(da.is_null());556557String output_dir = template_path.path_join(base_dir);558559if (!DirAccess::exists(output_dir)) {560Error mkdir_err = da->make_dir_recursive(output_dir);561ERR_CONTINUE(mkdir_err != OK);562}563}564565if (p) {566p->step(TTR("Importing:") + " " + file, fc);567}568569String to_write = template_path.path_join(file);570Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE);571572if (f.is_null()) {573ret = unzGoToNextFile(pkg);574fc++;575ERR_CONTINUE_MSG(true, "Can't open file from path '" + String(to_write) + "'.");576}577578f->store_buffer(uncomp_data.ptr(), uncomp_data.size());579f.unref(); // close file.580#ifndef WINDOWS_ENABLED581FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF);582#endif583584ret = unzGoToNextFile(pkg);585fc++;586}587588if (p) {589memdelete(p);590}591unzClose(pkg);592593_update_template_status();594EditorSettings::get_singleton()->set("_export_template_download_directory", p_file.get_base_dir());595return true;596}597598void ExportTemplateManager::_uninstall_template(const String &p_version) {599uninstall_confirm->set_text(vformat(TTR("Remove templates for the version '%s'?"), p_version));600uninstall_confirm->popup_centered();601uninstall_version = p_version;602}603604void ExportTemplateManager::_uninstall_template_confirmed() {605Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);606const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();607608Error err = da->change_dir(templates_dir);609ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir + "'.");610err = da->change_dir(uninstall_version);611ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir.path_join(uninstall_version) + "'.");612613err = da->erase_contents_recursive();614ERR_FAIL_COND_MSG(err != OK, "Could not remove all templates in '" + templates_dir.path_join(uninstall_version) + "'.");615616da->change_dir("..");617err = da->remove(uninstall_version);618ERR_FAIL_COND_MSG(err != OK, "Could not remove templates directory at '" + templates_dir.path_join(uninstall_version) + "'.");619620_update_template_status();621}622623String ExportTemplateManager::_get_selected_mirror() const {624if (mirrors_list->get_item_count() == 1) {625return "";626}627628int selected = mirrors_list->get_selected_id();629if (selected == 0) {630// This is a special "best available" value; so pick the first available mirror from the rest of the list.631selected = 1;632}633634return mirrors_list->get_item_metadata(selected);635}636637void ExportTemplateManager::_mirror_options_button_cbk(int p_id) {638switch (p_id) {639case VISIT_WEB_MIRROR: {640String mirror_url = _get_selected_mirror();641if (mirror_url.is_empty()) {642EditorNode::get_singleton()->show_warning(TTR("There are no mirrors available."));643return;644}645646OS::get_singleton()->shell_open(mirror_url);647} break;648649case COPY_MIRROR_URL: {650String mirror_url = _get_selected_mirror();651if (mirror_url.is_empty()) {652EditorNode::get_singleton()->show_warning(TTR("There are no mirrors available."));653return;654}655656DisplayServer::get_singleton()->clipboard_set(mirror_url);657} break;658}659}660661void ExportTemplateManager::_installed_table_button_cbk(Object *p_item, int p_column, int p_id, MouseButton p_button) {662if (p_button != MouseButton::LEFT) {663return;664}665TreeItem *ti = Object::cast_to<TreeItem>(p_item);666if (!ti) {667return;668}669670switch (p_id) {671case OPEN_TEMPLATE_FOLDER: {672String version_string = ti->get_text(0);673_open_template_folder(version_string);674} break;675676case UNINSTALL_TEMPLATE: {677String version_string = ti->get_text(0);678_uninstall_template(version_string);679} break;680}681}682683void ExportTemplateManager::_open_template_folder(const String &p_version) {684const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();685OS::get_singleton()->shell_show_in_file_manager(templates_dir.path_join(p_version), true);686}687688void ExportTemplateManager::popup_manager() {689_update_template_status();690691switch (_get_downloads_availability()) {692case DOWNLOADS_AVAILABLE: {693current_missing_label->set_text(TTR("Export templates are missing. Download them or install from a file."));694695mirrors_list->clear();696mirrors_list->add_item(TTR("Best available mirror"), 0);697mirrors_list->set_disabled(false);698mirrors_list->set_tooltip_text("");699700mirror_options_button->set_disabled(false);701702download_current_button->set_disabled(false);703download_current_button->set_tooltip_text("");704705if (!is_downloading_templates) {706_refresh_mirrors();707}708709enable_online_hb->hide();710} break;711712case DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE: {713current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));714715mirrors_list->clear();716mirrors_list->add_item(TTR("Not available in offline mode"), 0);717mirrors_list->set_disabled(true);718mirrors_list->set_tooltip_text(TTR("Template downloading is disabled in offline mode."));719720mirror_options_button->set_disabled(true);721722download_current_button->set_disabled(true);723download_current_button->set_tooltip_text(TTR("Template downloading is disabled in offline mode."));724725enable_online_hb->show();726} break;727728case DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS: {729current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));730731mirrors_list->clear();732mirrors_list->add_item(TTR("No templates for development builds"), 0);733mirrors_list->set_disabled(true);734mirrors_list->set_tooltip_text(TTR("Official export templates aren't available for development builds."));735736mirror_options_button->set_disabled(true);737738download_current_button->set_disabled(true);739download_current_button->set_tooltip_text(TTR("Official export templates aren't available for development builds."));740741enable_online_hb->hide();742} break;743744case DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS: {745current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));746747mirrors_list->clear();748mirrors_list->add_item(TTR("No templates for double-precision builds"), 0);749mirrors_list->set_disabled(true);750mirrors_list->set_tooltip_text(TTR("Official export templates aren't available for double-precision builds."));751752mirror_options_button->set_disabled(true);753754download_current_button->set_disabled(true);755download_current_button->set_tooltip_text(TTR("Official export templates aren't available for double-precision builds."));756}757}758759popup_centered(Size2(720, 280) * EDSCALE);760}761762void ExportTemplateManager::ok_pressed() {763if (!is_downloading_templates) {764hide();765return;766}767768hide_dialog_accept->popup_centered();769}770771void ExportTemplateManager::_hide_dialog() {772hide();773}774775String ExportTemplateManager::get_android_build_directory(const Ref<EditorExportPreset> &p_preset) {776if (p_preset.is_valid()) {777String gradle_build_dir = p_preset->get("gradle_build/gradle_build_directory");778if (!gradle_build_dir.is_empty()) {779return gradle_build_dir.path_join("build");780}781}782return "res://android/build";783}784785String ExportTemplateManager::get_android_source_zip(const Ref<EditorExportPreset> &p_preset) {786if (p_preset.is_valid()) {787String android_source_zip = p_preset->get("gradle_build/android_source_template");788if (!android_source_zip.is_empty()) {789return android_source_zip;790}791}792793const String templates_dir = EditorPaths::get_singleton()->get_export_templates_dir().path_join(GODOT_VERSION_FULL_CONFIG);794return templates_dir.path_join("android_source.zip");795}796797String ExportTemplateManager::get_android_template_identifier(const Ref<EditorExportPreset> &p_preset) {798// The template identifier is the Godot version for the default template, and the full path plus md5 hash for custom templates.799if (p_preset.is_valid()) {800String android_source_zip = p_preset->get("gradle_build/android_source_template");801if (!android_source_zip.is_empty()) {802return android_source_zip + String(" [") + FileAccess::get_md5(android_source_zip) + String("]");803}804}805return GODOT_VERSION_FULL_CONFIG;806}807808bool ExportTemplateManager::is_android_template_installed(const Ref<EditorExportPreset> &p_preset) {809return DirAccess::exists(get_android_build_directory(p_preset));810}811812bool ExportTemplateManager::can_install_android_template(const Ref<EditorExportPreset> &p_preset) {813return FileAccess::exists(get_android_source_zip(p_preset));814}815816Error ExportTemplateManager::install_android_template(const Ref<EditorExportPreset> &p_preset) {817const String source_zip = get_android_source_zip(p_preset);818ERR_FAIL_COND_V(!FileAccess::exists(source_zip), ERR_CANT_OPEN);819return install_android_template_from_file(source_zip, p_preset);820}821822Error ExportTemplateManager::install_android_template_from_file(const String &p_file, const Ref<EditorExportPreset> &p_preset) {823// To support custom Android builds, we install the Java source code and buildsystem824// from android_source.zip to the project's res://android folder.825826Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);827ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);828829String build_dir = get_android_build_directory(p_preset);830String parent_dir = build_dir.get_base_dir();831832// Make parent of the build dir (if it does not exist).833da->make_dir_recursive(parent_dir);834{835// Add identifier, to ensure building won't work if the current template doesn't match.836Ref<FileAccess> f = FileAccess::open(parent_dir.path_join(".build_version"), FileAccess::WRITE);837ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE);838f->store_line(get_android_template_identifier(p_preset));839}840841// Create the android build directory.842Error err = da->make_dir_recursive(build_dir);843ERR_FAIL_COND_V(err != OK, err);844{845// Add an empty .gdignore file to avoid scan.846Ref<FileAccess> f = FileAccess::open(build_dir.path_join(".gdignore"), FileAccess::WRITE);847ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE);848f->store_line("");849}850851// Uncompress source template.852853Ref<FileAccess> io_fa;854zlib_filefunc_def io = zipio_create_io(&io_fa);855856unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);857ERR_FAIL_NULL_V_MSG(pkg, ERR_CANT_OPEN, "Android sources not in ZIP format.");858859int ret = unzGoToFirstFile(pkg);860int total_files = 0;861// Count files to unzip.862while (ret == UNZ_OK) {863total_files++;864ret = unzGoToNextFile(pkg);865}866ret = unzGoToFirstFile(pkg);867868ProgressDialog::get_singleton()->add_task("uncompress_src", TTR("Uncompressing Android Build Sources"), total_files);869870HashSet<String> dirs_tested;871int idx = 0;872while (ret == UNZ_OK) {873// Get file path.874unz_file_info info;875char fpath[16384];876ret = unzGetCurrentFileInfo(pkg, &info, fpath, 16384, nullptr, 0, nullptr, 0);877if (ret != UNZ_OK) {878break;879}880881String path = String::utf8(fpath);882String base_dir = path.get_base_dir();883884if (!path.ends_with("/")) {885Vector<uint8_t> uncomp_data;886uncomp_data.resize(info.uncompressed_size);887888// Read.889unzOpenCurrentFile(pkg);890unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());891unzCloseCurrentFile(pkg);892893if (!dirs_tested.has(base_dir)) {894da->make_dir_recursive(build_dir.path_join(base_dir));895dirs_tested.insert(base_dir);896}897898String to_write = build_dir.path_join(path);899Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE);900if (f.is_valid()) {901f->store_buffer(uncomp_data.ptr(), uncomp_data.size());902f.unref(); // close file.903#ifndef WINDOWS_ENABLED904FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF);905#endif906} else {907ERR_PRINT("Can't uncompress file: " + to_write);908}909}910911ProgressDialog::get_singleton()->task_step("uncompress_src", path, idx);912913idx++;914ret = unzGoToNextFile(pkg);915}916917ProgressDialog::get_singleton()->end_task("uncompress_src");918unzClose(pkg);919EditorFileSystem::get_singleton()->scan_changes();920return OK;921}922923void ExportTemplateManager::_notification(int p_what) {924switch (p_what) {925case NOTIFICATION_THEME_CHANGED: {926current_value->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("main"), EditorStringName(EditorFonts)));927current_missing_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("error_color"), EditorStringName(Editor)));928current_installed_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor)));929930mirror_options_button->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));931} break;932933case NOTIFICATION_VISIBILITY_CHANGED: {934if (!is_visible()) {935set_process(false);936} else if (is_visible() && is_downloading_templates) {937set_process(true);938}939} break;940941case NOTIFICATION_PROCESS: {942update_countdown -= get_process_delta_time();943if (update_countdown > 0) {944return;945}946update_countdown = 0.5;947948String status;949int downloaded_bytes;950int total_bytes;951bool success = _humanize_http_status(download_templates, &status, &downloaded_bytes, &total_bytes);952953if (downloaded_bytes >= 0) {954if (total_bytes > 0) {955_set_current_progress_value(float(downloaded_bytes) / total_bytes, status);956} else {957_set_current_progress_value(0, status);958}959} else {960_set_current_progress_status(status);961}962963if (!success) {964set_process(false);965}966} break;967968case NOTIFICATION_WM_CLOSE_REQUEST: {969// This won't stop the window from closing, but will show the alert if the download is active.970ok_pressed();971} break;972}973}974975ExportTemplateManager::ExportTemplateManager() {976set_title(TTR("Export Template Manager"));977set_hide_on_ok(false);978set_ok_button_text(TTR("Close"));979980VBoxContainer *main_vb = memnew(VBoxContainer);981add_child(main_vb);982983// Current version controls.984HBoxContainer *current_hb = memnew(HBoxContainer);985main_vb->add_child(current_hb);986987Label *current_label = memnew(Label);988current_label->set_theme_type_variation("HeaderSmall");989current_label->set_text(TTR("Current Version:"));990current_hb->add_child(current_label);991992current_value = memnew(Label);993current_value->set_focus_mode(Control::FOCUS_ACCESSIBILITY);994current_hb->add_child(current_value);995996// Current version statuses.997// Status: Current version is missing.998current_missing_label = memnew(Label);999current_missing_label->set_theme_type_variation("HeaderSmall");10001001current_missing_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);1002current_missing_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);1003current_hb->add_child(current_missing_label);10041005// Status: Current version is installed.1006current_installed_label = memnew(Label);1007current_installed_label->set_theme_type_variation("HeaderSmall");1008current_installed_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);1009current_installed_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);1010current_installed_label->set_text(TTR("Export templates are installed and ready to be used."));1011current_hb->add_child(current_installed_label);1012current_installed_label->hide();10131014// Currently installed template.1015current_installed_hb = memnew(HBoxContainer);1016main_vb->add_child(current_installed_hb);10171018current_installed_path = memnew(LineEdit);1019current_installed_path->set_editable(false);1020current_installed_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);1021current_installed_path->set_accessibility_name(TTRC("Installed Path"));1022current_installed_hb->add_child(current_installed_path);10231024#ifndef ANDROID_ENABLED1025Button *current_open_button = memnew(Button);1026current_open_button->set_text(TTR("Open Folder"));1027current_open_button->set_tooltip_text(TTR("Open the folder containing installed templates for the current version."));1028current_installed_hb->add_child(current_open_button);1029current_open_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_open_template_folder).bind(GODOT_VERSION_FULL_CONFIG));1030#endif10311032current_uninstall_button = memnew(Button);1033current_uninstall_button->set_text(TTR("Uninstall"));1034current_uninstall_button->set_tooltip_text(TTR("Uninstall templates for the current version."));1035current_installed_hb->add_child(current_uninstall_button);1036current_uninstall_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_uninstall_template).bind(GODOT_VERSION_FULL_CONFIG));10371038main_vb->add_child(memnew(HSeparator));10391040// Download and install section.1041HBoxContainer *install_templates_hb = memnew(HBoxContainer);1042main_vb->add_child(install_templates_hb);10431044// Download and install buttons are available.1045install_options_vb = memnew(VBoxContainer);1046install_options_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);1047install_templates_hb->add_child(install_options_vb);10481049HBoxContainer *download_install_hb = memnew(HBoxContainer);1050install_options_vb->add_child(download_install_hb);10511052Label *mirrors_label = memnew(Label);1053mirrors_label->set_text(TTR("Download from:"));1054download_install_hb->add_child(mirrors_label);10551056mirrors_list = memnew(OptionButton);1057mirrors_list->set_accessibility_name(TTRC("Mirror"));1058mirrors_list->set_custom_minimum_size(Size2(280, 0) * EDSCALE);1059download_install_hb->add_child(mirrors_list);10601061request_mirrors = memnew(HTTPRequest);1062mirrors_list->add_child(request_mirrors);1063request_mirrors->connect("request_completed", callable_mp(this, &ExportTemplateManager::_refresh_mirrors_completed));10641065mirror_options_button = memnew(MenuButton);1066mirror_options_button->set_accessibility_name(TTRC("Mirror Options"));1067mirror_options_button->get_popup()->add_item(TTR("Open in Web Browser"), VISIT_WEB_MIRROR);1068mirror_options_button->get_popup()->add_item(TTR("Copy Mirror URL"), COPY_MIRROR_URL);1069download_install_hb->add_child(mirror_options_button);1070mirror_options_button->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ExportTemplateManager::_mirror_options_button_cbk));10711072download_install_hb->add_spacer();10731074download_current_button = memnew(Button);1075download_current_button->set_text(TTR("Download and Install"));1076download_current_button->set_tooltip_text(TTR("Download and install templates for the current version from the best possible mirror."));1077download_install_hb->add_child(download_current_button);1078download_current_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_download_current));10791080HBoxContainer *install_file_hb = memnew(HBoxContainer);1081install_file_hb->set_alignment(BoxContainer::ALIGNMENT_END);1082install_options_vb->add_child(install_file_hb);10831084install_file_button = memnew(Button);1085install_file_button->set_text(TTR("Install from File"));1086install_file_button->set_tooltip_text(TTR("Install templates from a local file."));1087install_file_hb->add_child(install_file_button);1088install_file_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_install_file));10891090enable_online_hb = memnew(HBoxContainer);1091install_options_vb->add_child(enable_online_hb);10921093Label *enable_online_label = memnew(Label);1094enable_online_label->set_text(TTR("Online mode is needed to download the templates."));1095enable_online_hb->add_child(enable_online_label);10961097LinkButton *enable_online_button = memnew(LinkButton);1098enable_online_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);1099enable_online_button->set_text(TTR("Go Online"));1100enable_online_hb->add_child(enable_online_button);1101enable_online_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_force_online_mode));11021103// Templates are being downloaded; buttons unavailable.1104download_progress_hb = memnew(HBoxContainer);1105download_progress_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);1106install_templates_hb->add_child(download_progress_hb);1107download_progress_hb->hide();11081109download_progress_bar = memnew(ProgressBar);1110download_progress_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL);1111download_progress_bar->set_v_size_flags(Control::SIZE_SHRINK_CENTER);1112download_progress_bar->set_min(0);1113download_progress_bar->set_max(1);1114download_progress_bar->set_value(0);1115download_progress_bar->set_step(0.01);1116download_progress_bar->set_editor_preview_indeterminate(true);1117download_progress_hb->add_child(download_progress_bar);11181119download_progress_label = memnew(Label);1120download_progress_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);1121download_progress_hb->add_child(download_progress_label);11221123Button *download_cancel_button = memnew(Button);1124download_cancel_button->set_text(TTR("Cancel"));1125download_cancel_button->set_tooltip_text(TTR("Cancel the download of the templates."));1126download_progress_hb->add_child(download_cancel_button);1127download_cancel_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_cancel_template_download));11281129download_templates = memnew(HTTPRequest);1130install_templates_hb->add_child(download_templates);1131download_templates->connect("request_completed", callable_mp(this, &ExportTemplateManager::_download_template_completed));11321133main_vb->add_child(memnew(HSeparator));11341135// Other installed templates table.1136HBoxContainer *installed_versions_hb = memnew(HBoxContainer);1137main_vb->add_child(installed_versions_hb);1138Label *installed_label = memnew(Label);1139installed_label->set_theme_type_variation("HeaderSmall");1140installed_label->set_text(TTR("Other Installed Versions:"));1141installed_versions_hb->add_child(installed_label);11421143installed_table = memnew(Tree);1144installed_table->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);1145installed_table->set_hide_root(true);1146installed_table->set_custom_minimum_size(Size2(0, 100) * EDSCALE);1147installed_table->set_v_size_flags(Control::SIZE_EXPAND_FILL);1148main_vb->add_child(installed_table);1149installed_table->connect("button_clicked", callable_mp(this, &ExportTemplateManager::_installed_table_button_cbk));11501151// Dialogs.1152uninstall_confirm = memnew(ConfirmationDialog);1153uninstall_confirm->set_title(TTR("Uninstall Template"));1154add_child(uninstall_confirm);1155uninstall_confirm->connect(SceneStringName(confirmed), callable_mp(this, &ExportTemplateManager::_uninstall_template_confirmed));11561157install_file_dialog = memnew(FileDialog);1158install_file_dialog->set_title(TTR("Select Template File"));1159install_file_dialog->set_access(FileDialog::ACCESS_FILESYSTEM);1160install_file_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_FILE);1161install_file_dialog->set_current_dir(EDITOR_DEF("_export_template_download_directory", ""));1162install_file_dialog->add_filter("*.tpz", TTR("Godot Export Templates"));1163install_file_dialog->connect("file_selected", callable_mp(this, &ExportTemplateManager::_install_file_selected).bind(false));1164add_child(install_file_dialog);11651166hide_dialog_accept = memnew(AcceptDialog);1167hide_dialog_accept->set_text(TTR("The templates will continue to download.\nYou may experience a short editor freeze when they finish."));1168add_child(hide_dialog_accept);1169hide_dialog_accept->connect(SceneStringName(confirmed), callable_mp(this, &ExportTemplateManager::_hide_dialog));1170}117111721173