Path: blob/master/platform/android/export/export_plugin.cpp
10278 views
/**************************************************************************/1/* export_plugin.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_plugin.h"3132#include "logo_svg.gen.h"33#include "run_icon_svg.gen.h"3435#include "core/io/dir_access.h"36#include "core/io/file_access.h"37#include "core/io/image_loader.h"38#include "core/io/json.h"39#include "core/io/marshalls.h"40#include "core/version.h"41#include "drivers/png/png_driver_common.h"42#include "editor/editor_log.h"43#include "editor/editor_node.h"44#include "editor/export/export_template_manager.h"45#include "editor/file_system/editor_paths.h"46#include "editor/import/resource_importer_texture_settings.h"47#include "editor/settings/editor_settings.h"48#include "editor/themes/editor_scale.h"49#include "main/splash.gen.h"50#include "scene/resources/image_texture.h"5152#include "modules/modules_enabled.gen.h" // For mono.53#include "modules/svg/image_loader_svg.h"5455#ifdef MODULE_MONO_ENABLED56#include "modules/mono/utils/path_utils.h"57#endif5859#ifdef ANDROID_ENABLED60#include "../os_android.h"61#endif6263static const char *ANDROID_PERMS[] = {64"ACCESS_CHECKIN_PROPERTIES",65"ACCESS_COARSE_LOCATION",66"ACCESS_FINE_LOCATION",67"ACCESS_LOCATION_EXTRA_COMMANDS",68"ACCESS_MEDIA_LOCATION",69"ACCESS_MOCK_LOCATION",70"ACCESS_NETWORK_STATE",71"ACCESS_SURFACE_FLINGER",72"ACCESS_WIFI_STATE",73"ACCOUNT_MANAGER",74"ADD_VOICEMAIL",75"AUTHENTICATE_ACCOUNTS",76"BATTERY_STATS",77"BIND_ACCESSIBILITY_SERVICE",78"BIND_APPWIDGET",79"BIND_DEVICE_ADMIN",80"BIND_INPUT_METHOD",81"BIND_NFC_SERVICE",82"BIND_NOTIFICATION_LISTENER_SERVICE",83"BIND_PRINT_SERVICE",84"BIND_REMOTEVIEWS",85"BIND_TEXT_SERVICE",86"BIND_VPN_SERVICE",87"BIND_WALLPAPER",88"BLUETOOTH",89"BLUETOOTH_ADMIN",90"BLUETOOTH_PRIVILEGED",91"BRICK",92"BROADCAST_PACKAGE_REMOVED",93"BROADCAST_SMS",94"BROADCAST_STICKY",95"BROADCAST_WAP_PUSH",96"CALL_PHONE",97"CALL_PRIVILEGED",98"CAMERA",99"CAPTURE_AUDIO_OUTPUT",100"CAPTURE_SECURE_VIDEO_OUTPUT",101"CAPTURE_VIDEO_OUTPUT",102"CHANGE_COMPONENT_ENABLED_STATE",103"CHANGE_CONFIGURATION",104"CHANGE_NETWORK_STATE",105"CHANGE_WIFI_MULTICAST_STATE",106"CHANGE_WIFI_STATE",107"CLEAR_APP_CACHE",108"CLEAR_APP_USER_DATA",109"CONTROL_LOCATION_UPDATES",110"DELETE_CACHE_FILES",111"DELETE_PACKAGES",112"DEVICE_POWER",113"DIAGNOSTIC",114"DISABLE_KEYGUARD",115"DUMP",116"EXPAND_STATUS_BAR",117"FACTORY_TEST",118"FLASHLIGHT",119"FORCE_BACK",120"GET_ACCOUNTS",121"GET_PACKAGE_SIZE",122"GET_TASKS",123"GET_TOP_ACTIVITY_INFO",124"GLOBAL_SEARCH",125"HARDWARE_TEST",126"INJECT_EVENTS",127"INSTALL_LOCATION_PROVIDER",128"INSTALL_PACKAGES",129"INSTALL_SHORTCUT",130"INTERNAL_SYSTEM_WINDOW",131"INTERNET",132"KILL_BACKGROUND_PROCESSES",133"LOCATION_HARDWARE",134"MANAGE_ACCOUNTS",135"MANAGE_APP_TOKENS",136"MANAGE_DOCUMENTS",137"MANAGE_EXTERNAL_STORAGE",138"MASTER_CLEAR",139"MEDIA_CONTENT_CONTROL",140"MODIFY_AUDIO_SETTINGS",141"MODIFY_PHONE_STATE",142"MOUNT_FORMAT_FILESYSTEMS",143"MOUNT_UNMOUNT_FILESYSTEMS",144"NFC",145"PERSISTENT_ACTIVITY",146"POST_NOTIFICATIONS",147"PROCESS_OUTGOING_CALLS",148"READ_CALENDAR",149"READ_CALL_LOG",150"READ_CONTACTS",151"READ_EXTERNAL_STORAGE",152"READ_FRAME_BUFFER",153"READ_HISTORY_BOOKMARKS",154"READ_INPUT_STATE",155"READ_LOGS",156"READ_MEDIA_AUDIO",157"READ_MEDIA_IMAGES",158"READ_MEDIA_VIDEO",159"READ_MEDIA_VISUAL_USER_SELECTED",160"READ_PHONE_STATE",161"READ_PROFILE",162"READ_SMS",163"READ_SOCIAL_STREAM",164"READ_SYNC_SETTINGS",165"READ_SYNC_STATS",166"READ_USER_DICTIONARY",167"REBOOT",168"RECEIVE_BOOT_COMPLETED",169"RECEIVE_MMS",170"RECEIVE_SMS",171"RECEIVE_WAP_PUSH",172"RECORD_AUDIO",173"REORDER_TASKS",174"RESTART_PACKAGES",175"SEND_RESPOND_VIA_MESSAGE",176"SEND_SMS",177"SET_ACTIVITY_WATCHER",178"SET_ALARM",179"SET_ALWAYS_FINISH",180"SET_ANIMATION_SCALE",181"SET_DEBUG_APP",182"SET_ORIENTATION",183"SET_POINTER_SPEED",184"SET_PREFERRED_APPLICATIONS",185"SET_PROCESS_LIMIT",186"SET_TIME",187"SET_TIME_ZONE",188"SET_WALLPAPER",189"SET_WALLPAPER_HINTS",190"SIGNAL_PERSISTENT_PROCESSES",191"STATUS_BAR",192"SUBSCRIBED_FEEDS_READ",193"SUBSCRIBED_FEEDS_WRITE",194"SYSTEM_ALERT_WINDOW",195"TRANSMIT_IR",196"UNINSTALL_SHORTCUT",197"UPDATE_DEVICE_STATS",198"USE_CREDENTIALS",199"USE_SIP",200"VIBRATE",201"WAKE_LOCK",202"WRITE_APN_SETTINGS",203"WRITE_CALENDAR",204"WRITE_CALL_LOG",205"WRITE_CONTACTS",206"WRITE_EXTERNAL_STORAGE",207"WRITE_GSERVICES",208"WRITE_HISTORY_BOOKMARKS",209"WRITE_PROFILE",210"WRITE_SECURE_SETTINGS",211"WRITE_SETTINGS",212"WRITE_SMS",213"WRITE_SOCIAL_STREAM",214"WRITE_SYNC_SETTINGS",215"WRITE_USER_DICTIONARY",216nullptr217};218219static const char *MISMATCHED_VERSIONS_MESSAGE = "Android build version mismatch:\n| Template installed: %s\n| Requested version: %s\nPlease reinstall Android build template from 'Project' menu.";220221static const char *GDEXTENSION_LIBS_PATH = "libs/gdextensionlibs.json";222223// This template string must be in sync with the content of 'platform/android/java/lib/res/mipmap-anydpi-v26/icon.xml'.224static const String ICON_XML_TEMPLATE =225"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"226"<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n"227" <background android:drawable=\"@mipmap/icon_background\"/>\n"228" <foreground android:drawable=\"@mipmap/icon_foreground\"/>\n"229"%s" // Placeholder for the optional monochrome tag.230"</adaptive-icon>";231232static const String ICON_XML_PATH = "res/mipmap-anydpi-v26/icon.xml";233static const String THEMED_ICON_XML_PATH = "res/mipmap-anydpi-v26/themed_icon.xml";234235static const int ICON_DENSITIES_COUNT = 6;236static const char *LAUNCHER_ICON_OPTION = PNAME("launcher_icons/main_192x192");237static const char *LAUNCHER_ADAPTIVE_ICON_FOREGROUND_OPTION = PNAME("launcher_icons/adaptive_foreground_432x432");238static const char *LAUNCHER_ADAPTIVE_ICON_BACKGROUND_OPTION = PNAME("launcher_icons/adaptive_background_432x432");239static const char *LAUNCHER_ADAPTIVE_ICON_MONOCHROME_OPTION = PNAME("launcher_icons/adaptive_monochrome_432x432");240241static const LauncherIcon LAUNCHER_ICONS[ICON_DENSITIES_COUNT] = {242{ "res/mipmap-xxxhdpi-v4/icon.png", 192 },243{ "res/mipmap-xxhdpi-v4/icon.png", 144 },244{ "res/mipmap-xhdpi-v4/icon.png", 96 },245{ "res/mipmap-hdpi-v4/icon.png", 72 },246{ "res/mipmap-mdpi-v4/icon.png", 48 },247{ "res/mipmap/icon.png", 192 }248};249250static const LauncherIcon LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[ICON_DENSITIES_COUNT] = {251{ "res/mipmap-xxxhdpi-v4/icon_foreground.png", 432 },252{ "res/mipmap-xxhdpi-v4/icon_foreground.png", 324 },253{ "res/mipmap-xhdpi-v4/icon_foreground.png", 216 },254{ "res/mipmap-hdpi-v4/icon_foreground.png", 162 },255{ "res/mipmap-mdpi-v4/icon_foreground.png", 108 },256{ "res/mipmap/icon_foreground.png", 432 }257};258259static const LauncherIcon LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[ICON_DENSITIES_COUNT] = {260{ "res/mipmap-xxxhdpi-v4/icon_background.png", 432 },261{ "res/mipmap-xxhdpi-v4/icon_background.png", 324 },262{ "res/mipmap-xhdpi-v4/icon_background.png", 216 },263{ "res/mipmap-hdpi-v4/icon_background.png", 162 },264{ "res/mipmap-mdpi-v4/icon_background.png", 108 },265{ "res/mipmap/icon_background.png", 432 }266};267268static const LauncherIcon LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[ICON_DENSITIES_COUNT] = {269{ "res/mipmap-xxxhdpi-v4/icon_monochrome.png", 432 },270{ "res/mipmap-xxhdpi-v4/icon_monochrome.png", 324 },271{ "res/mipmap-xhdpi-v4/icon_monochrome.png", 216 },272{ "res/mipmap-hdpi-v4/icon_monochrome.png", 162 },273{ "res/mipmap-mdpi-v4/icon_monochrome.png", 108 },274{ "res/mipmap/icon_monochrome.png", 432 }275};276277static const int EXPORT_FORMAT_APK = 0;278static const int EXPORT_FORMAT_AAB = 1;279280static const char *APK_ASSETS_DIRECTORY = "assets";281static const char *AAB_ASSETS_DIRECTORY = "assetPackInstallTime/src/main/assets";282283static const int DEFAULT_MIN_SDK_VERSION = 24; // Should match the value in 'platform/android/java/app/config.gradle#minSdk'284static const int DEFAULT_TARGET_SDK_VERSION = 35; // Should match the value in 'platform/android/java/app/config.gradle#targetSdk'285286#ifndef ANDROID_ENABLED287void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) {288EditorExportPlatformAndroid *ea = static_cast<EditorExportPlatformAndroid *>(ud);289290while (!ea->quit_request.is_set()) {291#ifndef DISABLE_DEPRECATED292// Check for android plugins updates293{294// Nothing to do if we already know the plugins have changed.295if (!ea->android_plugins_changed.is_set()) {296Vector<PluginConfigAndroid> loaded_plugins = get_plugins();297298MutexLock lock(ea->android_plugins_lock);299300if (ea->android_plugins.size() != loaded_plugins.size()) {301ea->android_plugins_changed.set();302} else {303for (int i = 0; i < ea->android_plugins.size(); i++) {304if (ea->android_plugins[i].name != loaded_plugins[i].name) {305ea->android_plugins_changed.set();306break;307}308}309}310311if (ea->android_plugins_changed.is_set()) {312ea->android_plugins = loaded_plugins;313}314}315}316#endif // DISABLE_DEPRECATED317318// Check for devices updates319String adb = get_adb_path();320// adb.exe was locking the editor_doc_cache file on startup. Adding a check for is_editor_ready provides just enough time321// to regenerate the doc cache.322if (ea->has_runnable_preset.is_set() && FileAccess::exists(adb) && EditorNode::get_singleton()->is_editor_ready()) {323String devices;324List<String> args;325args.push_back("devices");326int ec;327OS::get_singleton()->execute(adb, args, &devices, &ec);328329Vector<String> ds = devices.split("\n");330Vector<String> ldevices;331for (int i = 1; i < ds.size(); i++) {332String d = ds[i];333int dpos = d.find("device");334if (dpos == -1) {335continue;336}337d = d.substr(0, dpos).strip_edges();338ldevices.push_back(d);339}340341MutexLock lock(ea->device_lock);342343bool different = false;344345if (ea->devices.size() != ldevices.size()) {346different = true;347} else {348for (int i = 0; i < ea->devices.size(); i++) {349if (ea->devices[i].id != ldevices[i]) {350different = true;351break;352}353}354}355356if (different) {357Vector<Device> ndevices;358359for (int i = 0; i < ldevices.size(); i++) {360Device d;361d.id = ldevices[i];362for (int j = 0; j < ea->devices.size(); j++) {363if (ea->devices[j].id == ldevices[i]) {364d.description = ea->devices[j].description;365d.name = ea->devices[j].name;366d.api_level = ea->devices[j].api_level;367}368}369370if (d.description.is_empty()) {371//in the oven, request!372args.clear();373args.push_back("-s");374args.push_back(d.id);375args.push_back("shell");376args.push_back("getprop");377int ec2;378String dp;379380OS::get_singleton()->execute(adb, args, &dp, &ec2);381382Vector<String> props = dp.split("\n");383String vendor;384String device;385d.description = "Device ID: " + d.id + "\n";386d.api_level = 0;387for (int j = 0; j < props.size(); j++) {388// got information by `shell cat /system/build.prop` before and its format is "property=value"389// it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above390// its format is "[property]: [value]" so changed it as like build.prop391String p = props[j];392p = p.replace("]: ", "=");393p = p.remove_chars("[]");394395if (p.begins_with("ro.product.model=")) {396device = p.get_slicec('=', 1).strip_edges();397} else if (p.begins_with("ro.product.brand=")) {398vendor = p.get_slicec('=', 1).strip_edges().capitalize();399} else if (p.begins_with("ro.build.display.id=")) {400d.description += "Build: " + p.get_slicec('=', 1).strip_edges() + "\n";401} else if (p.begins_with("ro.build.version.release=")) {402d.description += "Release: " + p.get_slicec('=', 1).strip_edges() + "\n";403} else if (p.begins_with("ro.build.version.sdk=")) {404d.api_level = p.get_slicec('=', 1).to_int();405} else if (p.begins_with("ro.product.cpu.abi=")) {406d.architecture = p.get_slicec('=', 1).strip_edges();407d.description += "CPU: " + d.architecture + "\n";408} else if (p.begins_with("ro.product.manufacturer=")) {409d.description += "Manufacturer: " + p.get_slicec('=', 1).strip_edges() + "\n";410} else if (p.begins_with("ro.board.platform=")) {411d.description += "Chipset: " + p.get_slicec('=', 1).strip_edges() + "\n";412} else if (p.begins_with("ro.opengles.version=")) {413uint32_t opengl = p.get_slicec('=', 1).to_int();414d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl) & 0xFF) + "\n";415}416}417418d.name = vendor + " " + device;419if (device.is_empty()) {420continue;421}422}423424ndevices.push_back(d);425}426427ea->devices = ndevices;428ea->devices_changed.set();429}430}431432uint64_t sleep = 200;433uint64_t wait = 3000000;434uint64_t time = OS::get_singleton()->get_ticks_usec();435while (OS::get_singleton()->get_ticks_usec() - time < wait) {436OS::get_singleton()->delay_usec(1000 * sleep);437if (ea->quit_request.is_set()) {438break;439}440}441}442443if (ea->has_runnable_preset.is_set() && EDITOR_GET("export/android/shutdown_adb_on_exit")) {444String adb = get_adb_path();445if (!FileAccess::exists(adb)) {446return; //adb not configured447}448449List<String> args;450args.push_back("kill-server");451OS::get_singleton()->execute(adb, args);452}453}454455void EditorExportPlatformAndroid::_update_preset_status() {456const int preset_count = EditorExport::get_singleton()->get_export_preset_count();457bool has_runnable = false;458459for (int i = 0; i < preset_count; i++) {460const Ref<EditorExportPreset> &preset = EditorExport::get_singleton()->get_export_preset(i);461if (preset->get_platform() == this && preset->is_runnable()) {462has_runnable = true;463break;464}465}466467if (has_runnable) {468has_runnable_preset.set();469} else {470has_runnable_preset.clear();471}472devices_changed.set();473}474#endif475476String EditorExportPlatformAndroid::get_project_name(const Ref<EditorExportPreset> &p_preset, const String &p_name) const {477String aname;478if (!p_name.is_empty()) {479aname = p_name;480} else {481aname = get_project_setting(p_preset, "application/config/name");482}483484if (aname.is_empty()) {485aname = GODOT_VERSION_NAME;486}487488return aname;489}490491String EditorExportPlatformAndroid::get_package_name(const Ref<EditorExportPreset> &p_preset, const String &p_package) const {492String pname = p_package;493String name = get_valid_basename(p_preset);494pname = pname.replace("$genname", name);495return pname;496}497498// Returns the project name without invalid characters499// or the "noname" string if all characters are invalid.500String EditorExportPlatformAndroid::get_valid_basename(const Ref<EditorExportPreset> &p_preset) const {501String basename = get_project_setting(p_preset, "application/config/name");502basename = basename.to_lower();503504String name;505bool first = true;506for (int i = 0; i < basename.length(); i++) {507char32_t c = basename[i];508if (is_digit(c) && first) {509continue;510}511if (is_ascii_identifier_char(c)) {512name += String::chr(c);513first = false;514}515}516517if (name.is_empty()) {518name = "noname";519}520521return name;522}523524String EditorExportPlatformAndroid::get_assets_directory(const Ref<EditorExportPreset> &p_preset, int p_export_format) const {525String gradle_build_directory = ExportTemplateManager::get_android_build_directory(p_preset);526return gradle_build_directory.path_join(p_export_format == EXPORT_FORMAT_AAB ? AAB_ASSETS_DIRECTORY : APK_ASSETS_DIRECTORY);527}528529bool EditorExportPlatformAndroid::is_package_name_valid(const Ref<EditorExportPreset> &p_preset, const String &p_package, String *r_error) const {530String pname = get_package_name(p_preset, p_package);531532if (pname.length() == 0) {533if (r_error) {534*r_error = TTR("Package name is missing.");535}536return false;537}538539int segments = 0;540bool first = true;541for (int i = 0; i < pname.length(); i++) {542char32_t c = pname[i];543if (first && c == '.') {544if (r_error) {545*r_error = TTR("Package segments must be of non-zero length.");546}547return false;548}549if (c == '.') {550segments++;551first = true;552continue;553}554if (!is_ascii_identifier_char(c)) {555if (r_error) {556*r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c));557}558return false;559}560if (first && is_digit(c)) {561if (r_error) {562*r_error = TTR("A digit cannot be the first character in a package segment.");563}564return false;565}566if (first && is_underscore(c)) {567if (r_error) {568*r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c));569}570return false;571}572first = false;573}574575if (segments == 0) {576if (r_error) {577*r_error = TTR("The package must have at least one '.' separator.");578}579return false;580}581582if (first) {583if (r_error) {584*r_error = TTR("Package segments must be of non-zero length.");585}586return false;587}588589return true;590}591592bool EditorExportPlatformAndroid::is_project_name_valid(const Ref<EditorExportPreset> &p_preset) const {593// Get the original project name and convert to lowercase.594String basename = get_project_setting(p_preset, "application/config/name");595basename = basename.to_lower();596// Check if there are invalid characters.597if (basename != get_valid_basename(p_preset)) {598return false;599}600return true;601}602603bool EditorExportPlatformAndroid::_should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) {604/*605* By not compressing files with little or no benefit in doing so,606* a performance gain is expected at runtime. Moreover, if the APK is607* zip-aligned, assets stored as they are can be efficiently read by608* Android by memory-mapping them.609*/610611// -- Unconditional uncompress to mimic AAPT plus some other612613static const char *unconditional_compress_ext[] = {614// From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp615// These formats are already compressed, or don't compress well:616".jpg", ".jpeg", ".png", ".gif",617".wav", ".mp2", ".mp3", ".ogg", ".aac",618".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",619".rtttl", ".imy", ".xmf", ".mp4", ".m4a",620".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",621".amr", ".awb", ".wma", ".wmv",622// Godot-specific:623".webp", // Same reasoning as .png624".cfb", // Don't let small config files slow-down startup625".scn", // Binary scenes are usually already compressed626".ctex", // Streamable textures are usually already compressed627".pck", // Pack.628// Trailer for easier processing629nullptr630};631632for (const char **ext = unconditional_compress_ext; *ext; ++ext) {633if (p_path.to_lower().ends_with(String(*ext))) {634return false;635}636}637638// -- Compressed resource?639640if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') {641// Already compressed642return false;643}644645// --- TODO: Decide on texture resources according to their image compression setting646647return true;648}649650zip_fileinfo EditorExportPlatformAndroid::get_zip_fileinfo() {651OS::DateTime dt = OS::get_singleton()->get_datetime();652653zip_fileinfo zipfi;654zipfi.tmz_date.tm_year = dt.year;655zipfi.tmz_date.tm_mon = dt.month - 1; // tm_mon is zero indexed656zipfi.tmz_date.tm_mday = dt.day;657zipfi.tmz_date.tm_hour = dt.hour;658zipfi.tmz_date.tm_min = dt.minute;659zipfi.tmz_date.tm_sec = dt.second;660zipfi.dosDate = 0;661zipfi.external_fa = 0;662zipfi.internal_fa = 0;663664return zipfi;665}666667Vector<EditorExportPlatformAndroid::ABI> EditorExportPlatformAndroid::get_abis() {668// Should have the same order and size as get_archs.669Vector<ABI> abis;670abis.push_back(ABI("armeabi-v7a", "arm32"));671abis.push_back(ABI("arm64-v8a", "arm64"));672abis.push_back(ABI("x86", "x86_32"));673abis.push_back(ABI("x86_64", "x86_64"));674return abis;675}676677#ifndef DISABLE_DEPRECATED678/// List the gdap files in the directory specified by the p_path parameter.679Vector<String> EditorExportPlatformAndroid::list_gdap_files(const String &p_path) {680Vector<String> dir_files;681Ref<DirAccess> da = DirAccess::open(p_path);682if (da.is_valid()) {683da->list_dir_begin();684while (true) {685String file = da->get_next();686if (file.is_empty()) {687break;688}689690if (da->current_is_dir() || da->current_is_hidden()) {691continue;692}693694if (file.ends_with(PluginConfigAndroid::PLUGIN_CONFIG_EXT)) {695dir_files.push_back(file);696}697}698da->list_dir_end();699}700701return dir_files;702}703704Vector<PluginConfigAndroid> EditorExportPlatformAndroid::get_plugins() {705Vector<PluginConfigAndroid> loaded_plugins;706707String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().path_join("android/plugins");708709// Add the prebuilt plugins710loaded_plugins.append_array(PluginConfigAndroid::get_prebuilt_plugins(plugins_dir));711712if (DirAccess::exists(plugins_dir)) {713Vector<String> plugins_filenames = list_gdap_files(plugins_dir);714715if (!plugins_filenames.is_empty()) {716Ref<ConfigFile> config_file;717config_file.instantiate();718for (int i = 0; i < plugins_filenames.size(); i++) {719PluginConfigAndroid config = PluginConfigAndroid::load_plugin_config(config_file, plugins_dir.path_join(plugins_filenames[i]));720if (config.valid_config) {721loaded_plugins.push_back(config);722} else {723print_error("Invalid plugin config file " + plugins_filenames[i]);724}725}726}727}728729return loaded_plugins;730}731732Vector<PluginConfigAndroid> EditorExportPlatformAndroid::get_enabled_plugins(const Ref<EditorExportPreset> &p_presets) {733Vector<PluginConfigAndroid> enabled_plugins;734Vector<PluginConfigAndroid> all_plugins = get_plugins();735for (int i = 0; i < all_plugins.size(); i++) {736PluginConfigAndroid plugin = all_plugins[i];737bool enabled = p_presets->get("plugins/" + plugin.name);738if (enabled) {739enabled_plugins.push_back(plugin);740}741}742743return enabled_plugins;744}745#endif // DISABLE_DEPRECATED746747Error EditorExportPlatformAndroid::store_in_apk(APKExportData *ed, const String &p_path, const Vector<uint8_t> &p_data, int compression_method) {748zip_fileinfo zipfi = get_zip_fileinfo();749zipOpenNewFileInZip(ed->apk,750p_path.utf8().get_data(),751&zipfi,752nullptr,7530,754nullptr,7550,756nullptr,757compression_method,758Z_DEFAULT_COMPRESSION);759760zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size());761zipCloseFileInZip(ed->apk);762763return OK;764}765766Error EditorExportPlatformAndroid::save_apk_so(void *p_userdata, const SharedObject &p_so) {767if (!p_so.path.get_file().begins_with("lib")) {768String err = "Android .so file names must start with \"lib\", but got: " + p_so.path;769ERR_PRINT(err);770return FAILED;771}772APKExportData *ed = static_cast<APKExportData *>(p_userdata);773Vector<ABI> abis = get_abis();774bool exported = false;775for (int i = 0; i < p_so.tags.size(); ++i) {776// shared objects can be fat (compatible with multiple ABIs)777int abi_index = -1;778for (int j = 0; j < abis.size(); ++j) {779if (abis[j].abi == p_so.tags[i] || abis[j].arch == p_so.tags[i]) {780abi_index = j;781break;782}783}784if (abi_index != -1) {785exported = true;786String abi = abis[abi_index].abi;787String dst_path = String("lib").path_join(abi).path_join(p_so.path.get_file());788Vector<uint8_t> array = FileAccess::get_file_as_bytes(p_so.path);789Error store_err = store_in_apk(ed, dst_path, array, Z_NO_COMPRESSION);790ERR_FAIL_COND_V_MSG(store_err, store_err, "Cannot store in apk file '" + dst_path + "'.");791}792}793if (!exported) {794ERR_PRINT("Cannot determine architecture for library \"" + p_so.path + "\". One of the supported architectures must be used as a tag: " + join_abis(abis, " ", true));795return FAILED;796}797return OK;798}799800Error EditorExportPlatformAndroid::save_apk_file(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) {801APKExportData *ed = static_cast<APKExportData *>(p_userdata);802803String simplified_path = p_path.simplify_path();804if (simplified_path.begins_with("uid://")) {805simplified_path = ResourceUID::uid_to_path(simplified_path).simplify_path();806print_verbose(vformat(R"(UID referenced exported file name "%s" was replaced with "%s".)", p_path, simplified_path));807}808809Vector<uint8_t> enc_data;810EditorExportPlatform::SavedData sd;811Error err = _store_temp_file(simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, enc_data, sd);812if (err != OK) {813return err;814}815816const String dst_path = String("assets/") + simplified_path.trim_prefix("res://");817print_verbose("Saving project files from " + simplified_path + " into " + dst_path);818store_in_apk(ed, dst_path, enc_data, _should_compress_asset(simplified_path, enc_data) ? Z_DEFLATED : 0);819820ed->pd.file_ofs.push_back(sd);821822return OK;823}824825Error EditorExportPlatformAndroid::ignore_apk_file(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) {826return OK;827}828829Error EditorExportPlatformAndroid::copy_gradle_so(void *p_userdata, const SharedObject &p_so) {830ERR_FAIL_COND_V_MSG(!p_so.path.get_file().begins_with("lib"), FAILED,831"Android .so file names must start with \"lib\", but got: " + p_so.path);832Vector<ABI> abis = get_abis();833CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata);834bool exported = false;835for (int i = 0; i < p_so.tags.size(); ++i) {836int abi_index = -1;837for (int j = 0; j < abis.size(); ++j) {838if (abis[j].abi == p_so.tags[i] || abis[j].arch == p_so.tags[i]) {839abi_index = j;840break;841}842}843if (abi_index != -1) {844exported = true;845String type = export_data->debug ? "debug" : "release";846String abi = abis[abi_index].abi;847String filename = p_so.path.get_file();848String dst_path = export_data->libs_directory.path_join(type).path_join(abi).path_join(filename);849Vector<uint8_t> data = FileAccess::get_file_as_bytes(p_so.path);850print_verbose("Copying .so file from " + p_so.path + " to " + dst_path);851Error err = store_file_at_path(dst_path, data);852ERR_FAIL_COND_V_MSG(err, err, "Failed to copy .so file from " + p_so.path + " to " + dst_path);853export_data->libs.push_back(dst_path);854}855}856ERR_FAIL_COND_V_MSG(!exported, FAILED,857"Cannot determine architecture for library \"" + p_so.path + "\". One of the supported architectures must be used as a tag:" + join_abis(abis, " ", true));858return OK;859}860861bool EditorExportPlatformAndroid::_has_read_write_storage_permission(const Vector<String> &p_permissions) {862return p_permissions.has("android.permission.READ_EXTERNAL_STORAGE") || p_permissions.has("android.permission.WRITE_EXTERNAL_STORAGE");863}864865bool EditorExportPlatformAndroid::_has_manage_external_storage_permission(const Vector<String> &p_permissions) {866return p_permissions.has("android.permission.MANAGE_EXTERNAL_STORAGE");867}868869bool EditorExportPlatformAndroid::_uses_vulkan(const Ref<EditorExportPreset> &p_preset) const {870String rendering_method = get_project_setting(p_preset, "rendering/renderer/rendering_method.mobile");871String rendering_driver = get_project_setting(p_preset, "rendering/rendering_device/driver.android");872return (rendering_method == "forward_plus" || rendering_method == "mobile") && rendering_driver == "vulkan";873}874875void EditorExportPlatformAndroid::_notification(int p_what) {876#ifndef ANDROID_ENABLED877switch (p_what) {878case NOTIFICATION_POSTINITIALIZE: {879if (EditorExport::get_singleton()) {880EditorExport::get_singleton()->connect_presets_runnable_updated(callable_mp(this, &EditorExportPlatformAndroid::_update_preset_status));881}882} break;883884case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {885if (EditorSettings::get_singleton()->check_changed_settings_in_group("export/android")) {886_create_editor_debug_keystore_if_needed();887}888} break;889}890#endif891}892893void EditorExportPlatformAndroid::_create_editor_debug_keystore_if_needed() {894// Check if we have a valid keytool path.895String keytool_path = get_keytool_path();896if (!FileAccess::exists(keytool_path)) {897return;898}899900// Check if the current editor debug keystore exists.901String editor_debug_keystore = EDITOR_GET("export/android/debug_keystore");902if (FileAccess::exists(editor_debug_keystore)) {903return;904}905906// Generate the debug keystore.907String keystore_path = EditorPaths::get_singleton()->get_debug_keystore_path();908String keystores_dir = keystore_path.get_base_dir();909if (!DirAccess::exists(keystores_dir)) {910Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);911Error err = dir_access->make_dir_recursive(keystores_dir);912if (err != OK) {913WARN_PRINT(TTR("Error creating keystores directory:") + "\n" + keystores_dir);914return;915}916}917918if (!FileAccess::exists(keystore_path)) {919String output;920List<String> args;921args.push_back("-genkey");922args.push_back("-keystore");923args.push_back(keystore_path);924args.push_back("-storepass");925args.push_back("android");926args.push_back("-alias");927args.push_back(DEFAULT_ANDROID_KEYSTORE_DEBUG_USER);928args.push_back("-keypass");929args.push_back(DEFAULT_ANDROID_KEYSTORE_DEBUG_PASSWORD);930args.push_back("-keyalg");931args.push_back("RSA");932args.push_back("-keysize");933args.push_back("2048");934args.push_back("-validity");935args.push_back("10000");936args.push_back("-dname");937args.push_back("cn=Godot, ou=Godot Engine, o=Stichting Godot, c=NL");938Error error = OS::get_singleton()->execute(keytool_path, args, &output, nullptr, true);939print_verbose(output);940if (error != OK) {941WARN_PRINT("Error: Unable to create debug keystore");942return;943}944}945946// Update the editor settings.947EditorSettings::get_singleton()->set("export/android/debug_keystore", keystore_path);948EditorSettings::get_singleton()->set("export/android/debug_keystore_user", DEFAULT_ANDROID_KEYSTORE_DEBUG_USER);949EditorSettings::get_singleton()->set("export/android/debug_keystore_pass", DEFAULT_ANDROID_KEYSTORE_DEBUG_PASSWORD);950print_verbose("Updated editor debug keystore to " + keystore_path);951}952953void EditorExportPlatformAndroid::_get_manifest_info(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, Vector<String> &r_permissions, Vector<FeatureInfo> &r_features, Vector<MetadataInfo> &r_metadata) {954const char **aperms = ANDROID_PERMS;955while (*aperms) {956bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());957if (enabled) {958r_permissions.push_back("android.permission." + String(*aperms));959}960aperms++;961}962PackedStringArray user_perms = p_preset->get("permissions/custom_permissions");963for (int i = 0; i < user_perms.size(); i++) {964String user_perm = user_perms[i].strip_edges();965if (!user_perm.is_empty()) {966r_permissions.push_back(user_perm);967}968}969if (p_give_internet) {970if (!r_permissions.has("android.permission.INTERNET")) {971r_permissions.push_back("android.permission.INTERNET");972}973}974975if (_uses_vulkan(p_preset)) {976// Require vulkan hardware level 1 support977FeatureInfo vulkan_level = {978"android.hardware.vulkan.level", // name979false, // required980"1" // version981};982r_features.append(vulkan_level);983984// Require vulkan version 1.0985FeatureInfo vulkan_version = {986"android.hardware.vulkan.version", // name987true, // required988"0x400003" // version - Encoded value for api version 1.0989};990r_features.append(vulkan_version);991}992993MetadataInfo rendering_method_metadata = {994"org.godotengine.rendering.method",995p_preset->get_project_setting("rendering/renderer/rendering_method.mobile")996};997r_metadata.append(rendering_method_metadata);998999MetadataInfo editor_version_metadata = {1000"org.godotengine.editor.version",1001String(GODOT_VERSION_FULL_CONFIG)1002};1003r_metadata.append(editor_version_metadata);1004}10051006void EditorExportPlatformAndroid::_write_tmp_manifest(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, bool p_debug) {1007print_verbose("Building temporary manifest...");1008String manifest_text =1009"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"1010"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"1011" xmlns:tools=\"http://schemas.android.com/tools\">\n";10121013manifest_text += _get_screen_sizes_tag(p_preset);1014manifest_text += _get_gles_tag();10151016Vector<String> perms;1017Vector<FeatureInfo> features;1018Vector<MetadataInfo> manifest_metadata;1019_get_manifest_info(p_preset, p_give_internet, perms, features, manifest_metadata);1020for (int i = 0; i < perms.size(); i++) {1021String permission = perms.get(i);1022if (permission == "android.permission.WRITE_EXTERNAL_STORAGE" || (permission == "android.permission.READ_EXTERNAL_STORAGE" && _has_manage_external_storage_permission(perms))) {1023manifest_text += vformat(" <uses-permission android:name=\"%s\" android:maxSdkVersion=\"29\" />\n", permission);1024} else {1025manifest_text += vformat(" <uses-permission android:name=\"%s\" />\n", permission);1026}1027}10281029for (int i = 0; i < features.size(); i++) {1030manifest_text += vformat(" <uses-feature tools:node=\"replace\" android:name=\"%s\" android:required=\"%s\" android:version=\"%s\" />\n", features[i].name, features[i].required, features[i].version);1031}10321033Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();1034for (int i = 0; i < export_plugins.size(); i++) {1035if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {1036const String contents = export_plugins[i]->get_android_manifest_element_contents(Ref<EditorExportPlatform>(this), p_debug);1037if (!contents.is_empty()) {1038manifest_text += contents;1039manifest_text += "\n";1040}1041}1042}10431044manifest_text += _get_application_tag(Ref<EditorExportPlatform>(this), p_preset, _has_read_write_storage_permission(perms), p_debug, manifest_metadata);1045manifest_text += "</manifest>\n";1046String manifest_path = ExportTemplateManager::get_android_build_directory(p_preset).path_join(vformat("src/%s/AndroidManifest.xml", (p_debug ? "debug" : "release")));10471048print_verbose("Storing manifest into " + manifest_path + ": " + "\n" + manifest_text);1049store_string_at_path(manifest_path, manifest_text);1050}10511052bool EditorExportPlatformAndroid::_is_transparency_allowed(const Ref<EditorExportPreset> &p_preset) const {1053return (bool)get_project_setting(p_preset, "display/window/per_pixel_transparency/allowed");1054}10551056void EditorExportPlatformAndroid::_fix_themes_xml(const Ref<EditorExportPreset> &p_preset) {1057const String themes_xml_path = ExportTemplateManager::get_android_build_directory(p_preset).path_join("res/values/themes.xml");10581059if (!FileAccess::exists(themes_xml_path)) {1060print_error("res/values/themes.xml does not exist.");1061return;1062}10631064bool transparency_allowed = _is_transparency_allowed(p_preset);10651066// Default/Reserved theme attributes.1067Dictionary main_theme_attributes;1068main_theme_attributes["android:windowSwipeToDismiss"] = bool_to_string(p_preset->get("gesture/swipe_to_dismiss"));1069main_theme_attributes["android:windowIsTranslucent"] = bool_to_string(transparency_allowed);1070if (transparency_allowed) {1071main_theme_attributes["android:windowBackground"] = "@android:color/transparent";1072} else {1073main_theme_attributes["android:windowBackground"] = "#" + p_preset->get("screen/background_color").operator Color().to_html(false);1074}10751076Dictionary splash_theme_attributes;1077splash_theme_attributes["android:windowSplashScreenBackground"] = "@mipmap/icon_background";1078splash_theme_attributes["windowSplashScreenAnimatedIcon"] = "@mipmap/icon_foreground";1079splash_theme_attributes["postSplashScreenTheme"] = "@style/GodotAppMainTheme";1080splash_theme_attributes["android:windowIsTranslucent"] = bool_to_string(transparency_allowed);10811082PackedStringArray reserved_splash_keys;1083reserved_splash_keys.append("postSplashScreenTheme");1084reserved_splash_keys.append("android:windowIsTranslucent");10851086Dictionary custom_theme_attributes = p_preset->get("gradle_build/custom_theme_attributes");10871088// Does not override default/reserved theme attributes; skips any duplicates from custom_theme_attributes.1089for (const Variant &k : custom_theme_attributes.keys()) {1090String key = k;1091String value = custom_theme_attributes[k];1092if (key.begins_with("[splash]")) {1093String splash_key = key.trim_prefix("[splash]");1094if (reserved_splash_keys.has(splash_key)) {1095WARN_PRINT(vformat("Skipped custom_theme_attribute '%s'; this is a reserved attribute configured via other export options or project settings.", splash_key));1096} else {1097splash_theme_attributes[splash_key] = value;1098}1099} else {1100if (main_theme_attributes.has(key)) {1101WARN_PRINT(vformat("Skipped custom_theme_attribute '%s'; this is a reserved attribute configured via other export options or project settings.", key));1102} else {1103main_theme_attributes[key] = value;1104}1105}1106}11071108Ref<FileAccess> file = FileAccess::open(themes_xml_path, FileAccess::READ);1109PackedStringArray lines = file->get_as_text().split("\n");1110file->close();11111112PackedStringArray new_lines;1113bool inside_main_theme = false;1114bool inside_splash_theme = false;11151116for (int i = 0; i < lines.size(); i++) {1117String line = lines[i];11181119if (line.contains("<style name=\"GodotAppMainTheme\"")) {1120inside_main_theme = true;1121new_lines.append(line);1122continue;1123}1124if (line.contains("<style name=\"GodotAppSplashTheme\"")) {1125inside_splash_theme = true;1126new_lines.append(line);1127continue;1128}11291130// Inject GodotAppMainTheme attributes.1131if (inside_main_theme && line.contains("</style>")) {1132for (const Variant &attribute : main_theme_attributes.keys()) {1133String value = main_theme_attributes[attribute];1134String item_line = vformat(" <item name=\"%s\">%s</item>", attribute, value);1135new_lines.append(item_line);1136}1137new_lines.append(line); // Add </style> in the end.1138inside_main_theme = false;1139continue;1140}11411142// Inject GodotAppSplashTheme attributes.1143if (inside_splash_theme && line.contains("</style>")) {1144for (const Variant &attribute : splash_theme_attributes.keys()) {1145String value = splash_theme_attributes[attribute];1146String item_line = vformat(" <item name=\"%s\">%s</item>", attribute, value);1147new_lines.append(item_line);1148}1149new_lines.append(line); // Add </style> in the end.1150inside_splash_theme = false;1151continue;1152}11531154// Add all other lines unchanged.1155if (!inside_main_theme && !inside_splash_theme) {1156new_lines.append(line);1157}1158}11591160// Reconstruct the XML content from the modified lines.1161String xml_content = String("\n").join(new_lines);1162store_string_at_path(themes_xml_path, xml_content);1163print_verbose("Successfully modified " + themes_xml_path + ": " + "\n" + xml_content);1164}11651166void EditorExportPlatformAndroid::_fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {1167// Leaving the unused types commented because looking these constants up1168// again later would be annoying1169// const int CHUNK_AXML_FILE = 0x00080003;1170// const int CHUNK_RESOURCEIDS = 0x00080180;1171const int CHUNK_STRINGS = 0x001C0001;1172// const int CHUNK_XML_END_NAMESPACE = 0x00100101;1173const int CHUNK_XML_END_TAG = 0x00100103;1174// const int CHUNK_XML_START_NAMESPACE = 0x00100100;1175const int CHUNK_XML_START_TAG = 0x00100102;1176// const int CHUNK_XML_TEXT = 0x00100104;1177const int UTF8_FLAG = 0x00000100;11781179Vector<String> string_table;11801181uint32_t ofs = 8;11821183uint32_t string_count = 0;1184uint32_t string_flags = 0;1185uint32_t string_data_offset = 0;11861187uint32_t string_table_begins = 0;1188uint32_t string_table_ends = 0;1189Vector<uint8_t> stable_extra;11901191String version_name = p_preset->get_version("version/name");1192int version_code = p_preset->get("version/code");1193String package_name = p_preset->get("package/unique_name");11941195const int screen_orientation =1196_get_android_orientation_value(DisplayServer::ScreenOrientation(int(get_project_setting(p_preset, "display/window/handheld/orientation"))));11971198bool screen_support_small = p_preset->get("screen/support_small");1199bool screen_support_normal = p_preset->get("screen/support_normal");1200bool screen_support_large = p_preset->get("screen/support_large");1201bool screen_support_xlarge = p_preset->get("screen/support_xlarge");12021203bool backup_allowed = p_preset->get("user_data_backup/allow");1204int app_category = p_preset->get("package/app_category");1205bool retain_data_on_uninstall = p_preset->get("package/retain_data_on_uninstall");1206bool exclude_from_recents = p_preset->get("package/exclude_from_recents");1207bool is_resizeable = bool(get_project_setting(p_preset, "display/window/size/resizable"));12081209Vector<String> perms;1210Vector<FeatureInfo> features;1211Vector<MetadataInfo> manifest_metadata;1212_get_manifest_info(p_preset, p_give_internet, perms, features, manifest_metadata);1213bool has_read_write_storage_permission = _has_read_write_storage_permission(perms);12141215while (ofs < (uint32_t)p_manifest.size()) {1216uint32_t chunk = decode_uint32(&p_manifest[ofs]);1217uint32_t size = decode_uint32(&p_manifest[ofs + 4]);12181219switch (chunk) {1220case CHUNK_STRINGS: {1221int iofs = ofs + 8;12221223string_count = decode_uint32(&p_manifest[iofs]);1224string_flags = decode_uint32(&p_manifest[iofs + 8]);1225string_data_offset = decode_uint32(&p_manifest[iofs + 12]);12261227uint32_t st_offset = iofs + 20;1228string_table.resize(string_count);1229uint32_t string_end = 0;12301231string_table_begins = st_offset;12321233for (uint32_t i = 0; i < string_count; i++) {1234uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);1235string_at += st_offset + string_count * 4;12361237ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table.");12381239if (string_flags & UTF8_FLAG) {1240} else {1241uint32_t len = decode_uint16(&p_manifest[string_at]);1242Vector<char32_t> ucstring;1243ucstring.resize(len + 1);1244for (uint32_t j = 0; j < len; j++) {1245uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);1246ucstring.write[j] = c;1247}1248string_end = MAX(string_at + 2 + 2 * len, string_end);1249ucstring.write[len] = 0;1250string_table.write[i] = ucstring.ptr();1251}1252}12531254for (uint32_t i = string_end; i < (ofs + size); i++) {1255stable_extra.push_back(p_manifest[i]);1256}12571258string_table_ends = ofs + size;12591260} break;1261case CHUNK_XML_START_TAG: {1262int iofs = ofs + 8;1263uint32_t name = decode_uint32(&p_manifest[iofs + 12]);12641265String tname = string_table[name];1266uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);1267iofs += 28;12681269for (uint32_t i = 0; i < attrcount; i++) {1270uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);1271uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);1272uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);1273uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);12741275const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid);1276String attrname = string_table[attr_name];1277const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : "";12781279//replace project information1280if (tname == "manifest" && attrname == "package") {1281string_table.write[attr_value] = get_package_name(p_preset, package_name);1282}12831284if (tname == "manifest" && attrname == "versionCode") {1285encode_uint32(version_code, &p_manifest.write[iofs + 16]);1286}12871288if (tname == "manifest" && attrname == "versionName") {1289if (attr_value == 0xFFFFFFFF) {1290WARN_PRINT("Version name in a resource, should be plain text");1291} else {1292string_table.write[attr_value] = version_name;1293}1294}12951296if (tname == "application" && attrname == "requestLegacyExternalStorage") {1297encode_uint32(has_read_write_storage_permission ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);1298}12991300if (tname == "application" && attrname == "allowBackup") {1301encode_uint32(backup_allowed, &p_manifest.write[iofs + 16]);1302}13031304if (tname == "application" && attrname == "appCategory") {1305encode_uint32(_get_app_category_value(app_category), &p_manifest.write[iofs + 16]);1306}13071308if (tname == "application" && attrname == "isGame") {1309encode_uint32(app_category == APP_CATEGORY_GAME, &p_manifest.write[iofs + 16]);1310}13111312if (tname == "application" && attrname == "hasFragileUserData") {1313encode_uint32(retain_data_on_uninstall, &p_manifest.write[iofs + 16]);1314}13151316if (tname == "activity" && attrname == "screenOrientation") {1317encode_uint32(screen_orientation, &p_manifest.write[iofs + 16]);1318}13191320if (tname == "activity" && attrname == "excludeFromRecents") {1321encode_uint32(exclude_from_recents, &p_manifest.write[iofs + 16]);1322}13231324if (tname == "activity" && attrname == "resizeableActivity") {1325encode_uint32(is_resizeable, &p_manifest.write[iofs + 16]);1326}13271328if (tname == "provider" && attrname == "authorities") {1329string_table.write[attr_value] = get_package_name(p_preset, package_name) + String(".fileprovider");1330}13311332if (tname == "supports-screens") {1333if (attrname == "smallScreens") {1334encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);13351336} else if (attrname == "normalScreens") {1337encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);13381339} else if (attrname == "largeScreens") {1340encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);13411342} else if (attrname == "xlargeScreens") {1343encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);1344}1345}13461347iofs += 20;1348}13491350} break;1351case CHUNK_XML_END_TAG: {1352int iofs = ofs + 8;1353uint32_t name = decode_uint32(&p_manifest[iofs + 12]);1354String tname = string_table[name];13551356if (tname == "manifest" || tname == "application") {1357// save manifest ending so we can restore it1358Vector<uint8_t> manifest_end;1359uint32_t manifest_cur_size = p_manifest.size();13601361manifest_end.resize(p_manifest.size() - ofs);1362memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());13631364int32_t attr_name_string = string_table.find("name");1365ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");13661367int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android");1368if (ns_android_string == -1) {1369string_table.push_back("http://schemas.android.com/apk/res/android");1370ns_android_string = string_table.size() - 1;1371}13721373if (tname == "manifest") {1374// Updating manifest features1375int32_t attr_uses_feature_string = string_table.find("uses-feature");1376if (attr_uses_feature_string == -1) {1377string_table.push_back("uses-feature");1378attr_uses_feature_string = string_table.size() - 1;1379}13801381int32_t attr_required_string = string_table.find("required");1382if (attr_required_string == -1) {1383string_table.push_back("required");1384attr_required_string = string_table.size() - 1;1385}13861387for (int i = 0; i < features.size(); i++) {1388const String &feature_name = features[i].name;1389bool feature_required = features[i].required;1390String feature_version = features[i].version;1391bool has_version_attribute = !feature_version.is_empty();13921393print_line("Adding feature " + feature_name);13941395int32_t feature_string = string_table.find(feature_name);1396if (feature_string == -1) {1397string_table.push_back(feature_name);1398feature_string = string_table.size() - 1;1399}14001401String required_value_string = feature_required ? "true" : "false";1402int32_t required_value = string_table.find(required_value_string);1403if (required_value == -1) {1404string_table.push_back(required_value_string);1405required_value = string_table.size() - 1;1406}14071408int32_t attr_version_string = -1;1409int32_t version_value = -1;1410int tag_size;1411int attr_count;1412if (has_version_attribute) {1413attr_version_string = string_table.find("version");1414if (attr_version_string == -1) {1415string_table.push_back("version");1416attr_version_string = string_table.size() - 1;1417}14181419version_value = string_table.find(feature_version);1420if (version_value == -1) {1421string_table.push_back(feature_version);1422version_value = string_table.size() - 1;1423}14241425tag_size = 96; // node and three attrs + end node1426attr_count = 3;1427} else {1428tag_size = 76; // node and two attrs + end node1429attr_count = 2;1430}1431manifest_cur_size += tag_size + 24;1432p_manifest.resize(manifest_cur_size);14331434// start tag1435encode_uint16(0x102, &p_manifest.write[ofs]); // type1436encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1437encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size1438encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1439encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1440encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1441encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name1442encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start1443encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size1444encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs1445encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index1446encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index1447encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index14481449// android:name attribute1450encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns1451encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'1452encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value1453encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size1454p_manifest.write[ofs + 50] = 0; // typedvalue_always01455p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)1456encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference14571458// android:required attribute1459encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns1460encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name'1461encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value1462encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size1463p_manifest.write[ofs + 70] = 0; // typedvalue_always01464p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)1465encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference14661467ofs += 76;14681469if (has_version_attribute) {1470// android:version attribute1471encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns1472encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name'1473encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value1474encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size1475p_manifest.write[ofs + 14] = 0; // typedvalue_always01476p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string)1477encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference14781479ofs += 20;1480}14811482// end tag1483encode_uint16(0x103, &p_manifest.write[ofs]); // type1484encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1485encode_uint32(24, &p_manifest.write[ofs + 4]); // size1486encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1487encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1488encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1489encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name14901491ofs += 24;1492}14931494// Updating manifest permissions1495int32_t attr_uses_permission_string = string_table.find("uses-permission");1496if (attr_uses_permission_string == -1) {1497string_table.push_back("uses-permission");1498attr_uses_permission_string = string_table.size() - 1;1499}15001501for (int i = 0; i < perms.size(); ++i) {1502print_line("Adding permission " + perms[i]);15031504manifest_cur_size += 56 + 24; // node + end node1505p_manifest.resize(manifest_cur_size);15061507// Add permission to the string pool1508int32_t perm_string = string_table.find(perms[i]);1509if (perm_string == -1) {1510string_table.push_back(perms[i]);1511perm_string = string_table.size() - 1;1512}15131514// start tag1515encode_uint16(0x102, &p_manifest.write[ofs]); // type1516encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1517encode_uint32(56, &p_manifest.write[ofs + 4]); // size1518encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1519encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1520encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1521encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name1522encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start1523encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size1524encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs1525encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index1526encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index1527encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index15281529// attribute1530encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns1531encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'1532encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value1533encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size1534p_manifest.write[ofs + 50] = 0; // typedvalue_always01535p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)1536encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference15371538ofs += 56;15391540// end tag1541encode_uint16(0x103, &p_manifest.write[ofs]); // type1542encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1543encode_uint32(24, &p_manifest.write[ofs + 4]); // size1544encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1545encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1546encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1547encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name15481549ofs += 24;1550}1551}15521553if (tname == "application") {1554// Updating application meta-data1555int32_t attr_meta_data_string = string_table.find("meta-data");1556if (attr_meta_data_string == -1) {1557string_table.push_back("meta-data");1558attr_meta_data_string = string_table.size() - 1;1559}15601561int32_t attr_value_string = string_table.find("value");1562if (attr_value_string == -1) {1563string_table.push_back("value");1564attr_value_string = string_table.size() - 1;1565}15661567for (int i = 0; i < manifest_metadata.size(); i++) {1568String meta_data_name = manifest_metadata[i].name;1569String meta_data_value = manifest_metadata[i].value;15701571print_line("Adding application metadata " + meta_data_name);15721573int32_t meta_data_name_string = string_table.find(meta_data_name);1574if (meta_data_name_string == -1) {1575string_table.push_back(meta_data_name);1576meta_data_name_string = string_table.size() - 1;1577}15781579int32_t meta_data_value_string = string_table.find(meta_data_value);1580if (meta_data_value_string == -1) {1581string_table.push_back(meta_data_value);1582meta_data_value_string = string_table.size() - 1;1583}15841585int tag_size = 76; // node and two attrs + end node1586int attr_count = 2;1587manifest_cur_size += tag_size + 24;1588p_manifest.resize(manifest_cur_size);15891590// start tag1591encode_uint16(0x102, &p_manifest.write[ofs]); // type1592encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1593encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size1594encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1595encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1596encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1597encode_uint32(attr_meta_data_string, &p_manifest.write[ofs + 20]); // name1598encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start1599encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size1600encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs1601encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index1602encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index1603encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index16041605// android:name attribute1606encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns1607encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'1608encode_uint32(meta_data_name_string, &p_manifest.write[ofs + 44]); // raw_value1609encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size1610p_manifest.write[ofs + 50] = 0; // typedvalue_always01611p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)1612encode_uint32(meta_data_name_string, &p_manifest.write[ofs + 52]); // typedvalue reference16131614// android:value attribute1615encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns1616encode_uint32(attr_value_string, &p_manifest.write[ofs + 60]); // 'value'1617encode_uint32(meta_data_value_string, &p_manifest.write[ofs + 64]); // raw_value1618encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size1619p_manifest.write[ofs + 70] = 0; // typedvalue_always01620p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)1621encode_uint32(meta_data_value_string, &p_manifest.write[ofs + 72]); // typedvalue reference16221623ofs += 76;16241625// end tag1626encode_uint16(0x103, &p_manifest.write[ofs]); // type1627encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize1628encode_uint32(24, &p_manifest.write[ofs + 4]); // size1629encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno1630encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment1631encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns1632encode_uint32(attr_meta_data_string, &p_manifest.write[ofs + 20]); // name16331634ofs += 24;1635}1636}16371638// copy footer back in1639memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());1640}1641} break;1642}16431644ofs += size;1645}16461647// Create new android manifest binary.16481649Vector<uint8_t> ret;1650ret.resize(string_table_begins + string_table.size() * 4);16511652for (uint32_t i = 0; i < string_table_begins; i++) {1653ret.write[i] = p_manifest[i];1654}16551656ofs = 0;1657for (int i = 0; i < string_table.size(); i++) {1658encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);1659ofs += string_table[i].length() * 2 + 2 + 2;1660}16611662ret.resize(ret.size() + ofs);1663string_data_offset = ret.size() - ofs;1664uint8_t *chars = &ret.write[string_data_offset];1665for (int i = 0; i < string_table.size(); i++) {1666String s = string_table[i];1667encode_uint16(s.length(), chars);1668chars += 2;1669for (int j = 0; j < s.length(); j++) {1670encode_uint16(s[j], chars);1671chars += 2;1672}1673encode_uint16(0, chars);1674chars += 2;1675}16761677for (int i = 0; i < stable_extra.size(); i++) {1678ret.push_back(stable_extra[i]);1679}16801681//pad1682while (ret.size() % 4) {1683ret.push_back(0);1684}16851686uint32_t new_stable_end = ret.size();16871688uint32_t extra = (p_manifest.size() - string_table_ends);1689ret.resize(new_stable_end + extra);1690for (uint32_t i = 0; i < extra; i++) {1691ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];1692}16931694while (ret.size() % 4) {1695ret.push_back(0);1696}1697encode_uint32(ret.size(), &ret.write[4]); //update new file size16981699encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size1700encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings1701encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset17021703p_manifest = ret;1704}17051706String EditorExportPlatformAndroid::_get_keystore_path(const Ref<EditorExportPreset> &p_preset, bool p_debug) {1707String keystore_preference = p_debug ? "keystore/debug" : "keystore/release";1708String keystore_env_variable = p_debug ? ENV_ANDROID_KEYSTORE_DEBUG_PATH : ENV_ANDROID_KEYSTORE_RELEASE_PATH;1709String keystore_path = p_preset->get_or_env(keystore_preference, keystore_env_variable);17101711return ProjectSettings::get_singleton()->globalize_path(keystore_path).simplify_path();1712}17131714String EditorExportPlatformAndroid::_parse_string(const uint8_t *p_bytes, bool p_utf8) {1715uint32_t offset = 0;1716uint32_t len = 0;17171718if (p_utf8) {1719uint8_t byte = p_bytes[offset];1720if (byte & 0x80) {1721offset += 2;1722} else {1723offset += 1;1724}1725byte = p_bytes[offset];1726offset++;1727if (byte & 0x80) {1728len = byte & 0x7F;1729len = (len << 8) + p_bytes[offset];1730offset++;1731} else {1732len = byte;1733}1734} else {1735len = decode_uint16(&p_bytes[offset]);1736offset += 2;1737if (len & 0x8000) {1738len &= 0x7FFF;1739len = (len << 16) + decode_uint16(&p_bytes[offset]);1740offset += 2;1741}1742}17431744if (p_utf8) {1745Vector<uint8_t> str8;1746str8.resize(len + 1);1747for (uint32_t i = 0; i < len; i++) {1748str8.write[i] = p_bytes[offset + i];1749}1750str8.write[len] = 0;1751return String::utf8((const char *)str8.ptr(), len);1752} else {1753String str;1754for (uint32_t i = 0; i < len; i++) {1755char32_t c = decode_uint16(&p_bytes[offset + i * 2]);1756if (c == 0) {1757break;1758}1759str += String::chr(c);1760}1761return str;1762}1763}17641765void EditorExportPlatformAndroid::_fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &r_manifest) {1766const int UTF8_FLAG = 0x00000100;17671768uint32_t string_block_len = decode_uint32(&r_manifest[16]);1769uint32_t string_count = decode_uint32(&r_manifest[20]);1770uint32_t string_flags = decode_uint32(&r_manifest[28]);1771const uint32_t string_table_begins = 40;17721773Vector<String> string_table;17741775String package_name = p_preset->get("package/name");1776Dictionary appnames = get_project_setting(p_preset, "application/config/name_localized");17771778for (uint32_t i = 0; i < string_count; i++) {1779uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]);1780offset += string_table_begins + string_count * 4;17811782String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG);17831784if (str.begins_with("godot-project-name")) {1785if (str == "godot-project-name") {1786//project name1787str = get_project_name(p_preset, package_name);17881789} else {1790String lang = str.substr(str.rfind_char('-') + 1).replace_char('-', '_');1791if (appnames.has(lang)) {1792str = appnames[lang];1793} else {1794str = get_project_name(p_preset, package_name);1795}1796}1797}17981799string_table.push_back(str);1800}18011802//write a new string table, but use 16 bits1803Vector<uint8_t> ret;1804ret.resize(string_table_begins + string_table.size() * 4);18051806for (uint32_t i = 0; i < string_table_begins; i++) {1807ret.write[i] = r_manifest[i];1808}18091810int ofs = 0;1811for (int i = 0; i < string_table.size(); i++) {1812encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);1813ofs += string_table[i].length() * 2 + 2 + 2;1814}18151816ret.resize(ret.size() + ofs);1817uint8_t *chars = &ret.write[ret.size() - ofs];1818for (int i = 0; i < string_table.size(); i++) {1819String s = string_table[i];1820encode_uint16(s.length(), chars);1821chars += 2;1822for (int j = 0; j < s.length(); j++) {1823encode_uint16(s[j], chars);1824chars += 2;1825}1826encode_uint16(0, chars);1827chars += 2;1828}18291830//pad1831while (ret.size() % 4) {1832ret.push_back(0);1833}18341835//change flags to not use utf81836encode_uint32(string_flags & ~0x100, &ret.write[28]);1837//change length1838encode_uint32(ret.size() - 12, &ret.write[16]);1839//append the rest...1840int rest_from = 12 + string_block_len;1841int rest_to = ret.size();1842int rest_len = (r_manifest.size() - rest_from);1843ret.resize(ret.size() + (r_manifest.size() - rest_from));1844for (int i = 0; i < rest_len; i++) {1845ret.write[rest_to + i] = r_manifest[rest_from + i];1846}1847//finally update the size1848encode_uint32(ret.size(), &ret.write[4]);18491850r_manifest = ret;1851//printf("end\n");1852}18531854void EditorExportPlatformAndroid::_load_image_data(const Ref<Image> &p_splash_image, Vector<uint8_t> &p_data) {1855Vector<uint8_t> png_buffer;1856Error err = PNGDriverCommon::image_to_png(p_splash_image, png_buffer);1857if (err == OK) {1858p_data.resize(png_buffer.size());1859memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());1860} else {1861String err_str = String("Failed to convert splash image to png.");1862WARN_PRINT(err_str.utf8().get_data());1863}1864}18651866void EditorExportPlatformAndroid::_process_launcher_icons(const String &p_file_name, const Ref<Image> &p_source_image, int dimension, Vector<uint8_t> &p_data) {1867Ref<Image> working_image = p_source_image;18681869if (p_source_image->get_width() != dimension || p_source_image->get_height() != dimension) {1870working_image = p_source_image->duplicate();1871working_image->resize(dimension, dimension, Image::Interpolation::INTERPOLATE_LANCZOS);1872}18731874Vector<uint8_t> png_buffer;1875Error err = PNGDriverCommon::image_to_png(working_image, png_buffer);1876if (err == OK) {1877p_data.resize(png_buffer.size());1878memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());1879} else {1880String err_str = String("Failed to convert resized icon (") + p_file_name + ") to png.";1881WARN_PRINT(err_str.utf8().get_data());1882}1883}18841885void EditorExportPlatformAndroid::load_icon_refs(const Ref<EditorExportPreset> &p_preset, Ref<Image> &icon, Ref<Image> &foreground, Ref<Image> &background, Ref<Image> &monochrome) {1886String project_icon_path = get_project_setting(p_preset, "application/config/icon");18871888Error err = OK;18891890// Regular icon: user selection -> project icon -> default.1891String path = static_cast<String>(p_preset->get(LAUNCHER_ICON_OPTION)).strip_edges();1892print_verbose("Loading regular icon from " + path);1893if (!path.is_empty()) {1894icon = _load_icon_or_splash_image(path, &err);1895}1896if (path.is_empty() || err != OK || icon.is_null() || icon->is_empty()) {1897print_verbose("- falling back to project icon: " + project_icon_path);1898if (!project_icon_path.is_empty()) {1899icon = _load_icon_or_splash_image(project_icon_path, &err);1900} else {1901ERR_PRINT("No project icon specified. Please specify one in the Project Settings under Application -> Config -> Icon");1902}1903}19041905// Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default).1906path = static_cast<String>(p_preset->get(LAUNCHER_ADAPTIVE_ICON_FOREGROUND_OPTION)).strip_edges();1907print_verbose("Loading adaptive foreground icon from " + path);1908if (!path.is_empty()) {1909foreground = _load_icon_or_splash_image(path, &err);1910}1911if (path.is_empty() || err != OK || foreground.is_null() || foreground->is_empty()) {1912print_verbose("- falling back to using the regular icon");1913foreground = icon;1914}19151916// Adaptive background: user selection -> default.1917path = static_cast<String>(p_preset->get(LAUNCHER_ADAPTIVE_ICON_BACKGROUND_OPTION)).strip_edges();1918if (!path.is_empty()) {1919print_verbose("Loading adaptive background icon from " + path);1920background = _load_icon_or_splash_image(path, &err);1921}19221923// Adaptive monochrome: user selection -> default.1924path = static_cast<String>(p_preset->get(LAUNCHER_ADAPTIVE_ICON_MONOCHROME_OPTION)).strip_edges();1925if (!path.is_empty()) {1926print_verbose("Loading adaptive monochrome icon from " + path);1927monochrome = _load_icon_or_splash_image(path, &err);1928}1929}19301931void EditorExportPlatformAndroid::_copy_icons_to_gradle_project(const Ref<EditorExportPreset> &p_preset,1932const Ref<Image> &p_main_image,1933const Ref<Image> &p_foreground,1934const Ref<Image> &p_background,1935const Ref<Image> &p_monochrome) {1936String gradle_build_dir = ExportTemplateManager::get_android_build_directory(p_preset);19371938String monochrome_tag = "";19391940// Prepare images to be resized for the icons. If some image ends up being uninitialized,1941// the default image from the export template will be used.19421943for (int i = 0; i < ICON_DENSITIES_COUNT; ++i) {1944if (p_main_image.is_valid() && !p_main_image->is_empty()) {1945print_verbose("Processing launcher icon for dimension " + itos(LAUNCHER_ICONS[i].dimensions) + " into " + LAUNCHER_ICONS[i].export_path);1946Vector<uint8_t> data;1947_process_launcher_icons(LAUNCHER_ICONS[i].export_path, p_main_image, LAUNCHER_ICONS[i].dimensions, data);1948store_file_at_path(gradle_build_dir.path_join(LAUNCHER_ICONS[i].export_path), data);1949}19501951if (p_foreground.is_valid() && !p_foreground->is_empty()) {1952print_verbose("Processing launcher adaptive icon p_foreground for dimension " + itos(LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].dimensions) + " into " + LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].export_path);1953Vector<uint8_t> data;1954_process_launcher_icons(LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].export_path, p_foreground,1955LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].dimensions, data);1956store_file_at_path(gradle_build_dir.path_join(LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].export_path), data);1957}19581959if (p_background.is_valid() && !p_background->is_empty()) {1960print_verbose("Processing launcher adaptive icon p_background for dimension " + itos(LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].dimensions) + " into " + LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].export_path);1961Vector<uint8_t> data;1962_process_launcher_icons(LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].export_path, p_background,1963LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].dimensions, data);1964store_file_at_path(gradle_build_dir.path_join(LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].export_path), data);1965}19661967if (p_monochrome.is_valid() && !p_monochrome->is_empty()) {1968print_verbose("Processing launcher adaptive icon p_monochrome for dimension " + itos(LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].dimensions) + " into " + LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].export_path);1969Vector<uint8_t> data;1970_process_launcher_icons(LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].export_path, p_monochrome,1971LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].dimensions, data);1972store_file_at_path(gradle_build_dir.path_join(LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].export_path), data);1973monochrome_tag = " <monochrome android:drawable=\"@mipmap/icon_monochrome\"/>\n";1974}1975}19761977// Finalize the icon.xml by formatting the template with the optional monochrome tag.1978store_string_at_path(gradle_build_dir.path_join(ICON_XML_PATH), vformat(ICON_XML_TEMPLATE, monochrome_tag));1979}19801981Vector<EditorExportPlatformAndroid::ABI> EditorExportPlatformAndroid::get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {1982Vector<ABI> abis = get_abis();1983Vector<ABI> enabled_abis;1984for (int i = 0; i < abis.size(); ++i) {1985bool is_enabled = p_preset->get("architectures/" + abis[i].abi);1986if (is_enabled) {1987enabled_abis.push_back(abis[i]);1988}1989}1990return enabled_abis;1991}19921993void EditorExportPlatformAndroid::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const {1994r_features->push_back("etc2");1995r_features->push_back("astc");19961997if (p_preset->get("shader_baker/enabled")) {1998r_features->push_back("shader_baker");1999}20002001Vector<ABI> abis = get_enabled_abis(p_preset);2002for (int i = 0; i < abis.size(); ++i) {2003r_features->push_back(abis[i].arch);2004}2005}20062007String EditorExportPlatformAndroid::get_export_option_warning(const EditorExportPreset *p_preset, const StringName &p_name) const {2008if (p_preset) {2009if (p_name == ("apk_expansion/public_key")) {2010bool apk_expansion = p_preset->get("apk_expansion/enable");2011String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");2012if (apk_expansion && apk_expansion_pkey.is_empty()) {2013return TTR("Invalid public key for APK expansion.");2014}2015} else if (p_name == "package/unique_name") {2016String pn = p_preset->get("package/unique_name");2017String pn_err;20182019if (!is_package_name_valid(Ref<EditorExportPreset>(p_preset), pn, &pn_err)) {2020return TTR("Invalid package name:") + " " + pn_err;2021}2022} else if (p_name == "gesture/swipe_to_dismiss") {2023bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2024if (bool(p_preset->get("gesture/swipe_to_dismiss")) && !gradle_build_enabled) {2025return TTR("\"Use Gradle Build\" is required to enable \"Swipe to dismiss\".");2026}2027} else if (p_name == "gradle_build/use_gradle_build") {2028bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2029String enabled_deprecated_plugins_names = _get_deprecated_plugins_names(Ref<EditorExportPreset>(p_preset));2030if (!enabled_deprecated_plugins_names.is_empty() && !gradle_build_enabled) {2031return TTR("\"Use Gradle Build\" must be enabled to use the plugins.");2032}2033} else if (p_name == "gradle_build/compress_native_libraries") {2034bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2035if (bool(p_preset->get("gradle_build/compress_native_libraries")) && !gradle_build_enabled) {2036return TTR("\"Compress Native Libraries\" is only valid when \"Use Gradle Build\" is enabled.");2037}2038} else if (p_name == "gradle_build/export_format") {2039bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2040if (int(p_preset->get("gradle_build/export_format")) == EXPORT_FORMAT_AAB && !gradle_build_enabled) {2041return TTR("\"Export AAB\" is only valid when \"Use Gradle Build\" is enabled.");2042}2043} else if (p_name == "gradle_build/min_sdk") {2044String min_sdk_str = p_preset->get("gradle_build/min_sdk");2045bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2046if (!min_sdk_str.is_empty()) { // Empty means no override, nothing to do.2047if (!gradle_build_enabled) {2048return TTR("\"Min SDK\" can only be overridden when \"Use Gradle Build\" is enabled.");2049}2050if (!min_sdk_str.is_valid_int()) {2051return vformat(TTR("\"Min SDK\" should be a valid integer, but got \"%s\" which is invalid."), min_sdk_str);2052} else {2053int min_sdk_int = min_sdk_str.to_int();2054if (min_sdk_int < DEFAULT_MIN_SDK_VERSION) {2055return vformat(TTR("\"Min SDK\" cannot be lower than %d, which is the version needed by the Godot library."), DEFAULT_MIN_SDK_VERSION);2056}2057}2058}2059} else if (p_name == "gradle_build/target_sdk") {2060String target_sdk_str = p_preset->get("gradle_build/target_sdk");2061int target_sdk_int = DEFAULT_TARGET_SDK_VERSION;20622063String min_sdk_str = p_preset->get("gradle_build/min_sdk");2064int min_sdk_int = DEFAULT_MIN_SDK_VERSION;2065if (min_sdk_str.is_valid_int()) {2066min_sdk_int = min_sdk_str.to_int();2067}2068bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2069if (!target_sdk_str.is_empty()) { // Empty means no override, nothing to do.2070if (!gradle_build_enabled) {2071return TTR("\"Target SDK\" can only be overridden when \"Use Gradle Build\" is enabled.");2072}2073if (!target_sdk_str.is_valid_int()) {2074return vformat(TTR("\"Target SDK\" should be a valid integer, but got \"%s\" which is invalid."), target_sdk_str);2075} else {2076target_sdk_int = target_sdk_str.to_int();2077if (target_sdk_int < min_sdk_int) {2078return TTR("\"Target SDK\" version must be greater or equal to \"Min SDK\" version.");2079}2080}2081}2082} else if (p_name == "gradle_build/custom_theme_attributes") {2083bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2084if (bool(p_preset->get("gradle_build/custom_theme_attributes")) && !gradle_build_enabled) {2085return TTR("\"Use Gradle Build\" is required to add custom theme attributes.");2086}2087} else if (p_name == "package/show_in_android_tv") {2088bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2089if (bool(p_preset->get("package/show_in_android_tv")) && !gradle_build_enabled) {2090return TTR("\"Use Gradle Build\" must be enabled to enable \"Show In Android Tv\".");2091}2092} else if (p_name == "package/show_as_launcher_app") {2093bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2094if (bool(p_preset->get("package/show_as_launcher_app")) && !gradle_build_enabled) {2095return TTR("\"Use Gradle Build\" must be enabled to enable \"Show As Launcher App\".");2096}2097} else if (p_name == "package/show_in_app_library") {2098bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2099if (!bool(p_preset->get("package/show_in_app_library")) && !gradle_build_enabled) {2100return TTR("\"Use Gradle Build\" must be enabled to disable \"Show In App Library\".");2101}2102} else if (p_name == "shader_baker/enabled" && bool(p_preset->get("shader_baker/enabled"))) {2103String export_renderer = GLOBAL_GET("rendering/renderer/rendering_method.mobile");2104if (OS::get_singleton()->get_current_rendering_method() == "gl_compatibility") {2105return TTR("\"Shader Baker\" is not supported when using the Compatibility renderer.");2106} else if (OS::get_singleton()->get_current_rendering_method() != export_renderer) {2107return vformat(TTR("The editor is currently using a different renderer than what the target platform will use. \"Shader Baker\" won't be able to include core shaders. Switch to the \"%s\" renderer temporarily to fix this."), export_renderer);2108}2109}2110}2111return String();2112}21132114void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_options) const {2115r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));2116r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));21172118r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "gradle_build/use_gradle_build"), false, true, true));2119r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "gradle_build/gradle_build_directory", PROPERTY_HINT_PLACEHOLDER_TEXT, "res://android"), "", false, false));2120r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "gradle_build/android_source_template", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));2121r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "gradle_build/compress_native_libraries"), false, false, true));2122r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "gradle_build/export_format", PROPERTY_HINT_ENUM, "Export APK,Export AAB"), EXPORT_FORMAT_APK, false, true));2123// Using String instead of int to default to an empty string (no override) with placeholder for instructions (see GH-62465).2124// This implies doing validation that the string is a proper int.2125r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "gradle_build/min_sdk", PROPERTY_HINT_PLACEHOLDER_TEXT, vformat("%d (default)", DEFAULT_MIN_SDK_VERSION)), "", false, true));2126r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "gradle_build/target_sdk", PROPERTY_HINT_PLACEHOLDER_TEXT, vformat("%d (default)", DEFAULT_TARGET_SDK_VERSION)), "", false, true));21272128r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, "gradle_build/custom_theme_attributes", PROPERTY_HINT_DICTIONARY_TYPE, "String;String"), Dictionary()));21292130#ifndef DISABLE_DEPRECATED2131Vector<PluginConfigAndroid> plugins_configs = get_plugins();2132for (int i = 0; i < plugins_configs.size(); i++) {2133print_verbose("Found Android plugin " + plugins_configs[i].name);2134r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("plugins"), plugins_configs[i].name)), false));2135}2136android_plugins_changed.clear();2137#endif // DISABLE_DEPRECATED21382139// Android supports multiple architectures in an app bundle, so2140// we expose each option as a checkbox in the export dialog.2141const Vector<ABI> abis = get_abis();2142for (int i = 0; i < abis.size(); ++i) {2143const String abi = abis[i].abi;2144// All Android devices supporting Vulkan run 64-bit Android,2145// so there is usually no point in exporting for 32-bit Android.2146const bool is_default = abi == "arm64-v8a";2147r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("architectures"), abi)), is_default));2148}21492150r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));2151r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));2152r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password", PROPERTY_HINT_PASSWORD, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));2153r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));2154r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));2155r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password", PROPERTY_HINT_PASSWORD, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SECRET), ""));21562157r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));2158r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Leave empty to use project version"), ""));21592160r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "com.example.$genname", false, true));2161r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));2162r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));2163r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "package/app_category", PROPERTY_HINT_ENUM, "Accessibility,Audio,Game,Image,Maps,News,Productivity,Social,Video,Undefined"), APP_CATEGORY_GAME));2164r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/retain_data_on_uninstall"), false));2165r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/exclude_from_recents"), false));2166r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/show_in_android_tv"), false));2167r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/show_in_app_library"), true));2168r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/show_as_launcher_app"), false));21692170r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, LAUNCHER_ICON_OPTION, PROPERTY_HINT_FILE, "*.png"), ""));2171r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, LAUNCHER_ADAPTIVE_ICON_FOREGROUND_OPTION, PROPERTY_HINT_FILE, "*.png"), ""));2172r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, LAUNCHER_ADAPTIVE_ICON_BACKGROUND_OPTION, PROPERTY_HINT_FILE, "*.png"), ""));2173r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, LAUNCHER_ADAPTIVE_ICON_MONOCHROME_OPTION, PROPERTY_HINT_FILE, "*.png"), ""));21742175r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/opengl_debug"), false));21762177r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "shader_baker/enabled"), false));21782179r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,OpenXR"), XR_MODE_REGULAR, false, true));21802181r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "gesture/swipe_to_dismiss"), false));21822183r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));2184r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/edge_to_edge"), false));2185r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));2186r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));2187r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));2188r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));2189r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "screen/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));21902191r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data_backup/allow"), false));21922193r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));21942195r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false, false, true));2196r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));2197r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), "", false, true));21982199r_options->push_back(ExportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "permissions/custom_permissions"), PackedStringArray()));22002201const char **perms = ANDROID_PERMS;2202while (*perms) {2203r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("permissions"), String(*perms).to_lower())), false));2204perms++;2205}2206}22072208bool EditorExportPlatformAndroid::get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option) const {2209if (p_preset == nullptr) {2210return true;2211}22122213bool advanced_options_enabled = p_preset->are_advanced_options_enabled();2214if (p_option == "graphics/opengl_debug" ||2215p_option == "gradle_build/custom_theme_attributes" ||2216p_option == "command_line/extra_args" ||2217p_option == "permissions/custom_permissions" ||2218p_option == "keystore/debug" ||2219p_option == "keystore/debug_user" ||2220p_option == "keystore/debug_password" ||2221p_option == "package/retain_data_on_uninstall" ||2222p_option == "package/exclude_from_recents" ||2223p_option == "package/show_in_app_library" ||2224p_option == "package/show_as_launcher_app" ||2225p_option == "gesture/swipe_to_dismiss" ||2226p_option == "apk_expansion/enable" ||2227p_option == "apk_expansion/SALT" ||2228p_option == "apk_expansion/public_key") {2229return advanced_options_enabled;2230}2231if (p_option == "gradle_build/gradle_build_directory" || p_option == "gradle_build/android_source_template") {2232return advanced_options_enabled && bool(p_preset->get("gradle_build/use_gradle_build"));2233}2234if (p_option == "custom_template/debug" || p_option == "custom_template/release") {2235// The APK templates are ignored if Gradle build is enabled.2236return advanced_options_enabled && !bool(p_preset->get("gradle_build/use_gradle_build"));2237}22382239// Hide .NET embedding option (always enabled).2240if (p_option == "dotnet/embed_build_outputs") {2241return false;2242}22432244if (p_option == "dotnet/android_use_linux_bionic") {2245return advanced_options_enabled;2246}2247return true;2248}22492250String EditorExportPlatformAndroid::get_name() const {2251return "Android";2252}22532254String EditorExportPlatformAndroid::get_os_name() const {2255return "Android";2256}22572258Ref<Texture2D> EditorExportPlatformAndroid::get_logo() const {2259return logo;2260}22612262bool EditorExportPlatformAndroid::should_update_export_options() {2263#ifndef DISABLE_DEPRECATED2264if (android_plugins_changed.is_set()) {2265// don't clear unless we're reporting true, to avoid race2266android_plugins_changed.clear();2267return true;2268}2269#endif // DISABLE_DEPRECATED2270return false;2271}22722273bool EditorExportPlatformAndroid::poll_export() {2274bool dc = devices_changed.is_set();2275if (dc) {2276// don't clear unless we're reporting true, to avoid race2277devices_changed.clear();2278}2279return dc;2280}22812282int EditorExportPlatformAndroid::get_options_count() const {2283MutexLock lock(device_lock);2284return devices.size();2285}22862287String EditorExportPlatformAndroid::get_options_tooltip() const {2288return TTR("Select device from the list");2289}22902291String EditorExportPlatformAndroid::get_option_label(int p_index) const {2292ERR_FAIL_INDEX_V(p_index, devices.size(), "");2293MutexLock lock(device_lock);2294return devices[p_index].name;2295}22962297String EditorExportPlatformAndroid::get_option_tooltip(int p_index) const {2298ERR_FAIL_INDEX_V(p_index, devices.size(), "");2299MutexLock lock(device_lock);2300String s = devices[p_index].description;2301if (devices.size() == 1) {2302// Tooltip will be:2303// Name2304// Description2305s = devices[p_index].name + "\n\n" + s;2306}2307return s;2308}23092310String EditorExportPlatformAndroid::get_device_architecture(int p_index) const {2311ERR_FAIL_INDEX_V(p_index, devices.size(), "");2312MutexLock lock(device_lock);2313return devices[p_index].architecture;2314}23152316Error EditorExportPlatformAndroid::run(const Ref<EditorExportPreset> &p_preset, int p_device, BitField<EditorExportPlatform::DebugFlags> p_debug_flags) {2317ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);23182319String can_export_error;2320bool can_export_missing_templates;2321if (!can_export(p_preset, can_export_error, can_export_missing_templates)) {2322add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), can_export_error);2323return ERR_UNCONFIGURED;2324}23252326MutexLock lock(device_lock);23272328EditorProgress ep("run", vformat(TTR("Running on %s"), devices[p_device].name), 3);23292330String adb = get_adb_path();23312332// Export_temp APK.2333if (ep.step(TTR("Exporting APK..."), 0)) {2334return ERR_SKIP;2335}23362337const bool use_wifi_for_remote_debug = EDITOR_GET("export/android/use_wifi_for_remote_debug");2338const bool use_remote = p_debug_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG) || p_debug_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT);2339const bool use_reverse = devices[p_device].api_level >= 21 && !use_wifi_for_remote_debug;23402341if (use_reverse) {2342p_debug_flags.set_flag(DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST);2343}23442345String tmp_export_path = EditorPaths::get_singleton()->get_temp_dir().path_join("tmpexport." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");23462347#define CLEANUP_AND_RETURN(m_err) \2348{ \2349DirAccess::remove_file_or_error(tmp_export_path); \2350if (FileAccess::exists(tmp_export_path + ".idsig")) { \2351DirAccess::remove_file_or_error(tmp_export_path + ".idsig"); \2352} \2353return m_err; \2354} \2355((void)0)23562357// Export to temporary APK before sending to device.2358Error err = export_project_helper(p_preset, true, tmp_export_path, EXPORT_FORMAT_APK, true, p_debug_flags);23592360if (err != OK) {2361CLEANUP_AND_RETURN(err);2362}23632364List<String> args;2365int rv;2366String output;23672368bool remove_prev = EDITOR_GET("export/android/one_click_deploy_clear_previous_install");2369String version_name = p_preset->get_version("version/name");2370String package_name = p_preset->get("package/unique_name");23712372if (remove_prev) {2373if (ep.step(TTR("Uninstalling..."), 1)) {2374CLEANUP_AND_RETURN(ERR_SKIP);2375}23762377print_line("Uninstalling previous version: " + devices[p_device].name);23782379args.push_back("-s");2380args.push_back(devices[p_device].id);2381args.push_back("uninstall");2382if ((bool)EDITOR_GET("export/android/force_system_user") && devices[p_device].api_level >= 17) {2383args.push_back("--user");2384args.push_back("0");2385}2386args.push_back(get_package_name(p_preset, package_name));23872388output.clear();2389err = OS::get_singleton()->execute(adb, args, &output, &rv, true);2390print_verbose(output);2391}23922393print_line("Installing to device (please wait...): " + devices[p_device].name);2394if (ep.step(TTR("Installing to device, please wait..."), 2)) {2395CLEANUP_AND_RETURN(ERR_SKIP);2396}23972398args.clear();2399args.push_back("-s");2400args.push_back(devices[p_device].id);2401args.push_back("install");2402if ((bool)EDITOR_GET("export/android/force_system_user") && devices[p_device].api_level >= 17) {2403args.push_back("--user");2404args.push_back("0");2405}2406args.push_back("-r");2407args.push_back(tmp_export_path);24082409output.clear();2410err = OS::get_singleton()->execute(adb, args, &output, &rv, true);2411print_verbose(output);2412if (err || rv != 0) {2413add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Could not install to device: %s"), output));2414CLEANUP_AND_RETURN(ERR_CANT_CREATE);2415}24162417if (use_remote) {2418if (use_reverse) {2419static const char *const msg = "--- Device API >= 21; debugging over USB ---";2420EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);2421print_line(String(msg).to_upper());24222423args.clear();2424args.push_back("-s");2425args.push_back(devices[p_device].id);2426args.push_back("reverse");2427args.push_back("--remove-all");2428output.clear();2429OS::get_singleton()->execute(adb, args, &output, &rv, true);2430print_verbose(output);24312432if (p_debug_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG)) {2433int dbg_port = EDITOR_GET("network/debug/remote_port");2434args.clear();2435args.push_back("-s");2436args.push_back(devices[p_device].id);2437args.push_back("reverse");2438args.push_back("tcp:" + itos(dbg_port));2439args.push_back("tcp:" + itos(dbg_port));24402441output.clear();2442OS::get_singleton()->execute(adb, args, &output, &rv, true);2443print_verbose(output);2444print_line("Reverse result: " + itos(rv));2445}24462447if (p_debug_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {2448int fs_port = EDITOR_GET("filesystem/file_server/port");24492450args.clear();2451args.push_back("-s");2452args.push_back(devices[p_device].id);2453args.push_back("reverse");2454args.push_back("tcp:" + itos(fs_port));2455args.push_back("tcp:" + itos(fs_port));24562457output.clear();2458err = OS::get_singleton()->execute(adb, args, &output, &rv, true);2459print_verbose(output);2460print_line("Reverse result2: " + itos(rv));2461}2462} else {2463static const char *const api_version_msg = "--- Device API < 21; debugging over Wi-Fi ---";2464static const char *const manual_override_msg = "--- Wi-Fi remote debug enabled in project settings; debugging over Wi-Fi ---";24652466const char *const msg = use_wifi_for_remote_debug ? manual_override_msg : api_version_msg;2467EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);2468print_line(String(msg).to_upper());2469}2470}24712472if (ep.step(TTR("Running on device..."), 3)) {2473CLEANUP_AND_RETURN(ERR_SKIP);2474}2475args.clear();2476args.push_back("-s");2477args.push_back(devices[p_device].id);2478args.push_back("shell");2479args.push_back("am");2480args.push_back("start");2481if ((bool)EDITOR_GET("export/android/force_system_user") && devices[p_device].api_level >= 17) {2482args.push_back("--user");2483args.push_back("0");2484}2485args.push_back("-a");2486args.push_back("android.intent.action.MAIN");24872488// Going with implicit launch first based on the LAUNCHER category and the app's package.2489args.push_back("-c");2490args.push_back("android.intent.category.LAUNCHER");2491args.push_back(get_package_name(p_preset, package_name));24922493output.clear();2494err = OS::get_singleton()->execute(adb, args, &output, &rv, true);2495print_verbose(output);2496if (err || rv != 0 || output.contains("Error: Activity not started")) {2497// The implicit launch failed, let's try an explicit launch by specifying the component name before giving up.2498const String component_name = get_package_name(p_preset, package_name) + "/com.godot.game.GodotApp";2499print_line("Implicit launch failed.. Trying explicit launch using", component_name);2500args.erase(get_package_name(p_preset, package_name));2501args.push_back("-n");2502args.push_back(component_name);25032504output.clear();2505err = OS::get_singleton()->execute(adb, args, &output, &rv, true);2506print_verbose(output);25072508if (err || rv != 0 || output.begins_with("Error: Activity not started")) {2509add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), TTR("Could not execute on device."));2510CLEANUP_AND_RETURN(ERR_CANT_CREATE);2511}2512}25132514CLEANUP_AND_RETURN(OK);2515#undef CLEANUP_AND_RETURN2516}25172518Ref<Texture2D> EditorExportPlatformAndroid::get_run_icon() const {2519return run_icon;2520}25212522String EditorExportPlatformAndroid::get_java_path() {2523String exe_ext;2524if (OS::get_singleton()->get_name() == "Windows") {2525exe_ext = ".exe";2526}2527String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");2528return java_sdk_path.path_join("bin/java" + exe_ext);2529}25302531String EditorExportPlatformAndroid::get_keytool_path() {2532String exe_ext;2533if (OS::get_singleton()->get_name() == "Windows") {2534exe_ext = ".exe";2535}2536String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");2537return java_sdk_path.path_join("bin/keytool" + exe_ext);2538}25392540String EditorExportPlatformAndroid::get_adb_path() {2541String exe_ext;2542if (OS::get_singleton()->get_name() == "Windows") {2543exe_ext = ".exe";2544}2545String sdk_path = EDITOR_GET("export/android/android_sdk_path");2546return sdk_path.path_join("platform-tools/adb" + exe_ext);2547}25482549String EditorExportPlatformAndroid::get_apksigner_path(int p_target_sdk, bool p_check_executes) {2550if (p_target_sdk == -1) {2551p_target_sdk = DEFAULT_TARGET_SDK_VERSION;2552}2553String exe_ext;2554if (OS::get_singleton()->get_name() == "Windows") {2555exe_ext = ".bat";2556}2557String apksigner_command_name = "apksigner" + exe_ext;2558String sdk_path = EDITOR_GET("export/android/android_sdk_path");2559String apksigner_path;25602561Error errn;2562String build_tools_dir = sdk_path.path_join("build-tools");2563Ref<DirAccess> da = DirAccess::open(build_tools_dir, &errn);2564if (errn != OK) {2565print_error("Unable to open Android 'build-tools' directory.");2566return apksigner_path;2567}25682569// There are additional versions directories we need to go through.2570Vector<String> dir_list = da->get_directories();25712572// We need to use the version of build_tools that matches the Target SDK2573// If somehow we can't find that, we see if a version between 28 and the default target SDK exists.2574// We need to avoid versions <= 27 because they fail on Java versions >92575// If we can't find that, we just use the first valid version.2576Vector<String> ideal_versions;2577Vector<String> other_versions;2578Vector<String> versions;2579bool found_target_sdk = false;2580// We only allow for versions <= 27 if specifically set2581int min_version = p_target_sdk <= 27 ? p_target_sdk : 28;2582for (String sub_dir : dir_list) {2583if (!sub_dir.begins_with(".")) {2584Vector<String> ver_numbers = sub_dir.split(".");2585// Dir not a version number, will use as last resort2586if (!ver_numbers.size() || !ver_numbers[0].is_valid_int()) {2587other_versions.push_back(sub_dir);2588continue;2589}2590int ver_number = ver_numbers[0].to_int();2591if (ver_number == p_target_sdk) {2592found_target_sdk = true;2593//ensure this is in front of the ones we check2594versions.push_back(sub_dir);2595} else {2596if (ver_number >= min_version && ver_number <= DEFAULT_TARGET_SDK_VERSION) {2597ideal_versions.push_back(sub_dir);2598} else {2599other_versions.push_back(sub_dir);2600}2601}2602}2603}2604// we will check ideal versions first, then other versions.2605versions.append_array(ideal_versions);2606versions.append_array(other_versions);26072608if (!versions.size()) {2609print_error("Unable to find the 'apksigner' tool.");2610return apksigner_path;2611}26122613int i;2614bool failed = false;2615String version_to_use;26162617String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");2618if (!java_sdk_path.is_empty()) {2619OS::get_singleton()->set_environment("JAVA_HOME", java_sdk_path);26202621#ifdef UNIX_ENABLED2622String env_path = OS::get_singleton()->get_environment("PATH");2623if (!env_path.contains(java_sdk_path)) {2624OS::get_singleton()->set_environment("PATH", java_sdk_path + "/bin:" + env_path);2625}2626#endif2627}26282629List<String> args;2630args.push_back("--version");2631String output;2632int retval;2633Error err;2634for (i = 0; i < versions.size(); i++) {2635// Check if the tool is here.2636apksigner_path = build_tools_dir.path_join(versions[i]).path_join(apksigner_command_name);2637if (FileAccess::exists(apksigner_path)) {2638version_to_use = versions[i];2639// If we aren't exporting, just break here.2640if (!p_check_executes) {2641break;2642}2643// we only check to see if it executes on export because it is slow to load2644err = OS::get_singleton()->execute(apksigner_path, args, &output, &retval, false);2645if (err || retval) {2646failed = true;2647} else {2648break;2649}2650}2651}2652if (i == versions.size()) {2653if (failed) {2654print_error("All located 'apksigner' tools in " + build_tools_dir + " failed to execute");2655return "<FAILED>";2656} else {2657print_error("Unable to find the 'apksigner' tool.");2658return "";2659}2660}2661if (!found_target_sdk) {2662print_line("Could not find version of build tools that matches Target SDK, using " + version_to_use);2663} else if (failed && found_target_sdk) {2664print_line("Version of build tools that matches Target SDK failed to execute, using " + version_to_use);2665}26662667return apksigner_path;2668}26692670static bool has_valid_keystore_credentials(String &r_error_str, const String &p_keystore, const String &p_username, const String &p_password, const String &p_type) {2671String output;2672List<String> args;2673args.push_back("-list");2674args.push_back("-keystore");2675args.push_back(p_keystore);2676args.push_back("-storepass");2677args.push_back(p_password);2678args.push_back("-alias");2679args.push_back(p_username);2680String keytool_path = EditorExportPlatformAndroid::get_keytool_path();2681Error error = OS::get_singleton()->execute(keytool_path, args, &output, nullptr, true);2682String keytool_error = "keytool error:";2683bool valid = output.substr(0, keytool_error.length()) != keytool_error;26842685if (error != OK) {2686r_error_str = TTR("Error: There was a problem validating the keystore username and password");2687return false;2688}2689if (!valid) {2690r_error_str = TTR(p_type + " Username and/or Password is invalid for the given " + p_type + " Keystore");2691return false;2692}2693r_error_str = "";2694return true;2695}26962697bool EditorExportPlatformAndroid::has_valid_username_and_password(const Ref<EditorExportPreset> &p_preset, String &r_error) {2698String dk = _get_keystore_path(p_preset, true);2699String dk_user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);2700String dk_password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);2701String rk = _get_keystore_path(p_preset, false);2702String rk_user = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);2703String rk_password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);27042705bool valid = true;2706if (!dk.is_empty() && !dk_user.is_empty() && !dk_password.is_empty()) {2707String err = "";2708valid = has_valid_keystore_credentials(err, dk, dk_user, dk_password, "Debug");2709r_error += err;2710}2711if (!rk.is_empty() && !rk_user.is_empty() && !rk_password.is_empty()) {2712String err = "";2713valid = has_valid_keystore_credentials(err, rk, rk_user, rk_password, "Release");2714r_error += err;2715}2716return valid;2717}27182719#ifdef MODULE_MONO_ENABLED2720static uint64_t _last_validate_tfm_time = 0;2721static String _last_validate_tfm = "";27222723bool _validate_dotnet_tfm(const String &required_tfm, String &r_error) {2724String assembly_name = Path::get_csharp_project_name();2725String project_path = ProjectSettings::get_singleton()->globalize_path("res://" + assembly_name + ".csproj");27262727if (!FileAccess::exists(project_path)) {2728return true;2729}27302731uint64_t modified_time = FileAccess::get_modified_time(project_path);2732String tfm;27332734if (modified_time == _last_validate_tfm_time) {2735tfm = _last_validate_tfm;2736} else {2737String pipe;2738List<String> args;2739args.push_back("build");2740args.push_back(project_path);2741args.push_back("/p:GodotTargetPlatform=android");2742args.push_back("--getProperty:TargetFramework");27432744int exitcode;2745Error err = OS::get_singleton()->execute("dotnet", args, &pipe, &exitcode, true);2746if (err != OK || exitcode != 0) {2747if (err != OK) {2748WARN_PRINT("Failed to execute dotnet command. Error " + String(error_names[err]));2749} else if (exitcode != 0) {2750print_line(pipe);2751WARN_PRINT("dotnet command exited with code " + itos(exitcode) + ". See output above for more details.");2752}2753r_error += vformat(TTR("Unable to determine the C# project's TFM, it may be incompatible. The export template only supports '%s'. Make sure the project targets '%s' or consider using gradle builds instead."), required_tfm, required_tfm) + "\n";2754return true;2755} else {2756tfm = pipe.strip_edges();2757_last_validate_tfm_time = modified_time;2758_last_validate_tfm = tfm;2759}2760}27612762if (tfm != required_tfm) {2763r_error += vformat(TTR("C# project targets '%s' but the export template only supports '%s'. Consider using gradle builds instead."), tfm, required_tfm) + "\n";2764return false;2765}27662767return true;2768}2769#endif27702771bool EditorExportPlatformAndroid::has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates, bool p_debug) const {2772String err;2773bool valid = false;2774const bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");27752776#ifdef MODULE_MONO_ENABLED2777// Android export is still a work in progress, keep a message as a warning.2778err += TTR("Exporting to Android when using C#/.NET is experimental.") + "\n";27792780if (!gradle_build_enabled) {2781// For template exports we only support .NET 9 because the template2782// includes .jar dependencies that may only be compatible with .NET 9.2783if (!_validate_dotnet_tfm("net9.0", err)) {2784r_error = err;2785return false;2786}2787}2788#endif27892790// Look for export templates (first official, and if defined custom templates).27912792if (!gradle_build_enabled) {2793String template_err;2794bool dvalid = false;2795bool rvalid = false;2796bool has_export_templates = false;27972798if (p_preset->get("custom_template/debug") != "") {2799dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));2800if (!dvalid) {2801template_err += TTR("Custom debug template not found.") + "\n";2802}2803has_export_templates |= dvalid;2804} else {2805has_export_templates |= exists_export_template("android_debug.apk", &template_err);2806}28072808if (p_preset->get("custom_template/release") != "") {2809rvalid = FileAccess::exists(p_preset->get("custom_template/release"));2810if (!rvalid) {2811template_err += TTR("Custom release template not found.") + "\n";2812}2813has_export_templates |= rvalid;2814} else {2815has_export_templates |= exists_export_template("android_release.apk", &template_err);2816}28172818r_missing_templates = !has_export_templates;2819valid = dvalid || rvalid || has_export_templates;2820if (!valid) {2821err += template_err;2822}2823} else {2824#ifdef ANDROID_ENABLED2825err += TTR("Gradle build is not supported for the Android editor.") + "\n";2826valid = false;2827#else2828// Validate the custom gradle android source template.2829bool android_source_template_valid = false;2830const String android_source_template = p_preset->get("gradle_build/android_source_template");2831if (!android_source_template.is_empty()) {2832android_source_template_valid = FileAccess::exists(android_source_template);2833if (!android_source_template_valid) {2834err += TTR("Custom Android source template not found.") + "\n";2835}2836}28372838// Validate the installed build template.2839bool installed_android_build_template = FileAccess::exists(ExportTemplateManager::get_android_build_directory(p_preset).path_join("build.gradle"));2840if (!installed_android_build_template) {2841if (!android_source_template_valid) {2842r_missing_templates = !exists_export_template("android_source.zip", &err);2843}2844err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n";2845} else {2846r_missing_templates = false;2847}28482849valid = installed_android_build_template && !r_missing_templates;2850#endif2851}28522853// Validate the rest of the export configuration.28542855String dk = _get_keystore_path(p_preset, true);2856String dk_user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);2857String dk_password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);28582859if ((dk.is_empty() || dk_user.is_empty() || dk_password.is_empty()) && (!dk.is_empty() || !dk_user.is_empty() || !dk_password.is_empty())) {2860valid = false;2861err += TTR("Either Debug Keystore, Debug User AND Debug Password settings must be configured OR none of them.") + "\n";2862}28632864// Use OR to make the export UI able to show this error.2865if ((p_debug || !dk.is_empty()) && !FileAccess::exists(dk)) {2866dk = EDITOR_GET("export/android/debug_keystore");2867if (!FileAccess::exists(dk)) {2868valid = false;2869err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";2870}2871}28722873String rk = _get_keystore_path(p_preset, false);2874String rk_user = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);2875String rk_password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);28762877if ((rk.is_empty() || rk_user.is_empty() || rk_password.is_empty()) && (!rk.is_empty() || !rk_user.is_empty() || !rk_password.is_empty())) {2878valid = false;2879err += TTR("Either Release Keystore, Release User AND Release Password settings must be configured OR none of them.") + "\n";2880}28812882if (!p_debug && !rk.is_empty() && !FileAccess::exists(rk)) {2883valid = false;2884err += TTR("Release keystore incorrectly configured in the export preset.") + "\n";2885}28862887#ifndef ANDROID_ENABLED2888String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");2889if (java_sdk_path.is_empty()) {2890err += TTR("A valid Java SDK path is required in Editor Settings.") + "\n";2891valid = false;2892} else {2893// Validate the given path by checking that `java` is present under the `bin` directory.2894Error errn;2895// Check for the bin directory.2896Ref<DirAccess> da = DirAccess::open(java_sdk_path.path_join("bin"), &errn);2897if (errn != OK) {2898err += TTR("Invalid Java SDK path in Editor Settings.") + " ";2899err += TTR("Missing 'bin' directory!");2900err += "\n";2901valid = false;2902} else {2903// Check for the `java` command.2904String java_path = get_java_path();2905if (!FileAccess::exists(java_path)) {2906err += TTR("Unable to find 'java' command using the Java SDK path.") + " ";2907err += TTR("Please check the Java SDK directory specified in Editor Settings.");2908err += "\n";2909valid = false;2910}2911}2912}29132914String sdk_path = EDITOR_GET("export/android/android_sdk_path");2915if (sdk_path.is_empty()) {2916err += TTR("A valid Android SDK path is required in Editor Settings.") + "\n";2917valid = false;2918} else {2919Error errn;2920// Check for the platform-tools directory.2921Ref<DirAccess> da = DirAccess::open(sdk_path.path_join("platform-tools"), &errn);2922if (errn != OK) {2923err += TTR("Invalid Android SDK path in Editor Settings.") + " ";2924err += TTR("Missing 'platform-tools' directory!");2925err += "\n";2926valid = false;2927}29282929// Validate that adb is available.2930String adb_path = get_adb_path();2931if (!FileAccess::exists(adb_path)) {2932err += TTR("Unable to find Android SDK platform-tools' adb command.") + " ";2933err += TTR("Please check in the Android SDK directory specified in Editor Settings.");2934err += "\n";2935valid = false;2936}29372938// Check for the build-tools directory.2939Ref<DirAccess> build_tools_da = DirAccess::open(sdk_path.path_join("build-tools"), &errn);2940if (errn != OK) {2941err += TTR("Invalid Android SDK path in Editor Settings.") + " ";2942err += TTR("Missing 'build-tools' directory!");2943err += "\n";2944valid = false;2945}29462947String target_sdk_version = p_preset->get("gradle_build/target_sdk");2948if (!target_sdk_version.is_valid_int()) {2949target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);2950}2951// Validate that apksigner is available.2952String apksigner_path = get_apksigner_path(target_sdk_version.to_int());2953if (!FileAccess::exists(apksigner_path)) {2954err += TTR("Unable to find Android SDK build-tools' apksigner command.") + " ";2955err += TTR("Please check in the Android SDK directory specified in Editor Settings.");2956err += "\n";2957valid = false;2958}2959}2960#endif29612962if (!err.is_empty()) {2963r_error = err;2964}29652966return valid;2967}29682969bool EditorExportPlatformAndroid::has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const {2970String err;2971bool valid = true;29722973List<ExportOption> options;2974get_export_options(&options);2975for (const EditorExportPlatform::ExportOption &E : options) {2976if (get_export_option_visibility(p_preset.ptr(), E.option.name)) {2977String warn = get_export_option_warning(p_preset.ptr(), E.option.name);2978if (!warn.is_empty()) {2979err += warn + "\n";2980if (E.required) {2981valid = false;2982}2983}2984}2985}29862987if (!ResourceImporterTextureSettings::should_import_etc2_astc()) {2988valid = false;2989}29902991bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2992if (gradle_build_enabled) {2993String build_version_path = ExportTemplateManager::get_android_build_directory(p_preset).get_base_dir().path_join(".build_version");2994Ref<FileAccess> f = FileAccess::open(build_version_path, FileAccess::READ);2995if (f.is_valid()) {2996String current_version = ExportTemplateManager::get_android_template_identifier(p_preset);2997String installed_version = f->get_line().strip_edges();2998if (current_version != installed_version) {2999err += vformat(TTR(MISMATCHED_VERSIONS_MESSAGE), installed_version, current_version);3000err += "\n";3001}3002}3003} else {3004if (_is_transparency_allowed(p_preset)) {3005// Warning only, so don't override `valid`.3006err += vformat(TTR("\"Use Gradle Build\" is required for transparent background on Android"));3007err += "\n";3008}3009}30103011String target_sdk_str = p_preset->get("gradle_build/target_sdk");3012int target_sdk_int = DEFAULT_TARGET_SDK_VERSION;3013if (!target_sdk_str.is_empty()) { // Empty means no override, nothing to do.3014if (target_sdk_str.is_valid_int()) {3015target_sdk_int = target_sdk_str.to_int();3016if (target_sdk_int > DEFAULT_TARGET_SDK_VERSION) {3017// Warning only, so don't override `valid`.3018err += vformat(TTR("\"Target SDK\" %d is higher than the default version %d. This may work, but wasn't tested and may be unstable."), target_sdk_int, DEFAULT_TARGET_SDK_VERSION);3019err += "\n";3020}3021}3022}30233024String current_renderer = get_project_setting(p_preset, "rendering/renderer/rendering_method.mobile");3025if (current_renderer == "forward_plus") {3026// Warning only, so don't override `valid`.3027err += vformat(TTR("The \"%s\" renderer is designed for Desktop devices, and is not suitable for Android devices."), current_renderer);3028err += "\n";3029}30303031String package_name = p_preset->get("package/unique_name");3032if (package_name.contains("$genname") && !is_project_name_valid(p_preset)) {3033// Warning only, so don't override `valid`.3034err += vformat(TTR("The project name does not meet the requirement for the package name format and will be updated to \"%s\". Please explicitly specify the package name if needed."), get_valid_basename(p_preset));3035err += "\n";3036}30373038r_error = err;3039return valid;3040}30413042List<String> EditorExportPlatformAndroid::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {3043List<String> list;3044list.push_back("apk");3045list.push_back("aab");3046return list;3047}30483049String EditorExportPlatformAndroid::get_apk_expansion_fullpath(const Ref<EditorExportPreset> &p_preset, const String &p_path) {3050int version_code = p_preset->get("version/code");3051String package_name = p_preset->get("package/unique_name");3052String apk_file_name = "main." + itos(version_code) + "." + get_package_name(p_preset, package_name) + ".obb";3053String fullpath = p_path.get_base_dir().path_join(apk_file_name);3054return fullpath;3055}30563057Error EditorExportPlatformAndroid::save_apk_expansion_file(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {3058String fullpath = get_apk_expansion_fullpath(p_preset, p_path);3059Error err = save_pack(p_preset, p_debug, fullpath);3060return err;3061}30623063void EditorExportPlatformAndroid::get_command_line_flags(const Ref<EditorExportPreset> &p_preset, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags, Vector<uint8_t> &r_command_line_flags) {3064String cmdline = p_preset->get("command_line/extra_args");3065Vector<String> command_line_strings = cmdline.strip_edges().split(" ");3066for (int i = 0; i < command_line_strings.size(); i++) {3067if (command_line_strings[i].strip_edges().length() == 0) {3068command_line_strings.remove_at(i);3069i--;3070}3071}30723073command_line_strings.append_array(gen_export_flags(p_flags));30743075bool apk_expansion = p_preset->get("apk_expansion/enable");3076if (apk_expansion) {3077String fullpath = get_apk_expansion_fullpath(p_preset, p_path);3078String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");30793080command_line_strings.push_back("--use_apk_expansion");3081command_line_strings.push_back("--apk_expansion_md5");3082command_line_strings.push_back(FileAccess::get_md5(fullpath));3083command_line_strings.push_back("--apk_expansion_key");3084command_line_strings.push_back(apk_expansion_public_key.strip_edges());3085}30863087int xr_mode_index = p_preset->get("xr_features/xr_mode");3088if (xr_mode_index == XR_MODE_OPENXR) {3089command_line_strings.push_back("--xr_mode_openxr");3090} else { // XRMode.REGULAR is the default.3091command_line_strings.push_back("--xr_mode_regular");30923093// Also override the 'xr/openxr/enabled' project setting.3094// This is useful for multi-platforms projects supporting both XR and non-XR devices. The project would need3095// to enable openxr for development, and would create multiple XR and non-XR export presets.3096// These command line args ensure that the non-XR export presets will have openxr disabled.3097command_line_strings.push_back("--xr-mode");3098command_line_strings.push_back("off");3099}31003101bool immersive = p_preset->get("screen/immersive_mode");3102if (immersive) {3103command_line_strings.push_back("--fullscreen");3104}31053106bool edge_to_edge = p_preset->get("screen/edge_to_edge");3107if (edge_to_edge) {3108command_line_strings.push_back("--edge_to_edge");3109}31103111String background_color = "#" + p_preset->get("screen/background_color").operator Color().to_html(false);31123113// For Gradle build, _fix_themes_xml() sets background to transparent if _is_transparency_allowed().3114// Overriding to transparent here too as it's used as fallback for system bar appearance.3115if (_is_transparency_allowed(p_preset) && p_preset->get("gradle_build/use_gradle_build")) {3116background_color = "#00000000";3117}3118command_line_strings.push_back("--background_color");3119command_line_strings.push_back(background_color);31203121bool debug_opengl = p_preset->get("graphics/opengl_debug");3122if (debug_opengl) {3123command_line_strings.push_back("--debug_opengl");3124}31253126if (command_line_strings.size()) {3127r_command_line_flags.resize(4);3128encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);3129for (int i = 0; i < command_line_strings.size(); i++) {3130print_line(itos(i) + " param: " + command_line_strings[i]);3131CharString command_line_argument = command_line_strings[i].utf8();3132int base = r_command_line_flags.size();3133int length = command_line_argument.length();3134if (length == 0) {3135continue;3136}3137r_command_line_flags.resize(base + 4 + length);3138encode_uint32(length, &r_command_line_flags.write[base]);3139memcpy(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);3140}3141}3142}31433144Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &export_path, EditorProgress &ep) {3145int export_format = int(p_preset->get("gradle_build/export_format"));3146if (export_format == EXPORT_FORMAT_AAB) {3147add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("AAB signing is not supported"));3148return FAILED;3149}31503151String keystore;3152String password;3153String user;3154if (p_debug) {3155keystore = _get_keystore_path(p_preset, true);3156password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);3157user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);31583159if (keystore.is_empty()) {3160keystore = EDITOR_GET("export/android/debug_keystore");3161password = EDITOR_GET("export/android/debug_keystore_pass");3162user = EDITOR_GET("export/android/debug_keystore_user");3163}31643165if (ep.step(TTR("Signing debug APK..."), 104)) {3166return ERR_SKIP;3167}3168} else {3169keystore = _get_keystore_path(p_preset, false);3170password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);3171user = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);31723173if (ep.step(TTR("Signing release APK..."), 104)) {3174return ERR_SKIP;3175}3176}31773178if (!FileAccess::exists(keystore)) {3179if (p_debug) {3180add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not find debug keystore, unable to export."));3181} else {3182add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not find release keystore, unable to export."));3183}3184return ERR_FILE_CANT_OPEN;3185}31863187String apk_path = export_path;3188if (apk_path.is_relative_path()) {3189apk_path = OS::get_singleton()->get_resource_dir().path_join(apk_path);3190}3191apk_path = ProjectSettings::get_singleton()->globalize_path(apk_path).simplify_path();31923193Error err;3194#ifdef ANDROID_ENABLED3195err = OS_Android::get_singleton()->sign_apk(apk_path, apk_path, keystore, user, password);3196if (err != OK) {3197add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Unable to sign apk."));3198return err;3199}3200#else3201String target_sdk_version = p_preset->get("gradle_build/target_sdk");3202if (!target_sdk_version.is_valid_int()) {3203target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);3204}32053206String apksigner = get_apksigner_path(target_sdk_version.to_int(), true);3207print_verbose("Starting signing of the APK binary using " + apksigner);3208if (apksigner == "<FAILED>") {3209add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("All 'apksigner' tools located in Android SDK 'build-tools' directory failed to execute. Please check that you have the correct version installed for your target sdk version. The resulting APK is unsigned."));3210return OK;3211}3212if (!FileAccess::exists(apksigner)) {3213add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("'apksigner' could not be found. Please check that the command is available in the Android SDK build-tools directory. The resulting APK is unsigned."));3214return OK;3215}32163217String output;3218List<String> args;3219args.push_back("sign");3220args.push_back("--verbose");3221args.push_back("--ks");3222args.push_back(keystore);3223args.push_back("--ks-pass");3224args.push_back("pass:" + password);3225args.push_back("--ks-key-alias");3226args.push_back(user);3227args.push_back(apk_path);3228if (OS::get_singleton()->is_stdout_verbose() && p_debug) {3229// We only print verbose logs with credentials for debug builds to avoid leaking release keystore credentials.3230print_verbose("Signing debug binary using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));3231} else {3232List<String> redacted_args = List<String>(args);3233redacted_args.find(keystore)->set("<REDACTED>");3234redacted_args.find("pass:" + password)->set("pass:<REDACTED>");3235redacted_args.find(user)->set("<REDACTED>");3236print_line("Signing binary using: " + String("\n") + apksigner + " " + join_list(redacted_args, String(" ")));3237}3238int retval;3239err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);3240if (err != OK) {3241add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));3242return err;3243}3244// By design, apksigner does not output credentials in its output unless --verbose is used3245print_line(output);3246if (retval) {3247add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("'apksigner' returned with error #%d"), retval));3248add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));3249return ERR_CANT_CREATE;3250}3251#endif32523253if (ep.step(TTR("Verifying APK..."), 105)) {3254return ERR_SKIP;3255}32563257#ifdef ANDROID_ENABLED3258err = OS_Android::get_singleton()->verify_apk(apk_path);3259if (err != OK) {3260add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Unable to verify signed apk."));3261return err;3262}3263#else3264args.clear();3265args.push_back("verify");3266args.push_back("--verbose");3267args.push_back(apk_path);3268if (p_debug) {3269print_verbose("Verifying signed build using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));3270}32713272output.clear();3273err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);3274if (err != OK) {3275add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));3276return err;3277}3278print_verbose(output);3279if (retval) {3280add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("'apksigner' verification of APK failed."));3281add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));3282return ERR_CANT_CREATE;3283}3284#endif32853286print_verbose("Successfully completed signing build.");32873288#ifdef ANDROID_ENABLED3289bool prompt_apk_install = EDITOR_GET("export/android/install_exported_apk");3290if (prompt_apk_install) {3291OS_Android::get_singleton()->shell_open(apk_path);3292}3293#endif32943295return OK;3296}32973298void EditorExportPlatformAndroid::_clear_assets_directory(const Ref<EditorExportPreset> &p_preset) {3299Ref<DirAccess> da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);3300String gradle_build_directory = ExportTemplateManager::get_android_build_directory(p_preset);33013302// Clear the APK assets directory3303String apk_assets_directory = gradle_build_directory.path_join(APK_ASSETS_DIRECTORY);3304if (da_res->dir_exists(apk_assets_directory)) {3305print_verbose("Clearing APK assets directory...");3306Ref<DirAccess> da_assets = DirAccess::open(apk_assets_directory);3307ERR_FAIL_COND(da_assets.is_null());33083309da_assets->erase_contents_recursive();3310da_res->remove(apk_assets_directory);3311}33123313// Clear the AAB assets directory3314String aab_assets_directory = gradle_build_directory.path_join(AAB_ASSETS_DIRECTORY);3315if (da_res->dir_exists(aab_assets_directory)) {3316print_verbose("Clearing AAB assets directory...");3317Ref<DirAccess> da_assets = DirAccess::open(aab_assets_directory);3318ERR_FAIL_COND(da_assets.is_null());33193320da_assets->erase_contents_recursive();3321da_res->remove(aab_assets_directory);3322}3323}33243325void EditorExportPlatformAndroid::_remove_copied_libs(String p_gdextension_libs_path) {3326print_verbose("Removing previously installed libraries...");3327Error error;3328String libs_json = FileAccess::get_file_as_string(p_gdextension_libs_path, &error);3329if (error || libs_json.is_empty()) {3330print_verbose("No previously installed libraries found");3331return;3332}33333334JSON json;3335error = json.parse(libs_json);3336ERR_FAIL_COND_MSG(error, "Error parsing \"" + libs_json + "\" on line " + itos(json.get_error_line()) + ": " + json.get_error_message());33373338Vector<String> libs = json.get_data();3339Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);3340for (int i = 0; i < libs.size(); i++) {3341print_verbose("Removing previously installed library " + libs[i]);3342da->remove(libs[i]);3343}3344da->remove(p_gdextension_libs_path);3345}33463347String EditorExportPlatformAndroid::join_list(const List<String> &p_parts, const String &p_separator) {3348String ret;3349for (List<String>::ConstIterator itr = p_parts.begin(); itr != p_parts.end(); ++itr) {3350if (itr != p_parts.begin()) {3351ret += p_separator;3352}3353ret += *itr;3354}3355return ret;3356}33573358String EditorExportPlatformAndroid::join_abis(const Vector<EditorExportPlatformAndroid::ABI> &p_parts, const String &p_separator, bool p_use_arch) {3359String ret;3360for (int i = 0; i < p_parts.size(); ++i) {3361if (i > 0) {3362ret += p_separator;3363}3364ret += (p_use_arch) ? p_parts[i].arch : p_parts[i].abi;3365}3366return ret;3367}33683369String EditorExportPlatformAndroid::_get_deprecated_plugins_names(const Ref<EditorExportPreset> &p_preset) const {3370Vector<String> names;33713372#ifndef DISABLE_DEPRECATED3373PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset), names);3374#endif // DISABLE_DEPRECATED33753376String plugins_names = String("|").join(names);3377return plugins_names;3378}33793380String EditorExportPlatformAndroid::_get_plugins_names(const Ref<EditorExportPreset> &p_preset) const {3381Vector<String> names;33823383#ifndef DISABLE_DEPRECATED3384PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset), names);3385#endif // DISABLE_DEPRECATED33863387Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3388for (int i = 0; i < export_plugins.size(); i++) {3389if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3390names.push_back(export_plugins[i]->get_name());3391}3392}33933394String plugins_names = String("|").join(names);3395return plugins_names;3396}33973398String EditorExportPlatformAndroid::_resolve_export_plugin_android_library_path(const String &p_android_library_path) const {3399String absolute_path;3400if (!p_android_library_path.is_empty()) {3401if (p_android_library_path.is_absolute_path()) {3402absolute_path = ProjectSettings::get_singleton()->globalize_path(p_android_library_path);3403} else {3404const String export_plugin_absolute_path = String("res://addons/").path_join(p_android_library_path);3405absolute_path = ProjectSettings::get_singleton()->globalize_path(export_plugin_absolute_path);3406}3407}3408return absolute_path;3409}34103411bool EditorExportPlatformAndroid::_is_clean_build_required(const Ref<EditorExportPreset> &p_preset) {3412bool first_build = last_gradle_build_time == 0;3413bool have_plugins_changed = false;3414String gradle_build_dir = ExportTemplateManager::get_android_build_directory(p_preset);3415bool has_build_dir_changed = last_gradle_build_dir != gradle_build_dir;34163417String plugin_names = _get_plugins_names(p_preset);34183419if (!first_build) {3420have_plugins_changed = plugin_names != last_plugin_names;3421#ifndef DISABLE_DEPRECATED3422if (!have_plugins_changed) {3423Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);3424for (int i = 0; i < enabled_plugins.size(); i++) {3425if (enabled_plugins.get(i).last_updated > last_gradle_build_time) {3426have_plugins_changed = true;3427break;3428}3429}3430}3431#endif // DISABLE_DEPRECATED3432}34333434last_gradle_build_time = OS::get_singleton()->get_unix_time();3435last_gradle_build_dir = gradle_build_dir;3436last_plugin_names = plugin_names;34373438return have_plugins_changed || has_build_dir_changed || first_build;3439}34403441Error EditorExportPlatformAndroid::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {3442int export_format = int(p_preset->get("gradle_build/export_format"));3443bool should_sign = p_preset->get("package/signed");3444return export_project_helper(p_preset, p_debug, p_path, export_format, should_sign, p_flags);3445}34463447Error EditorExportPlatformAndroid::_generate_sparse_pck_metadata(const Ref<EditorExportPreset> &p_preset, PackData &p_pack_data, Vector<uint8_t> &r_data) {3448Error err;3449Ref<FileAccess> ftmp = FileAccess::create_temp(FileAccess::WRITE_READ, "export_index", "tmp", false, &err);3450if (err != OK) {3451add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not create temporary file!"));3452return err;3453}3454int64_t pck_start_pos = ftmp->get_position();3455uint64_t file_base_ofs = 0;3456uint64_t dir_base_ofs = 0;3457EditorExportPlatform::_store_header(ftmp, p_preset->get_enc_pck() && p_preset->get_enc_directory(), true, file_base_ofs, dir_base_ofs);34583459// Write directory.3460uint64_t dir_offset = ftmp->get_position();3461ftmp->seek(dir_base_ofs);3462ftmp->store_64(dir_offset - pck_start_pos);3463ftmp->seek(dir_offset);34643465Vector<uint8_t> key;3466if (p_preset->get_enc_pck() && p_preset->get_enc_directory()) {3467String script_key = _get_script_encryption_key(p_preset);3468key.resize(32);3469if (script_key.length() == 64) {3470for (int i = 0; i < 32; i++) {3471int v = 0;3472if (i * 2 < script_key.length()) {3473char32_t ct = script_key[i * 2];3474if (is_digit(ct)) {3475ct = ct - '0';3476} else if (ct >= 'a' && ct <= 'f') {3477ct = 10 + ct - 'a';3478}3479v |= ct << 4;3480}34813482if (i * 2 + 1 < script_key.length()) {3483char32_t ct = script_key[i * 2 + 1];3484if (is_digit(ct)) {3485ct = ct - '0';3486} else if (ct >= 'a' && ct <= 'f') {3487ct = 10 + ct - 'a';3488}3489v |= ct;3490}3491key.write[i] = v;3492}3493}3494}34953496if (!EditorExportPlatform::_encrypt_and_store_directory(ftmp, p_pack_data, key, p_preset->get_seed(), 0)) {3497add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Can't create encrypted file."));3498return ERR_CANT_CREATE;3499}35003501r_data.resize(ftmp->get_length());3502ftmp->seek(0);3503ftmp->get_buffer(r_data.ptrw(), r_data.size());3504ftmp.unref();35053506return OK;3507}35083509Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int export_format, bool should_sign, BitField<EditorExportPlatform::DebugFlags> p_flags) {3510ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);35113512const String base_dir = p_path.get_base_dir();3513if (!DirAccess::exists(base_dir)) {3514add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Target folder does not exist or is inaccessible: \"%s\""), base_dir));3515return ERR_FILE_BAD_PATH;3516}35173518String src_apk;3519Error err;35203521EditorProgress ep("export", TTR("Exporting for Android"), 105, true);35223523bool use_gradle_build = bool(p_preset->get("gradle_build/use_gradle_build"));3524String gradle_build_directory = use_gradle_build ? ExportTemplateManager::get_android_build_directory(p_preset) : "";3525bool p_give_internet = p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT) || p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG);3526bool apk_expansion = p_preset->get("apk_expansion/enable");3527Vector<ABI> enabled_abis = get_enabled_abis(p_preset);35283529print_verbose("Exporting for Android...");3530print_verbose("- debug build: " + bool_to_string(p_debug));3531print_verbose("- export path: " + p_path);3532print_verbose("- export format: " + itos(export_format));3533print_verbose("- sign build: " + bool_to_string(should_sign));3534print_verbose("- gradle build enabled: " + bool_to_string(use_gradle_build));3535print_verbose("- apk expansion enabled: " + bool_to_string(apk_expansion));3536print_verbose("- enabled abis: " + join_abis(enabled_abis, ",", false));3537print_verbose("- export filter: " + itos(p_preset->get_export_filter()));3538print_verbose("- include filter: " + p_preset->get_include_filter());3539print_verbose("- exclude filter: " + p_preset->get_exclude_filter());35403541Ref<Image> main_image;3542Ref<Image> foreground;3543Ref<Image> background;3544Ref<Image> monochrome;35453546load_icon_refs(p_preset, main_image, foreground, background, monochrome);35473548Vector<uint8_t> command_line_flags;3549// Write command line flags into the command_line_flags variable.3550get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);35513552if (export_format == EXPORT_FORMAT_AAB) {3553if (!p_path.ends_with(".aab")) {3554add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android App Bundle requires the *.aab extension."));3555return ERR_UNCONFIGURED;3556}3557if (apk_expansion) {3558add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("APK Expansion not compatible with Android App Bundle."));3559return ERR_UNCONFIGURED;3560}3561}3562if (export_format == EXPORT_FORMAT_APK && !p_path.ends_with(".apk")) {3563add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android APK requires the *.apk extension."));3564return ERR_UNCONFIGURED;3565}3566if (export_format > EXPORT_FORMAT_AAB || export_format < EXPORT_FORMAT_APK) {3567add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unsupported export format!"));3568return ERR_UNCONFIGURED;3569}3570String err_string;3571if (!has_valid_username_and_password(p_preset, err_string)) {3572add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR(err_string));3573return ERR_UNCONFIGURED;3574}35753576if (use_gradle_build) {3577print_verbose("Starting gradle build...");3578//test that installed build version is alright3579{3580print_verbose("Checking build version...");3581String gradle_base_directory = gradle_build_directory.get_base_dir();3582Ref<FileAccess> f = FileAccess::open(gradle_base_directory.path_join(".build_version"), FileAccess::READ);3583if (f.is_null()) {3584add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Trying to build from a gradle built template, but no version info for it exists. Please reinstall from the 'Project' menu."));3585return ERR_UNCONFIGURED;3586}3587String current_version = ExportTemplateManager::get_android_template_identifier(p_preset);3588String installed_version = f->get_line().strip_edges();3589print_verbose("- build version: " + installed_version);3590if (installed_version != current_version) {3591add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR(MISMATCHED_VERSIONS_MESSAGE), installed_version, current_version));3592return ERR_UNCONFIGURED;3593}3594}3595const String assets_directory = get_assets_directory(p_preset, export_format);3596String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");3597if (java_sdk_path.is_empty()) {3598add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Java SDK path must be configured in Editor Settings at 'export/android/java_sdk_path'."));3599return ERR_UNCONFIGURED;3600}3601print_verbose("Java sdk path: " + java_sdk_path);36023603String sdk_path = EDITOR_GET("export/android/android_sdk_path");3604if (sdk_path.is_empty()) {3605add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Android SDK path must be configured in Editor Settings at 'export/android/android_sdk_path'."));3606return ERR_UNCONFIGURED;3607}3608print_verbose("Android sdk path: " + sdk_path);36093610// TODO: should we use "package/name" or "application/config/name"?3611String project_name = get_project_name(p_preset, p_preset->get("package/name"));3612err = _create_project_name_strings_files(p_preset, project_name, gradle_build_directory, get_project_setting(p_preset, "application/config/name_localized")); //project name localization.3613if (err != OK) {3614add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to overwrite res/*.xml files with project name."));3615}3616// Copies the project icon files into the appropriate Gradle project directory.3617_copy_icons_to_gradle_project(p_preset, main_image, foreground, background, monochrome);3618// Write an AndroidManifest.xml file into the Gradle project directory.3619_write_tmp_manifest(p_preset, p_give_internet, p_debug);3620// Modify res/values/themes.xml file.3621_fix_themes_xml(p_preset);36223623//stores all the project files inside the Gradle project directory. Also includes all ABIs3624_clear_assets_directory(p_preset);3625String gdextension_libs_path = gradle_build_directory.path_join(GDEXTENSION_LIBS_PATH);3626_remove_copied_libs(gdextension_libs_path);3627if (!apk_expansion) {3628print_verbose("Exporting project files...");3629CustomExportData user_data;3630user_data.assets_directory = assets_directory;3631user_data.libs_directory = gradle_build_directory.path_join("libs");3632user_data.debug = p_debug;3633if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {3634err = export_project_files(p_preset, p_debug, ignore_apk_file, nullptr, &user_data, copy_gradle_so);3635} else {3636user_data.pd.path = "assets.sparsepck";3637user_data.pd.use_sparse_pck = true;3638err = export_project_files(p_preset, p_debug, rename_and_store_file_in_gradle_project, nullptr, &user_data, copy_gradle_so);36393640Vector<uint8_t> enc_data;3641err = _generate_sparse_pck_metadata(p_preset, user_data.pd, enc_data);3642if (err != OK) {3643add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not generate sparse pck metadata!"));3644return err;3645}36463647err = store_file_at_path(user_data.assets_directory + "/assets.sparsepck", enc_data);3648if (err != OK) {3649add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not write PCK directory!"));3650return err;3651}3652}3653if (err != OK) {3654add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not export project files to gradle project."));3655return err;3656}3657if (user_data.libs.size() > 0) {3658Ref<FileAccess> fa = FileAccess::open(gdextension_libs_path, FileAccess::WRITE);3659fa->store_string(JSON::stringify(user_data.libs, "\t"));3660}3661} else {3662print_verbose("Saving apk expansion file...");3663err = save_apk_expansion_file(p_preset, p_debug, p_path);3664if (err != OK) {3665add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));3666return err;3667}3668}3669print_verbose("Storing command line flags...");3670store_file_at_path(assets_directory + "/_cl_", command_line_flags);36713672print_verbose("Updating JAVA_HOME environment to " + java_sdk_path);3673OS::get_singleton()->set_environment("JAVA_HOME", java_sdk_path);36743675print_verbose("Updating ANDROID_HOME environment to " + sdk_path);3676OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path);3677String build_command;36783679#ifdef WINDOWS_ENABLED3680build_command = "gradlew.bat";3681#else3682build_command = "gradlew";3683#endif36843685String build_path = ProjectSettings::get_singleton()->globalize_path(gradle_build_directory);3686build_command = build_path.path_join(build_command);36873688String package_name = get_package_name(p_preset, p_preset->get("package/unique_name"));3689String version_code = itos(p_preset->get("version/code"));3690String version_name = p_preset->get_version("version/name");3691String min_sdk_version = p_preset->get("gradle_build/min_sdk");3692if (!min_sdk_version.is_valid_int()) {3693min_sdk_version = itos(DEFAULT_MIN_SDK_VERSION);3694}3695String target_sdk_version = p_preset->get("gradle_build/target_sdk");3696if (!target_sdk_version.is_valid_int()) {3697target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);3698}3699String enabled_abi_string = join_abis(enabled_abis, "|", false);3700String sign_flag = bool_to_string(should_sign);3701String zipalign_flag = "true";3702String compress_native_libraries_flag = bool_to_string(p_preset->get("gradle_build/compress_native_libraries"));37033704Vector<String> android_libraries;3705Vector<String> android_dependencies;3706Vector<String> android_dependencies_maven_repos;37073708#ifndef DISABLE_DEPRECATED3709Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);3710PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_LOCAL, enabled_plugins, android_libraries);3711PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_REMOTE, enabled_plugins, android_dependencies);3712PluginConfigAndroid::get_plugins_custom_maven_repos(enabled_plugins, android_dependencies_maven_repos);3713#endif // DISABLE_DEPRECATED37143715bool has_dotnet_project = false;3716Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3717for (int i = 0; i < export_plugins.size(); i++) {3718if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3719PackedStringArray export_plugin_android_libraries = export_plugins[i]->get_android_libraries(Ref<EditorExportPlatform>(this), p_debug);3720for (int k = 0; k < export_plugin_android_libraries.size(); k++) {3721const String resolved_android_library_path = _resolve_export_plugin_android_library_path(export_plugin_android_libraries[k]);3722if (!resolved_android_library_path.is_empty()) {3723android_libraries.push_back(resolved_android_library_path);3724}3725}37263727PackedStringArray export_plugin_android_dependencies = export_plugins[i]->get_android_dependencies(Ref<EditorExportPlatform>(this), p_debug);3728android_dependencies.append_array(export_plugin_android_dependencies);37293730PackedStringArray export_plugin_android_dependencies_maven_repos = export_plugins[i]->get_android_dependencies_maven_repos(Ref<EditorExportPlatform>(this), p_debug);3731android_dependencies_maven_repos.append_array(export_plugin_android_dependencies_maven_repos);3732}37333734PackedStringArray features = export_plugins[i]->get_export_features(Ref<EditorExportPlatform>(this), p_debug);3735if (features.has("dotnet")) {3736has_dotnet_project = true;3737}3738}37393740bool clean_build_required = _is_clean_build_required(p_preset);3741String combined_android_libraries = String("|").join(android_libraries);3742String combined_android_dependencies = String("|").join(android_dependencies);3743String combined_android_dependencies_maven_repos = String("|").join(android_dependencies_maven_repos);37443745List<String> cmdline;3746cmdline.push_back("validateJavaVersion");3747if (clean_build_required) {3748cmdline.push_back("clean");3749}37503751String edition = has_dotnet_project ? "Mono" : "Standard";3752String build_type = p_debug ? "Debug" : "Release";3753if (export_format == EXPORT_FORMAT_AAB) {3754String bundle_build_command = vformat("bundle%s%s", edition, build_type);3755cmdline.push_back(bundle_build_command);3756} else if (export_format == EXPORT_FORMAT_APK) {3757String apk_build_command = vformat("assemble%s%s", edition, build_type);3758cmdline.push_back(apk_build_command);3759}37603761String addons_directory = ProjectSettings::get_singleton()->globalize_path("res://addons");37623763cmdline.push_back("-p"); // argument to specify the start directory.3764cmdline.push_back(build_path); // start directory.3765cmdline.push_back("-Paddons_directory=" + addons_directory); // path to the addon directory as it may contain jar or aar dependencies3766cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.3767cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code.3768cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name.3769cmdline.push_back("-Pexport_version_min_sdk=" + min_sdk_version); // argument to specify the min sdk.3770cmdline.push_back("-Pexport_version_target_sdk=" + target_sdk_version); // argument to specify the target sdk.3771cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs.3772cmdline.push_back("-Pplugins_local_binaries=" + combined_android_libraries); // argument to specify the list of android libraries provided by plugins.3773cmdline.push_back("-Pplugins_remote_binaries=" + combined_android_dependencies); // argument to specify the list of android dependencies provided by plugins.3774cmdline.push_back("-Pplugins_maven_repos=" + combined_android_dependencies_maven_repos); // argument to specify the list of maven repos for android dependencies provided by plugins.3775cmdline.push_back("-Pperform_zipalign=" + zipalign_flag); // argument to specify whether the build should be zipaligned.3776cmdline.push_back("-Pperform_signing=" + sign_flag); // argument to specify whether the build should be signed.3777cmdline.push_back("-Pcompress_native_libraries=" + compress_native_libraries_flag); // argument to specify whether the build should compress native libraries.37783779// NOTE: The release keystore is not included in the verbose logging3780// to avoid accidentally leaking sensitive information when sharing verbose logs for troubleshooting.3781// Any non-sensitive additions to the command line arguments must be done above this section.3782// Sensitive additions must be done below the logging statement.3783print_verbose("Build Android project using gradle command: " + String("\n") + build_command + " " + join_list(cmdline, String(" ")));37843785if (should_sign) {3786if (p_debug) {3787String debug_keystore = _get_keystore_path(p_preset, true);3788String debug_password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);3789String debug_user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);37903791if (debug_keystore.is_empty()) {3792debug_keystore = EDITOR_GET("export/android/debug_keystore");3793debug_password = EDITOR_GET("export/android/debug_keystore_pass");3794debug_user = EDITOR_GET("export/android/debug_keystore_user");3795}3796if (debug_keystore.is_relative_path()) {3797debug_keystore = OS::get_singleton()->get_resource_dir().path_join(debug_keystore).simplify_path();3798}3799if (!FileAccess::exists(debug_keystore)) {3800add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find debug keystore, unable to export."));3801return ERR_FILE_CANT_OPEN;3802}38033804cmdline.push_back("-Pdebug_keystore_file=" + debug_keystore); // argument to specify the debug keystore file.3805cmdline.push_back("-Pdebug_keystore_alias=" + debug_user); // argument to specify the debug keystore alias.3806cmdline.push_back("-Pdebug_keystore_password=" + debug_password); // argument to specify the debug keystore password.3807} else {3808// Pass the release keystore info as well3809String release_keystore = _get_keystore_path(p_preset, false);3810String release_username = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);3811String release_password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);3812if (release_keystore.is_relative_path()) {3813release_keystore = OS::get_singleton()->get_resource_dir().path_join(release_keystore).simplify_path();3814}3815if (!FileAccess::exists(release_keystore)) {3816add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find release keystore, unable to export."));3817return ERR_FILE_CANT_OPEN;3818}38193820cmdline.push_back("-Prelease_keystore_file=" + release_keystore); // argument to specify the release keystore file.3821cmdline.push_back("-Prelease_keystore_alias=" + release_username); // argument to specify the release keystore alias.3822cmdline.push_back("-Prelease_keystore_password=" + release_password); // argument to specify the release keystore password.3823}3824}38253826String build_project_output;3827int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline, true, false, &build_project_output);3828if (result != 0) {3829add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Building of Android project failed, check output for the error:") + "\n\n" + build_project_output);3830return ERR_CANT_CREATE;3831} else {3832print_verbose(build_project_output);3833}38343835List<String> copy_args;3836String copy_command = "copyAndRenameBinary";3837copy_args.push_back(copy_command);38383839copy_args.push_back("-p"); // argument to specify the start directory.3840copy_args.push_back(build_path); // start directory.38413842copy_args.push_back("-Pexport_edition=" + edition.to_lower());38433844copy_args.push_back("-Pexport_build_type=" + build_type.to_lower());38453846String export_format_arg = export_format == EXPORT_FORMAT_AAB ? "aab" : "apk";3847copy_args.push_back("-Pexport_format=" + export_format_arg);38483849String export_filename = p_path.get_file();3850String export_path = p_path.get_base_dir();3851if (export_path.is_relative_path()) {3852export_path = OS::get_singleton()->get_resource_dir().path_join(export_path);3853}3854export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path();38553856copy_args.push_back("-Pexport_path=file:" + export_path);3857copy_args.push_back("-Pexport_filename=" + export_filename);38583859print_verbose("Copying Android binary using gradle command: " + String("\n") + build_command + " " + join_list(copy_args, String(" ")));3860String copy_binary_output;3861int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args, true, false, ©_binary_output);3862if (copy_result != 0) {3863add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to copy and rename export file:") + "\n\n" + copy_binary_output);3864return ERR_CANT_CREATE;3865} else {3866print_verbose(copy_binary_output);3867}38683869print_verbose("Successfully completed Android gradle build.");3870return OK;3871}3872// This is the start of the Legacy build system3873print_verbose("Starting legacy build system...");3874if (p_debug) {3875src_apk = p_preset->get("custom_template/debug");3876} else {3877src_apk = p_preset->get("custom_template/release");3878}3879src_apk = src_apk.strip_edges();3880if (src_apk.is_empty()) {3881if (p_debug) {3882src_apk = find_export_template("android_debug.apk");3883} else {3884src_apk = find_export_template("android_release.apk");3885}3886if (src_apk.is_empty()) {3887add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(p_debug ? TTR("Debug export template not found: \"%s\".") : TTR("Release export template not found: \"%s\"."), src_apk));3888return ERR_FILE_NOT_FOUND;3889}3890}38913892Ref<FileAccess> io_fa;3893zlib_filefunc_def io = zipio_create_io(&io_fa);38943895if (ep.step(TTR("Creating APK..."), 0)) {3896return ERR_SKIP;3897}38983899unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);3900if (!pkg) {3901add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not find template APK to export: \"%s\"."), src_apk));3902return ERR_FILE_NOT_FOUND;3903}39043905int ret = unzGoToFirstFile(pkg);39063907Ref<FileAccess> io2_fa;3908zlib_filefunc_def io2 = zipio_create_io(&io2_fa);39093910String tmp_unaligned_path = EditorPaths::get_singleton()->get_temp_dir().path_join("tmpexport-unaligned." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");39113912#define CLEANUP_AND_RETURN(m_err) \3913{ \3914DirAccess::remove_file_or_error(tmp_unaligned_path); \3915return m_err; \3916} \3917((void)0)39183919zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);39203921String cmdline = p_preset->get("command_line/extra_args");39223923String version_name = p_preset->get_version("version/name");3924String package_name = p_preset->get("package/unique_name");39253926String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");39273928Vector<ABI> invalid_abis(enabled_abis);39293930//To temporarily store icon xml data.3931Vector<uint8_t> themed_icon_xml_data;3932int icon_xml_compression_method = -1;39333934while (ret == UNZ_OK) {3935//get filename3936unz_file_info info;3937char fname[16384];3938ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);3939if (ret != UNZ_OK) {3940break;3941}39423943bool skip = false;39443945String file = String::utf8(fname);39463947Vector<uint8_t> data;3948data.resize(info.uncompressed_size);39493950//read3951unzOpenCurrentFile(pkg);3952unzReadCurrentFile(pkg, data.ptrw(), data.size());3953unzCloseCurrentFile(pkg);39543955//write3956if (file == "AndroidManifest.xml") {3957_fix_manifest(p_preset, data, p_give_internet);39583959// Allow editor export plugins to update the prebuilt manifest as needed.3960Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3961for (int i = 0; i < export_plugins.size(); i++) {3962if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3963PackedByteArray export_plugin_data = export_plugins[i]->update_android_prebuilt_manifest(Ref<EditorExportPlatform>(this), data);3964if (!export_plugin_data.is_empty()) {3965data = export_plugin_data;3966}3967}3968}3969}3970if (file == "resources.arsc") {3971_fix_resources(p_preset, data);3972}39733974if (file == THEMED_ICON_XML_PATH) {3975// Store themed_icon.xml data.3976themed_icon_xml_data = data;3977skip = true;3978}39793980if (file == ICON_XML_PATH) {3981if (monochrome.is_valid() && !monochrome->is_empty()) {3982// Defer processing of icon.xml until after themed_icon.xml is read.3983icon_xml_compression_method = info.compression_method;3984skip = true;3985}3986}39873988if (file.ends_with(".png") && file.contains("mipmap")) {3989for (int i = 0; i < ICON_DENSITIES_COUNT; ++i) {3990if (main_image.is_valid() && !main_image->is_empty()) {3991if (file == LAUNCHER_ICONS[i].export_path) {3992_process_launcher_icons(file, main_image, LAUNCHER_ICONS[i].dimensions, data);3993}3994}3995if (foreground.is_valid() && !foreground->is_empty()) {3996if (file == LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].export_path) {3997_process_launcher_icons(file, foreground, LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].dimensions, data);3998}3999}4000if (background.is_valid() && !background->is_empty()) {4001if (file == LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].export_path) {4002_process_launcher_icons(file, background, LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].dimensions, data);4003}4004}4005if (monochrome.is_valid() && !monochrome->is_empty()) {4006if (file == LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].export_path) {4007_process_launcher_icons(file, monochrome, LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].dimensions, data);4008}4009}4010}4011}40124013if (file.ends_with(".so")) {4014bool enabled = false;4015for (int i = 0; i < enabled_abis.size(); ++i) {4016if (file.begins_with("lib/" + enabled_abis[i].abi + "/")) {4017invalid_abis.erase(enabled_abis[i]);4018enabled = true;4019break;4020}4021}4022if (!enabled) {4023skip = true;4024}4025}40264027if (file.begins_with("META-INF") && should_sign) {4028skip = true;4029}40304031if (!skip) {4032print_line("ADDING: " + file);40334034// Respect decision on compression made by AAPT for the export template4035const bool uncompressed = info.compression_method == 0;40364037zip_fileinfo zipfi = get_zip_fileinfo();40384039zipOpenNewFileInZip(unaligned_apk,4040file.utf8().get_data(),4041&zipfi,4042nullptr,40430,4044nullptr,40450,4046nullptr,4047uncompressed ? 0 : Z_DEFLATED,4048Z_DEFAULT_COMPRESSION);40494050zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());4051zipCloseFileInZip(unaligned_apk);4052}40534054ret = unzGoToNextFile(pkg);4055}40564057// Process deferred icon.xml and replace it's data with themed_icon.xml.4058if (monochrome.is_valid() && !monochrome->is_empty()) {4059print_line("ADDING: " + ICON_XML_PATH + " (replacing with themed_icon.xml data)");40604061const bool uncompressed = icon_xml_compression_method == 0;4062zip_fileinfo zipfi = get_zip_fileinfo();40634064zipOpenNewFileInZip(unaligned_apk,4065ICON_XML_PATH.utf8().get_data(),4066&zipfi,4067nullptr,40680,4069nullptr,40700,4071nullptr,4072uncompressed ? 0 : Z_DEFLATED,4073Z_DEFAULT_COMPRESSION);40744075zipWriteInFileInZip(unaligned_apk, themed_icon_xml_data.ptr(), themed_icon_xml_data.size());4076zipCloseFileInZip(unaligned_apk);4077}40784079if (!invalid_abis.is_empty()) {4080add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Missing libraries in the export template for the selected architectures: %s. Please build a template with all required libraries, or uncheck the missing architectures in the export preset."), join_abis(invalid_abis, ", ", false)));4081CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);4082}40834084if (ep.step(TTR("Adding files..."), 1)) {4085CLEANUP_AND_RETURN(ERR_SKIP);4086}4087err = OK;40884089if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {4090APKExportData ed;4091ed.ep = &ep;4092ed.apk = unaligned_apk;4093err = export_project_files(p_preset, p_debug, ignore_apk_file, nullptr, &ed, save_apk_so);4094} else {4095if (apk_expansion) {4096err = save_apk_expansion_file(p_preset, p_debug, p_path);4097if (err != OK) {4098add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));4099return err;4100}4101} else {4102APKExportData ed;4103ed.ep = &ep;4104ed.apk = unaligned_apk;4105ed.pd.path = "assets.sparsepck";4106ed.pd.use_sparse_pck = true;4107err = export_project_files(p_preset, p_debug, save_apk_file, nullptr, &ed, save_apk_so);41084109Vector<uint8_t> enc_data;4110err = _generate_sparse_pck_metadata(p_preset, ed.pd, enc_data);4111if (err != OK) {4112add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not generate sparse pck metadata!"));4113return err;4114}41154116store_in_apk(&ed, "assets/assets.sparsepck", enc_data, 0);4117}4118}41194120if (err != OK) {4121unzClose(pkg);4122add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not export project files.")));4123CLEANUP_AND_RETURN(ERR_SKIP);4124}41254126zip_fileinfo zipfi = get_zip_fileinfo();4127zipOpenNewFileInZip(unaligned_apk,4128"assets/_cl_",4129&zipfi,4130nullptr,41310,4132nullptr,41330,4134nullptr,41350, // No compress (little size gain and potentially slower startup)4136Z_DEFAULT_COMPRESSION);4137zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());4138zipCloseFileInZip(unaligned_apk);4139zipClose(unaligned_apk, nullptr);4140unzClose(pkg);41414142// Let's zip-align (must be done before signing)41434144static const int PAGE_SIZE_KB = 16 * 1024;4145static const int ZIP_ALIGNMENT = 4;41464147// If we're not signing the apk, then the next step should be the last.4148const int next_step = should_sign ? 103 : 105;4149if (ep.step(TTR("Aligning APK..."), next_step)) {4150CLEANUP_AND_RETURN(ERR_SKIP);4151}41524153unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);4154if (!tmp_unaligned) {4155add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not unzip temporary unaligned APK.")));4156CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);4157}41584159ret = unzGoToFirstFile(tmp_unaligned);41604161io2 = zipio_create_io(&io2_fa);4162zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);41634164// Take files from the unaligned APK and write them out to the aligned one4165// in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,4166// following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp4167int bias = 0;4168while (ret == UNZ_OK) {4169unz_file_info info;4170memset(&info, 0, sizeof(info));41714172char fname[16384];4173char extra[16384];4174ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0);4175if (ret != UNZ_OK) {4176break;4177}41784179String file = String::utf8(fname);41804181Vector<uint8_t> data;4182data.resize(info.compressed_size);41834184// read4185int method, level;4186unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read4187long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);4188unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());4189unzCloseCurrentFile(tmp_unaligned);41904191// align4192int padding = 0;4193if (!info.compression_method) {4194// Uncompressed file => Align4195long new_offset = file_offset + bias;4196const char *ext = strrchr(fname, '.');4197if (ext && strcmp(ext, ".so") == 0) {4198padding = (PAGE_SIZE_KB - (new_offset % PAGE_SIZE_KB)) % PAGE_SIZE_KB;4199} else {4200padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;4201}4202}42034204memset(extra + info.size_file_extra, 0, padding);42054206zip_fileinfo fileinfo = get_zip_fileinfo();4207zipOpenNewFileInZip2(final_apk,4208file.utf8().get_data(),4209&fileinfo,4210extra,4211info.size_file_extra + padding,4212nullptr,42130,4214nullptr,4215method,4216level,42171); // raw write4218zipWriteInFileInZip(final_apk, data.ptr(), data.size());4219zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);42204221bias += padding;42224223ret = unzGoToNextFile(tmp_unaligned);4224}42254226zipClose(final_apk, nullptr);4227unzClose(tmp_unaligned);42284229if (should_sign) {4230// Signing must be done last as any additional modifications to the4231// file will invalidate the signature.4232err = sign_apk(p_preset, p_debug, p_path, ep);4233if (err != OK) {4234// Message is supplied by the subroutine method.4235CLEANUP_AND_RETURN(err);4236}4237}42384239CLEANUP_AND_RETURN(OK);4240}42414242void EditorExportPlatformAndroid::get_platform_features(List<String> *r_features) const {4243r_features->push_back("mobile");4244r_features->push_back("android");4245}42464247void EditorExportPlatformAndroid::resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, HashSet<String> &p_features) {4248}42494250EditorExportPlatformAndroid::EditorExportPlatformAndroid() {4251if (EditorNode::get_singleton()) {4252Ref<Image> img = memnew(Image);4253const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE);42544255ImageLoaderSVG::create_image_from_string(img, _android_logo_svg, EDSCALE, upsample, false);4256logo = ImageTexture::create_from_image(img);42574258ImageLoaderSVG::create_image_from_string(img, _android_run_icon_svg, EDSCALE, upsample, false);4259run_icon = ImageTexture::create_from_image(img);42604261devices_changed.set();4262#ifndef DISABLE_DEPRECATED4263android_plugins_changed.set();4264#endif // DISABLE_DEPRECATED4265#ifndef ANDROID_ENABLED4266_create_editor_debug_keystore_if_needed();4267_update_preset_status();4268check_for_changes_thread.start(_check_for_changes_poll_thread, this);4269#endif4270}4271}42724273EditorExportPlatformAndroid::~EditorExportPlatformAndroid() {4274#ifndef ANDROID_ENABLED4275quit_request.set();4276if (check_for_changes_thread.is_started()) {4277check_for_changes_thread.wait_to_finish();4278}4279#endif4280}428142824283