Path: blob/master/platform/android/export/gradle_export_util.cpp
21135 views
/**************************************************************************/1/* gradle_export_util.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 "gradle_export_util.h"3132#include "core/string/translation_server.h"33#include "modules/regex/regex.h"3435int _get_android_orientation_value(DisplayServer::ScreenOrientation screen_orientation) {36switch (screen_orientation) {37case DisplayServer::SCREEN_PORTRAIT:38return 1;39case DisplayServer::SCREEN_REVERSE_LANDSCAPE:40return 8;41case DisplayServer::SCREEN_REVERSE_PORTRAIT:42return 9;43case DisplayServer::SCREEN_SENSOR_LANDSCAPE:44return 11;45case DisplayServer::SCREEN_SENSOR_PORTRAIT:46return 12;47case DisplayServer::SCREEN_SENSOR:48return 13;49case DisplayServer::SCREEN_LANDSCAPE:50default:51return 0;52}53}5455String _get_android_orientation_label(DisplayServer::ScreenOrientation screen_orientation) {56switch (screen_orientation) {57case DisplayServer::SCREEN_PORTRAIT:58return "portrait";59case DisplayServer::SCREEN_REVERSE_LANDSCAPE:60return "reverseLandscape";61case DisplayServer::SCREEN_REVERSE_PORTRAIT:62return "reversePortrait";63case DisplayServer::SCREEN_SENSOR_LANDSCAPE:64return "userLandscape";65case DisplayServer::SCREEN_SENSOR_PORTRAIT:66return "userPortrait";67case DisplayServer::SCREEN_SENSOR:68return "fullUser";69case DisplayServer::SCREEN_LANDSCAPE:70default:71return "landscape";72}73}7475int _get_app_category_value(int category_index) {76switch (category_index) {77case APP_CATEGORY_ACCESSIBILITY:78return 8;79case APP_CATEGORY_AUDIO:80return 1;81case APP_CATEGORY_IMAGE:82return 3;83case APP_CATEGORY_MAPS:84return 6;85case APP_CATEGORY_NEWS:86return 5;87case APP_CATEGORY_PRODUCTIVITY:88return 7;89case APP_CATEGORY_SOCIAL:90return 4;91case APP_CATEGORY_UNDEFINED:92return -1;93case APP_CATEGORY_VIDEO:94return 2;95case APP_CATEGORY_GAME:96default:97return 0;98}99}100101String _get_app_category_label(int category_index) {102switch (category_index) {103case APP_CATEGORY_ACCESSIBILITY:104return "accessibility";105case APP_CATEGORY_AUDIO:106return "audio";107case APP_CATEGORY_IMAGE:108return "image";109case APP_CATEGORY_MAPS:110return "maps";111case APP_CATEGORY_NEWS:112return "news";113case APP_CATEGORY_PRODUCTIVITY:114return "productivity";115case APP_CATEGORY_SOCIAL:116return "social";117case APP_CATEGORY_VIDEO:118return "video";119case APP_CATEGORY_GAME:120default:121return "game";122}123}124125// Utility method used to create a directory.126Error create_directory(const String &p_dir) {127if (!DirAccess::exists(p_dir)) {128Ref<DirAccess> filesystem_da = DirAccess::create(DirAccess::ACCESS_RESOURCES);129ERR_FAIL_COND_V_MSG(filesystem_da.is_null(), ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'.");130Error err = filesystem_da->make_dir_recursive(p_dir);131ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'.");132}133return OK;134}135136// Writes p_data into a file at p_path, creating directories if necessary.137// Note: this will overwrite the file at p_path if it already exists.138Error store_file_at_path(const String &p_path, const Vector<uint8_t> &p_data) {139String dir = p_path.get_base_dir();140Error err = create_directory(dir);141if (err != OK) {142return err;143}144Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE);145ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'.");146fa->store_buffer(p_data.ptr(), p_data.size());147return OK;148}149150// Writes string p_data into a file at p_path, creating directories if necessary.151// Note: this will overwrite the file at p_path if it already exists.152Error store_string_at_path(const String &p_path, const String &p_data) {153String dir = p_path.get_base_dir();154Error err = create_directory(dir);155if (err != OK) {156if (OS::get_singleton()->is_stdout_verbose()) {157print_error("Unable to write data into " + p_path);158}159return err;160}161Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE);162ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'.");163fa->store_string(p_data);164return OK;165}166167// Implementation of EditorExportSaveFunction.168// This method will only be called as an input to export_project_files.169// It is used by the export_project_files method to save all the asset files into the gradle project.170// It's functionality mirrors that of the method save_apk_file.171// This method will be called ONLY when gradle build is enabled.172Error rename_and_store_file_in_gradle_project(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed, bool p_delta) {173CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata);174175const String simplified_path = EditorExportPlatform::simplify_path(p_path);176177Vector<uint8_t> enc_data;178EditorExportPlatform::SavedData sd;179Error err = _store_temp_file(simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, p_delta, enc_data, sd);180if (err != OK) {181return err;182}183184String dst_path;185if (export_data->pd.salt.length() == 32) {186dst_path = export_data->assets_directory + String("/") + (simplified_path + export_data->pd.salt).sha256_text();187} else {188dst_path = export_data->assets_directory + String("/") + simplified_path.trim_prefix("res://");189}190print_verbose("Saving project files from " + simplified_path + " into " + dst_path);191err = store_file_at_path(dst_path, enc_data);192193export_data->pd.file_ofs.push_back(sd);194return err;195}196197String _android_xml_escape(const String &p_string) {198// Android XML requires strings to be both valid XML (`xml_escape()`) but also199// to escape characters which are valid XML but have special meaning in Android XML.200// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling201// Note: Didn't handle U+XXXX unicode chars, could be done if needed.202return p_string203.replace("@", "\\@")204.replace("?", "\\?")205.replace("'", "\\'")206.replace("\"", "\\\"")207.replace("\n", "\\n")208.replace("\t", "\\t")209.xml_escape(false);210}211212// Creates strings.xml files inside the gradle project for different locales.213Error _create_project_name_strings_files(const Ref<EditorExportPreset> &p_preset, const String &p_project_name, const String &p_gradle_build_dir, const Dictionary &p_appnames) {214print_verbose("Creating strings resources for supported locales for project " + p_project_name);215// Stores the string into the default values directory.216String processed_default_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(p_project_name));217store_string_at_path(p_gradle_build_dir.path_join("res/values/godot_project_name_string.xml"), processed_default_xml_string);218219// Searches the Gradle project res/ directory to find all supported locales220Ref<DirAccess> da = DirAccess::open(p_gradle_build_dir.path_join("res"));221if (da.is_null()) {222if (OS::get_singleton()->is_stdout_verbose()) {223print_error("Unable to open Android resources directory.");224}225return ERR_CANT_OPEN;226}227228// Setup a temporary translation domain to translate the project name.229const StringName domain_name = "godot.project_name_localization";230Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(domain_name);231TranslationServer::get_singleton()->load_project_translations(domain);232233da->list_dir_begin();234while (true) {235String file = da->get_next();236if (file.is_empty()) {237break;238}239if (!file.begins_with("values-")) {240// NOTE: This assumes all directories that start with "values-" are for localization.241continue;242}243String locale = file.replace("values-", "").replace("-r", "_");244String locale_directory = p_gradle_build_dir.path_join("res/" + file + "/godot_project_name_string.xml");245246String locale_project_name;247if (p_appnames.is_empty()) {248domain->set_locale_override(locale);249locale_project_name = domain->translate(p_project_name, String());250} else {251locale_project_name = p_appnames.get(locale, p_project_name);252}253if (locale_project_name != p_project_name) {254String processed_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(locale_project_name));255print_verbose("Storing project name for locale " + locale + " under " + locale_directory);256store_string_at_path(locale_directory, processed_xml_string);257} else {258// TODO: Once the legacy build system is deprecated we don't need to have xml files for this else branch259store_string_at_path(locale_directory, processed_default_xml_string);260}261}262da->list_dir_end();263264TranslationServer::get_singleton()->remove_domain(domain_name);265266return OK;267}268269String bool_to_string(bool v) {270return v ? "true" : "false";271}272273String _get_gles_tag() {274return " <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" />\n";275}276277String _get_screen_sizes_tag(const Ref<EditorExportPreset> &p_preset) {278String manifest_screen_sizes = " <supports-screens \n tools:node=\"replace\"";279String sizes[] = { "small", "normal", "large", "xlarge" };280constexpr size_t num_sizes = std_size(sizes);281for (size_t i = 0; i < num_sizes; i++) {282String feature_name = vformat("screen/support_%s", sizes[i]);283String feature_support = bool_to_string(p_preset->get(feature_name));284String xml_entry = vformat("\n android:%sScreens=\"%s\"", sizes[i], feature_support);285manifest_screen_sizes += xml_entry;286}287manifest_screen_sizes += " />\n";288return manifest_screen_sizes;289}290291String _get_activity_tag(const Ref<EditorExportPlatform> &p_export_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug) {292String export_plugins_activity_element_contents;293Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();294for (int i = 0; i < export_plugins.size(); i++) {295if (export_plugins[i]->supports_platform(p_export_platform)) {296const String contents = export_plugins[i]->get_android_manifest_activity_element_contents(p_export_platform, p_debug);297if (!contents.is_empty()) {298const String export_plugin_name = export_plugins[i]->get_name();299export_plugins_activity_element_contents += "<!-- Start of manifest activity element contents from " + export_plugin_name + " -->\n";300export_plugins_activity_element_contents += contents;301export_plugins_activity_element_contents += "\n";302export_plugins_activity_element_contents += "<!-- End of manifest activity element contents from " + export_plugin_name + " -->\n";303}304}305}306307// Update the GodotApp activity tag.308String orientation = _get_android_orientation_label(DisplayServer::ScreenOrientation(int(p_export_platform->get_project_setting(p_preset, "display/window/handheld/orientation"))));309String manifest_activity_text = vformat(310" <activity android:name=\".GodotApp\" "311"tools:replace=\"android:screenOrientation,android:excludeFromRecents,android:resizeableActivity\" "312"tools:node=\"mergeOnlyAttributes\" "313"android:excludeFromRecents=\"%s\" "314"android:screenOrientation=\"%s\" "315"android:resizeableActivity=\"%s\">\n",316bool_to_string(p_preset->get("package/exclude_from_recents")),317orientation,318bool_to_string(bool(p_export_platform->get_project_setting(p_preset, "display/window/size/resizable"))));319320// *LAUNCHER and *HOME categories should only go to the activity-alias.321Ref<RegEx> activity_content_to_remove_regex = RegEx::create_from_string(R"delim(<category\s+android:name\s*=\s*"\S+(LAUNCHER|HOME)"\s*\/>)delim");322String updated_export_plugins_activity_element_contents = activity_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);323manifest_activity_text += updated_export_plugins_activity_element_contents;324325manifest_activity_text += " </activity>\n";326327// Update the GodotAppLauncher activity tag.328manifest_activity_text += " <activity-alias\n"329" tools:node=\"mergeOnlyAttributes\"\n"330" android:name=\".GodotAppLauncher\"\n"331" android:targetActivity=\".GodotApp\"\n"332" android:exported=\"true\">\n";333334manifest_activity_text += " <intent-filter>\n"335" <action android:name=\"android.intent.action.MAIN\" />\n"336" <category android:name=\"android.intent.category.DEFAULT\" />\n";337338bool show_in_app_library = p_preset->get("package/show_in_app_library");339if (show_in_app_library) {340manifest_activity_text += " <category android:name=\"android.intent.category.LAUNCHER\" />\n";341}342343bool uses_leanback_category = p_preset->get("package/show_in_android_tv");344if (uses_leanback_category) {345manifest_activity_text += " <category android:name=\"android.intent.category.LEANBACK_LAUNCHER\" />\n";346}347348bool uses_home_category = p_preset->get("package/show_as_launcher_app");349if (uses_home_category) {350manifest_activity_text += " <category android:name=\"android.intent.category.HOME\" />\n";351}352353manifest_activity_text += " </intent-filter>\n";354355// Hybrid categories should only go to the actual 'GodotApp' activity.356Ref<RegEx> activity_alias_content_to_remove_regex = RegEx::create_from_string(R"delim(<category\s+android:name\s*=\s*"org.godotengine.xr.hybrid.(IMMERSIVE|PANEL)"\s*\/>)delim");357String updated_export_plugins_activity_alias_element_contents = activity_alias_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);358manifest_activity_text += updated_export_plugins_activity_alias_element_contents;359360manifest_activity_text += " </activity-alias>\n";361return manifest_activity_text;362}363364String _get_application_tag(const Ref<EditorExportPlatform> &p_export_platform, const Ref<EditorExportPreset> &p_preset, bool p_has_read_write_storage_permission, bool p_debug, const Vector<MetadataInfo> &p_metadata) {365int app_category_index = (int)(p_preset->get("package/app_category"));366bool is_game = app_category_index == APP_CATEGORY_GAME;367368String manifest_application_text = vformat(369" <application android:label=\"@string/godot_project_name_string\"\n"370" android:allowBackup=\"%s\"\n"371" android:icon=\"@mipmap/icon\"\n"372" android:isGame=\"%s\"\n"373" android:hasFragileUserData=\"%s\"\n"374" android:requestLegacyExternalStorage=\"%s\"\n",375bool_to_string(p_preset->get("user_data_backup/allow")),376bool_to_string(is_game),377bool_to_string(p_preset->get("package/retain_data_on_uninstall")),378bool_to_string(p_has_read_write_storage_permission));379if (app_category_index != APP_CATEGORY_UNDEFINED) {380manifest_application_text += vformat(" android:appCategory=\"%s\"\n", _get_app_category_label(app_category_index));381manifest_application_text += " tools:replace=\"android:allowBackup,android:appCategory,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";382} else {383manifest_application_text += " tools:remove=\"android:appCategory\"\n";384manifest_application_text += " tools:replace=\"android:allowBackup,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";385}386manifest_application_text += " tools:ignore=\"GoogleAppIndexingWarning\">\n\n";387388for (int i = 0; i < p_metadata.size(); i++) {389manifest_application_text += vformat(" <meta-data tools:node=\"replace\" android:name=\"%s\" android:value=\"%s\" />\n", p_metadata[i].name, p_metadata[i].value);390}391392Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();393for (int i = 0; i < export_plugins.size(); i++) {394if (export_plugins[i]->supports_platform(p_export_platform)) {395const String contents = export_plugins[i]->get_android_manifest_application_element_contents(p_export_platform, p_debug);396if (!contents.is_empty()) {397const String export_plugin_name = export_plugins[i]->get_name();398manifest_application_text += "<!-- Start of manifest application element contents from " + export_plugin_name + " -->\n";399manifest_application_text += contents;400manifest_application_text += "\n";401manifest_application_text += "<!-- End of manifest application element contents from " + export_plugin_name + " -->\n";402}403}404}405406manifest_application_text += _get_activity_tag(p_export_platform, p_preset, p_debug);407manifest_application_text += " </application>\n";408return manifest_application_text;409}410411Error _store_temp_file(const String &p_simplified_path, const Vector<uint8_t> &p_data, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed, bool p_delta, Vector<uint8_t> &r_enc_data, EditorExportPlatform::SavedData &r_sd) {412Error err = OK;413Ref<FileAccess> ftmp = FileAccess::create_temp(FileAccess::WRITE_READ, "export", "tmp", false, &err);414if (err != OK) {415return err;416}417r_sd.path_utf8 = p_simplified_path.trim_prefix("res://").utf8();418r_sd.ofs = 0;419r_sd.size = p_data.size();420r_sd.delta = p_delta;421err = EditorExportPlatform::_encrypt_and_store_data(ftmp, p_simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, r_sd.encrypted);422if (err != OK) {423return err;424}425426r_enc_data.resize(ftmp->get_length());427ftmp->seek(0);428ftmp->get_buffer(r_enc_data.ptrw(), r_enc_data.size());429ftmp.unref();430431// Store MD5 of original file.432{433unsigned char hash[16];434CryptoCore::md5(p_data.ptr(), p_data.size(), hash);435r_sd.md5.resize(16);436for (int i = 0; i < 16; i++) {437r_sd.md5.write[i] = hash[i];438}439}440return OK;441}442443444