Path: blob/master/platform/android/export/export_plugin.cpp
11353 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.28542855if (p_debug) {2856String dk = _get_keystore_path(p_preset, true);2857String dk_user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);2858String dk_password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);28592860if ((dk.is_empty() || dk_user.is_empty() || dk_password.is_empty()) && (!dk.is_empty() || !dk_user.is_empty() || !dk_password.is_empty())) {2861valid = false;2862err += TTR("Either Debug Keystore, Debug User AND Debug Password settings must be configured OR none of them.") + "\n";2863}28642865// Use OR to make the export UI able to show this error.2866if (!dk.is_empty() && !FileAccess::exists(dk)) {2867dk = EDITOR_GET("export/android/debug_keystore");2868if (!FileAccess::exists(dk)) {2869valid = false;2870err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";2871}2872}2873} else {2874String rk = _get_keystore_path(p_preset, false);2875String rk_user = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);2876String rk_password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);28772878if ((rk.is_empty() || rk_user.is_empty() || rk_password.is_empty()) && (!rk.is_empty() || !rk_user.is_empty() || !rk_password.is_empty())) {2879valid = false;2880err += TTR("Either Release Keystore, Release User AND Release Password settings must be configured OR none of them.") + "\n";2881}28822883if (!rk.is_empty() && !FileAccess::exists(rk)) {2884valid = false;2885err += TTR("Release keystore incorrectly configured in the export preset.") + "\n";2886}2887}28882889#ifndef ANDROID_ENABLED2890String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");2891if (java_sdk_path.is_empty()) {2892err += TTR("A valid Java SDK path is required in Editor Settings.") + "\n";2893valid = false;2894} else {2895// Validate the given path by checking that `java` is present under the `bin` directory.2896Error errn;2897// Check for the bin directory.2898Ref<DirAccess> da = DirAccess::open(java_sdk_path.path_join("bin"), &errn);2899if (errn != OK) {2900err += TTR("Invalid Java SDK path in Editor Settings.") + " ";2901err += TTR("Missing 'bin' directory!");2902err += "\n";2903valid = false;2904} else {2905// Check for the `java` command.2906String java_path = get_java_path();2907if (!FileAccess::exists(java_path)) {2908err += TTR("Unable to find 'java' command using the Java SDK path.") + " ";2909err += TTR("Please check the Java SDK directory specified in Editor Settings.");2910err += "\n";2911valid = false;2912}2913}2914}29152916String sdk_path = EDITOR_GET("export/android/android_sdk_path");2917if (sdk_path.is_empty()) {2918err += TTR("A valid Android SDK path is required in Editor Settings.") + "\n";2919valid = false;2920} else {2921Error errn;2922// Check for the platform-tools directory.2923Ref<DirAccess> da = DirAccess::open(sdk_path.path_join("platform-tools"), &errn);2924if (errn != OK) {2925err += TTR("Invalid Android SDK path in Editor Settings.") + " ";2926err += TTR("Missing 'platform-tools' directory!");2927err += "\n";2928valid = false;2929}29302931// Validate that adb is available.2932String adb_path = get_adb_path();2933if (!FileAccess::exists(adb_path)) {2934err += TTR("Unable to find Android SDK platform-tools' adb command.") + " ";2935err += TTR("Please check in the Android SDK directory specified in Editor Settings.");2936err += "\n";2937valid = false;2938}29392940// Check for the build-tools directory.2941Ref<DirAccess> build_tools_da = DirAccess::open(sdk_path.path_join("build-tools"), &errn);2942if (errn != OK) {2943err += TTR("Invalid Android SDK path in Editor Settings.") + " ";2944err += TTR("Missing 'build-tools' directory!");2945err += "\n";2946valid = false;2947}29482949String target_sdk_version = p_preset->get("gradle_build/target_sdk");2950if (!target_sdk_version.is_valid_int()) {2951target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);2952}2953// Validate that apksigner is available.2954String apksigner_path = get_apksigner_path(target_sdk_version.to_int());2955if (!FileAccess::exists(apksigner_path)) {2956err += TTR("Unable to find Android SDK build-tools' apksigner command.") + " ";2957err += TTR("Please check in the Android SDK directory specified in Editor Settings.");2958err += "\n";2959valid = false;2960}2961}2962#endif29632964if (!err.is_empty()) {2965r_error = err;2966}29672968return valid;2969}29702971bool EditorExportPlatformAndroid::has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const {2972String err;2973bool valid = true;29742975List<ExportOption> options;2976get_export_options(&options);2977for (const EditorExportPlatform::ExportOption &E : options) {2978if (get_export_option_visibility(p_preset.ptr(), E.option.name)) {2979String warn = get_export_option_warning(p_preset.ptr(), E.option.name);2980if (!warn.is_empty()) {2981err += warn + "\n";2982if (E.required) {2983valid = false;2984}2985}2986}2987}29882989if (!ResourceImporterTextureSettings::should_import_etc2_astc()) {2990valid = false;2991}29922993bool gradle_build_enabled = p_preset->get("gradle_build/use_gradle_build");2994if (gradle_build_enabled) {2995String build_version_path = ExportTemplateManager::get_android_build_directory(p_preset).get_base_dir().path_join(".build_version");2996Ref<FileAccess> f = FileAccess::open(build_version_path, FileAccess::READ);2997if (f.is_valid()) {2998String current_version = ExportTemplateManager::get_android_template_identifier(p_preset);2999String installed_version = f->get_line().strip_edges();3000if (current_version != installed_version) {3001err += vformat(TTR(MISMATCHED_VERSIONS_MESSAGE), installed_version, current_version);3002err += "\n";3003}3004}3005} else {3006if (_is_transparency_allowed(p_preset)) {3007// Warning only, so don't override `valid`.3008err += vformat(TTR("\"Use Gradle Build\" is required for transparent background on Android"));3009err += "\n";3010}3011}30123013String target_sdk_str = p_preset->get("gradle_build/target_sdk");3014int target_sdk_int = DEFAULT_TARGET_SDK_VERSION;3015if (!target_sdk_str.is_empty()) { // Empty means no override, nothing to do.3016if (target_sdk_str.is_valid_int()) {3017target_sdk_int = target_sdk_str.to_int();3018if (target_sdk_int > DEFAULT_TARGET_SDK_VERSION) {3019// Warning only, so don't override `valid`.3020err += 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);3021err += "\n";3022}3023}3024}30253026String current_renderer = get_project_setting(p_preset, "rendering/renderer/rendering_method.mobile");3027if (current_renderer == "forward_plus") {3028// Warning only, so don't override `valid`.3029err += vformat(TTR("The \"%s\" renderer is designed for Desktop devices, and is not suitable for Android devices."), current_renderer);3030err += "\n";3031}30323033String package_name = p_preset->get("package/unique_name");3034if (package_name.contains("$genname") && !is_project_name_valid(p_preset)) {3035// Warning only, so don't override `valid`.3036err += 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));3037err += "\n";3038}30393040r_error = err;3041return valid;3042}30433044List<String> EditorExportPlatformAndroid::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {3045List<String> list;3046list.push_back("apk");3047list.push_back("aab");3048return list;3049}30503051String EditorExportPlatformAndroid::get_apk_expansion_fullpath(const Ref<EditorExportPreset> &p_preset, const String &p_path) {3052int version_code = p_preset->get("version/code");3053String package_name = p_preset->get("package/unique_name");3054String apk_file_name = "main." + itos(version_code) + "." + get_package_name(p_preset, package_name) + ".obb";3055String fullpath = p_path.get_base_dir().path_join(apk_file_name);3056return fullpath;3057}30583059Error EditorExportPlatformAndroid::save_apk_expansion_file(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {3060String fullpath = get_apk_expansion_fullpath(p_preset, p_path);3061Error err = save_pack(p_preset, p_debug, fullpath);3062return err;3063}30643065void 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) {3066String cmdline = p_preset->get("command_line/extra_args");3067Vector<String> command_line_strings = cmdline.strip_edges().split(" ");3068for (int i = 0; i < command_line_strings.size(); i++) {3069if (command_line_strings[i].strip_edges().length() == 0) {3070command_line_strings.remove_at(i);3071i--;3072}3073}30743075command_line_strings.append_array(gen_export_flags(p_flags));30763077bool apk_expansion = p_preset->get("apk_expansion/enable");3078if (apk_expansion) {3079String fullpath = get_apk_expansion_fullpath(p_preset, p_path);3080String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");30813082command_line_strings.push_back("--use_apk_expansion");3083command_line_strings.push_back("--apk_expansion_md5");3084command_line_strings.push_back(FileAccess::get_md5(fullpath));3085command_line_strings.push_back("--apk_expansion_key");3086command_line_strings.push_back(apk_expansion_public_key.strip_edges());3087}30883089int xr_mode_index = p_preset->get("xr_features/xr_mode");3090if (xr_mode_index == XR_MODE_OPENXR) {3091command_line_strings.push_back("--xr_mode_openxr");3092} else { // XRMode.REGULAR is the default.3093command_line_strings.push_back("--xr_mode_regular");30943095// Also override the 'xr/openxr/enabled' project setting.3096// This is useful for multi-platforms projects supporting both XR and non-XR devices. The project would need3097// to enable openxr for development, and would create multiple XR and non-XR export presets.3098// These command line args ensure that the non-XR export presets will have openxr disabled.3099command_line_strings.push_back("--xr-mode");3100command_line_strings.push_back("off");3101}31023103bool immersive = p_preset->get("screen/immersive_mode");3104if (immersive) {3105command_line_strings.push_back("--fullscreen");3106}31073108bool edge_to_edge = p_preset->get("screen/edge_to_edge");3109if (edge_to_edge) {3110command_line_strings.push_back("--edge_to_edge");3111}31123113String background_color = "#" + p_preset->get("screen/background_color").operator Color().to_html(false);31143115// For Gradle build, _fix_themes_xml() sets background to transparent if _is_transparency_allowed().3116// Overriding to transparent here too as it's used as fallback for system bar appearance.3117if (_is_transparency_allowed(p_preset) && p_preset->get("gradle_build/use_gradle_build")) {3118background_color = "#00000000";3119}3120command_line_strings.push_back("--background_color");3121command_line_strings.push_back(background_color);31223123bool debug_opengl = p_preset->get("graphics/opengl_debug");3124if (debug_opengl) {3125command_line_strings.push_back("--debug_opengl");3126}31273128if (command_line_strings.size()) {3129r_command_line_flags.resize(4);3130encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);3131for (int i = 0; i < command_line_strings.size(); i++) {3132print_line(itos(i) + " param: " + command_line_strings[i]);3133CharString command_line_argument = command_line_strings[i].utf8();3134int base = r_command_line_flags.size();3135int length = command_line_argument.length();3136if (length == 0) {3137continue;3138}3139r_command_line_flags.resize(base + 4 + length);3140encode_uint32(length, &r_command_line_flags.write[base]);3141memcpy(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);3142}3143}3144}31453146Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &export_path, EditorProgress &ep) {3147int export_format = int(p_preset->get("gradle_build/export_format"));3148if (export_format == EXPORT_FORMAT_AAB) {3149add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("AAB signing is not supported"));3150return FAILED;3151}31523153String keystore;3154String password;3155String user;3156if (p_debug) {3157keystore = _get_keystore_path(p_preset, true);3158password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);3159user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);31603161if (keystore.is_empty()) {3162keystore = EDITOR_GET("export/android/debug_keystore");3163password = EDITOR_GET("export/android/debug_keystore_pass");3164user = EDITOR_GET("export/android/debug_keystore_user");3165}31663167if (ep.step(TTR("Signing debug APK..."), 104)) {3168return ERR_SKIP;3169}3170} else {3171keystore = _get_keystore_path(p_preset, false);3172password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);3173user = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);31743175if (ep.step(TTR("Signing release APK..."), 104)) {3176return ERR_SKIP;3177}3178}31793180if (!FileAccess::exists(keystore)) {3181if (p_debug) {3182add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not find debug keystore, unable to export."));3183} else {3184add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not find release keystore, unable to export."));3185}3186return ERR_FILE_CANT_OPEN;3187}31883189String apk_path = export_path;3190if (apk_path.is_relative_path()) {3191apk_path = OS::get_singleton()->get_resource_dir().path_join(apk_path);3192}3193apk_path = ProjectSettings::get_singleton()->globalize_path(apk_path).simplify_path();31943195Error err;3196#ifdef ANDROID_ENABLED3197err = OS_Android::get_singleton()->sign_apk(apk_path, apk_path, keystore, user, password);3198if (err != OK) {3199add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Unable to sign apk."));3200return err;3201}3202#else3203String target_sdk_version = p_preset->get("gradle_build/target_sdk");3204if (!target_sdk_version.is_valid_int()) {3205target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);3206}32073208String apksigner = get_apksigner_path(target_sdk_version.to_int(), true);3209print_verbose("Starting signing of the APK binary using " + apksigner);3210if (apksigner == "<FAILED>") {3211add_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."));3212return OK;3213}3214if (!FileAccess::exists(apksigner)) {3215add_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."));3216return OK;3217}32183219String output;3220List<String> args;3221args.push_back("sign");3222args.push_back("--verbose");3223args.push_back("--ks");3224args.push_back(keystore);3225args.push_back("--ks-pass");3226args.push_back("pass:" + password);3227args.push_back("--ks-key-alias");3228args.push_back(user);3229args.push_back(apk_path);3230if (OS::get_singleton()->is_stdout_verbose() && p_debug) {3231// We only print verbose logs with credentials for debug builds to avoid leaking release keystore credentials.3232print_verbose("Signing debug binary using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));3233} else {3234List<String> redacted_args = List<String>(args);3235redacted_args.find(keystore)->set("<REDACTED>");3236redacted_args.find("pass:" + password)->set("pass:<REDACTED>");3237redacted_args.find(user)->set("<REDACTED>");3238print_line("Signing binary using: " + String("\n") + apksigner + " " + join_list(redacted_args, String(" ")));3239}3240int retval;3241err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);3242if (err != OK) {3243add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));3244return err;3245}3246// By design, apksigner does not output credentials in its output unless --verbose is used3247print_line(output);3248if (retval) {3249add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("'apksigner' returned with error #%d"), retval));3250add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));3251return ERR_CANT_CREATE;3252}3253#endif32543255if (ep.step(TTR("Verifying APK..."), 105)) {3256return ERR_SKIP;3257}32583259#ifdef ANDROID_ENABLED3260err = OS_Android::get_singleton()->verify_apk(apk_path);3261if (err != OK) {3262add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Unable to verify signed apk."));3263return err;3264}3265#else3266args.clear();3267args.push_back("verify");3268args.push_back("--verbose");3269args.push_back(apk_path);3270if (p_debug) {3271print_verbose("Verifying signed build using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));3272}32733274output.clear();3275err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);3276if (err != OK) {3277add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));3278return err;3279}3280print_verbose(output);3281if (retval) {3282add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("'apksigner' verification of APK failed."));3283add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));3284return ERR_CANT_CREATE;3285}3286#endif32873288print_verbose("Successfully completed signing build.");32893290#ifdef ANDROID_ENABLED3291bool prompt_apk_install = EDITOR_GET("export/android/install_exported_apk");3292if (prompt_apk_install) {3293OS_Android::get_singleton()->shell_open(apk_path);3294}3295#endif32963297return OK;3298}32993300void EditorExportPlatformAndroid::_clear_assets_directory(const Ref<EditorExportPreset> &p_preset) {3301Ref<DirAccess> da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);3302String gradle_build_directory = ExportTemplateManager::get_android_build_directory(p_preset);33033304// Clear the APK assets directory3305String apk_assets_directory = gradle_build_directory.path_join(APK_ASSETS_DIRECTORY);3306if (da_res->dir_exists(apk_assets_directory)) {3307print_verbose("Clearing APK assets directory...");3308Ref<DirAccess> da_assets = DirAccess::open(apk_assets_directory);3309ERR_FAIL_COND(da_assets.is_null());33103311da_assets->erase_contents_recursive();3312da_res->remove(apk_assets_directory);3313}33143315// Clear the AAB assets directory3316String aab_assets_directory = gradle_build_directory.path_join(AAB_ASSETS_DIRECTORY);3317if (da_res->dir_exists(aab_assets_directory)) {3318print_verbose("Clearing AAB assets directory...");3319Ref<DirAccess> da_assets = DirAccess::open(aab_assets_directory);3320ERR_FAIL_COND(da_assets.is_null());33213322da_assets->erase_contents_recursive();3323da_res->remove(aab_assets_directory);3324}3325}33263327void EditorExportPlatformAndroid::_remove_copied_libs(String p_gdextension_libs_path) {3328print_verbose("Removing previously installed libraries...");3329Error error;3330String libs_json = FileAccess::get_file_as_string(p_gdextension_libs_path, &error);3331if (error || libs_json.is_empty()) {3332print_verbose("No previously installed libraries found");3333return;3334}33353336JSON json;3337error = json.parse(libs_json);3338ERR_FAIL_COND_MSG(error, "Error parsing \"" + libs_json + "\" on line " + itos(json.get_error_line()) + ": " + json.get_error_message());33393340Vector<String> libs = json.get_data();3341Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);3342for (int i = 0; i < libs.size(); i++) {3343print_verbose("Removing previously installed library " + libs[i]);3344da->remove(libs[i]);3345}3346da->remove(p_gdextension_libs_path);3347}33483349String EditorExportPlatformAndroid::join_list(const List<String> &p_parts, const String &p_separator) {3350String ret;3351for (List<String>::ConstIterator itr = p_parts.begin(); itr != p_parts.end(); ++itr) {3352if (itr != p_parts.begin()) {3353ret += p_separator;3354}3355ret += *itr;3356}3357return ret;3358}33593360String EditorExportPlatformAndroid::join_abis(const Vector<EditorExportPlatformAndroid::ABI> &p_parts, const String &p_separator, bool p_use_arch) {3361String ret;3362for (int i = 0; i < p_parts.size(); ++i) {3363if (i > 0) {3364ret += p_separator;3365}3366ret += (p_use_arch) ? p_parts[i].arch : p_parts[i].abi;3367}3368return ret;3369}33703371String EditorExportPlatformAndroid::_get_deprecated_plugins_names(const Ref<EditorExportPreset> &p_preset) const {3372Vector<String> names;33733374#ifndef DISABLE_DEPRECATED3375PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset), names);3376#endif // DISABLE_DEPRECATED33773378String plugins_names = String("|").join(names);3379return plugins_names;3380}33813382String EditorExportPlatformAndroid::_get_plugins_names(const Ref<EditorExportPreset> &p_preset) const {3383Vector<String> names;33843385#ifndef DISABLE_DEPRECATED3386PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset), names);3387#endif // DISABLE_DEPRECATED33883389Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3390for (int i = 0; i < export_plugins.size(); i++) {3391if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3392names.push_back(export_plugins[i]->get_name());3393}3394}33953396String plugins_names = String("|").join(names);3397return plugins_names;3398}33993400String EditorExportPlatformAndroid::_resolve_export_plugin_android_library_path(const String &p_android_library_path) const {3401String absolute_path;3402if (!p_android_library_path.is_empty()) {3403if (p_android_library_path.is_absolute_path()) {3404absolute_path = ProjectSettings::get_singleton()->globalize_path(p_android_library_path);3405} else {3406const String export_plugin_absolute_path = String("res://addons/").path_join(p_android_library_path);3407absolute_path = ProjectSettings::get_singleton()->globalize_path(export_plugin_absolute_path);3408}3409}3410return absolute_path;3411}34123413bool EditorExportPlatformAndroid::_is_clean_build_required(const Ref<EditorExportPreset> &p_preset) {3414bool first_build = last_gradle_build_time == 0;3415bool have_plugins_changed = false;3416String gradle_build_dir = ExportTemplateManager::get_android_build_directory(p_preset);3417bool has_build_dir_changed = last_gradle_build_dir != gradle_build_dir;34183419String plugin_names = _get_plugins_names(p_preset);34203421if (!first_build) {3422have_plugins_changed = plugin_names != last_plugin_names;3423#ifndef DISABLE_DEPRECATED3424if (!have_plugins_changed) {3425Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);3426for (int i = 0; i < enabled_plugins.size(); i++) {3427if (enabled_plugins.get(i).last_updated > last_gradle_build_time) {3428have_plugins_changed = true;3429break;3430}3431}3432}3433#endif // DISABLE_DEPRECATED3434}34353436last_gradle_build_time = OS::get_singleton()->get_unix_time();3437last_gradle_build_dir = gradle_build_dir;3438last_plugin_names = plugin_names;34393440return have_plugins_changed || has_build_dir_changed || first_build;3441}34423443Error EditorExportPlatformAndroid::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {3444int export_format = int(p_preset->get("gradle_build/export_format"));3445bool should_sign = p_preset->get("package/signed");3446return export_project_helper(p_preset, p_debug, p_path, export_format, should_sign, p_flags);3447}34483449Error EditorExportPlatformAndroid::_generate_sparse_pck_metadata(const Ref<EditorExportPreset> &p_preset, PackData &p_pack_data, Vector<uint8_t> &r_data) {3450Error err;3451Ref<FileAccess> ftmp = FileAccess::create_temp(FileAccess::WRITE_READ, "export_index", "tmp", false, &err);3452if (err != OK) {3453add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not create temporary file!"));3454return err;3455}3456int64_t pck_start_pos = ftmp->get_position();3457uint64_t file_base_ofs = 0;3458uint64_t dir_base_ofs = 0;3459EditorExportPlatform::_store_header(ftmp, p_preset->get_enc_pck() && p_preset->get_enc_directory(), true, file_base_ofs, dir_base_ofs);34603461// Write directory.3462uint64_t dir_offset = ftmp->get_position();3463ftmp->seek(dir_base_ofs);3464ftmp->store_64(dir_offset - pck_start_pos);3465ftmp->seek(dir_offset);34663467Vector<uint8_t> key;3468if (p_preset->get_enc_pck() && p_preset->get_enc_directory()) {3469String script_key = _get_script_encryption_key(p_preset);3470key.resize(32);3471if (script_key.length() == 64) {3472for (int i = 0; i < 32; i++) {3473int v = 0;3474if (i * 2 < script_key.length()) {3475char32_t ct = script_key[i * 2];3476if (is_digit(ct)) {3477ct = ct - '0';3478} else if (ct >= 'a' && ct <= 'f') {3479ct = 10 + ct - 'a';3480}3481v |= ct << 4;3482}34833484if (i * 2 + 1 < script_key.length()) {3485char32_t ct = script_key[i * 2 + 1];3486if (is_digit(ct)) {3487ct = ct - '0';3488} else if (ct >= 'a' && ct <= 'f') {3489ct = 10 + ct - 'a';3490}3491v |= ct;3492}3493key.write[i] = v;3494}3495}3496}34973498if (!EditorExportPlatform::_encrypt_and_store_directory(ftmp, p_pack_data, key, p_preset->get_seed(), 0)) {3499add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Can't create encrypted file."));3500return ERR_CANT_CREATE;3501}35023503r_data.resize(ftmp->get_length());3504ftmp->seek(0);3505ftmp->get_buffer(r_data.ptrw(), r_data.size());3506ftmp.unref();35073508return OK;3509}35103511Error 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) {3512ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);35133514const String base_dir = p_path.get_base_dir();3515if (!DirAccess::exists(base_dir)) {3516add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Target folder does not exist or is inaccessible: \"%s\""), base_dir));3517return ERR_FILE_BAD_PATH;3518}35193520String src_apk;3521Error err;35223523EditorProgress ep("export", TTR("Exporting for Android"), 105, true);35243525bool use_gradle_build = bool(p_preset->get("gradle_build/use_gradle_build"));3526String gradle_build_directory = use_gradle_build ? ExportTemplateManager::get_android_build_directory(p_preset) : "";3527bool p_give_internet = p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT) || p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG);3528bool apk_expansion = p_preset->get("apk_expansion/enable");3529Vector<ABI> enabled_abis = get_enabled_abis(p_preset);35303531print_verbose("Exporting for Android...");3532print_verbose("- debug build: " + bool_to_string(p_debug));3533print_verbose("- export path: " + p_path);3534print_verbose("- export format: " + itos(export_format));3535print_verbose("- sign build: " + bool_to_string(should_sign));3536print_verbose("- gradle build enabled: " + bool_to_string(use_gradle_build));3537print_verbose("- apk expansion enabled: " + bool_to_string(apk_expansion));3538print_verbose("- enabled abis: " + join_abis(enabled_abis, ",", false));3539print_verbose("- export filter: " + itos(p_preset->get_export_filter()));3540print_verbose("- include filter: " + p_preset->get_include_filter());3541print_verbose("- exclude filter: " + p_preset->get_exclude_filter());35423543Ref<Image> main_image;3544Ref<Image> foreground;3545Ref<Image> background;3546Ref<Image> monochrome;35473548load_icon_refs(p_preset, main_image, foreground, background, monochrome);35493550Vector<uint8_t> command_line_flags;3551// Write command line flags into the command_line_flags variable.3552get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);35533554if (export_format == EXPORT_FORMAT_AAB) {3555if (!p_path.ends_with(".aab")) {3556add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android App Bundle requires the *.aab extension."));3557return ERR_UNCONFIGURED;3558}3559if (apk_expansion) {3560add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("APK Expansion not compatible with Android App Bundle."));3561return ERR_UNCONFIGURED;3562}3563}3564if (export_format == EXPORT_FORMAT_APK && !p_path.ends_with(".apk")) {3565add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android APK requires the *.apk extension."));3566return ERR_UNCONFIGURED;3567}3568if (export_format > EXPORT_FORMAT_AAB || export_format < EXPORT_FORMAT_APK) {3569add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unsupported export format!"));3570return ERR_UNCONFIGURED;3571}3572String err_string;3573if (!has_valid_username_and_password(p_preset, err_string)) {3574add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR(err_string));3575return ERR_UNCONFIGURED;3576}35773578if (use_gradle_build) {3579print_verbose("Starting gradle build...");3580//test that installed build version is alright3581{3582print_verbose("Checking build version...");3583String gradle_base_directory = gradle_build_directory.get_base_dir();3584Ref<FileAccess> f = FileAccess::open(gradle_base_directory.path_join(".build_version"), FileAccess::READ);3585if (f.is_null()) {3586add_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."));3587return ERR_UNCONFIGURED;3588}3589String current_version = ExportTemplateManager::get_android_template_identifier(p_preset);3590String installed_version = f->get_line().strip_edges();3591print_verbose("- build version: " + installed_version);3592if (installed_version != current_version) {3593add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR(MISMATCHED_VERSIONS_MESSAGE), installed_version, current_version));3594return ERR_UNCONFIGURED;3595}3596}3597const String assets_directory = get_assets_directory(p_preset, export_format);3598String java_sdk_path = EDITOR_GET("export/android/java_sdk_path");3599if (java_sdk_path.is_empty()) {3600add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Java SDK path must be configured in Editor Settings at 'export/android/java_sdk_path'."));3601return ERR_UNCONFIGURED;3602}3603print_verbose("Java sdk path: " + java_sdk_path);36043605String sdk_path = EDITOR_GET("export/android/android_sdk_path");3606if (sdk_path.is_empty()) {3607add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Android SDK path must be configured in Editor Settings at 'export/android/android_sdk_path'."));3608return ERR_UNCONFIGURED;3609}3610print_verbose("Android sdk path: " + sdk_path);36113612// TODO: should we use "package/name" or "application/config/name"?3613String project_name = get_project_name(p_preset, p_preset->get("package/name"));3614err = _create_project_name_strings_files(p_preset, project_name, gradle_build_directory, get_project_setting(p_preset, "application/config/name_localized")); //project name localization.3615if (err != OK) {3616add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to overwrite res/*.xml files with project name."));3617}3618// Copies the project icon files into the appropriate Gradle project directory.3619_copy_icons_to_gradle_project(p_preset, main_image, foreground, background, monochrome);3620// Write an AndroidManifest.xml file into the Gradle project directory.3621_write_tmp_manifest(p_preset, p_give_internet, p_debug);3622// Modify res/values/themes.xml file.3623_fix_themes_xml(p_preset);36243625//stores all the project files inside the Gradle project directory. Also includes all ABIs3626_clear_assets_directory(p_preset);3627String gdextension_libs_path = gradle_build_directory.path_join(GDEXTENSION_LIBS_PATH);3628_remove_copied_libs(gdextension_libs_path);3629if (!apk_expansion) {3630print_verbose("Exporting project files...");3631CustomExportData user_data;3632user_data.assets_directory = assets_directory;3633user_data.libs_directory = gradle_build_directory.path_join("libs");3634user_data.debug = p_debug;3635if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {3636err = export_project_files(p_preset, p_debug, ignore_apk_file, nullptr, &user_data, copy_gradle_so);3637} else {3638user_data.pd.path = "assets.sparsepck";3639user_data.pd.use_sparse_pck = true;3640err = export_project_files(p_preset, p_debug, rename_and_store_file_in_gradle_project, nullptr, &user_data, copy_gradle_so);36413642Vector<uint8_t> enc_data;3643err = _generate_sparse_pck_metadata(p_preset, user_data.pd, enc_data);3644if (err != OK) {3645add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not generate sparse pck metadata!"));3646return err;3647}36483649err = store_file_at_path(user_data.assets_directory + "/assets.sparsepck", enc_data);3650if (err != OK) {3651add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not write PCK directory!"));3652return err;3653}3654}3655if (err != OK) {3656add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not export project files to gradle project."));3657return err;3658}3659if (user_data.libs.size() > 0) {3660Ref<FileAccess> fa = FileAccess::open(gdextension_libs_path, FileAccess::WRITE);3661fa->store_string(JSON::stringify(user_data.libs, "\t"));3662}3663} else {3664print_verbose("Saving apk expansion file...");3665err = save_apk_expansion_file(p_preset, p_debug, p_path);3666if (err != OK) {3667add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));3668return err;3669}3670}3671print_verbose("Storing command line flags...");3672store_file_at_path(assets_directory + "/_cl_", command_line_flags);36733674print_verbose("Updating JAVA_HOME environment to " + java_sdk_path);3675OS::get_singleton()->set_environment("JAVA_HOME", java_sdk_path);36763677print_verbose("Updating ANDROID_HOME environment to " + sdk_path);3678OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path);3679String build_command;36803681#ifdef WINDOWS_ENABLED3682build_command = "gradlew.bat";3683#else3684build_command = "gradlew";3685#endif36863687String build_path = ProjectSettings::get_singleton()->globalize_path(gradle_build_directory);3688build_command = build_path.path_join(build_command);36893690String package_name = get_package_name(p_preset, p_preset->get("package/unique_name"));3691String version_code = itos(p_preset->get("version/code"));3692String version_name = p_preset->get_version("version/name");3693String min_sdk_version = p_preset->get("gradle_build/min_sdk");3694if (!min_sdk_version.is_valid_int()) {3695min_sdk_version = itos(DEFAULT_MIN_SDK_VERSION);3696}3697String target_sdk_version = p_preset->get("gradle_build/target_sdk");3698if (!target_sdk_version.is_valid_int()) {3699target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);3700}3701String enabled_abi_string = join_abis(enabled_abis, "|", false);3702String sign_flag = bool_to_string(should_sign);3703String zipalign_flag = "true";3704String compress_native_libraries_flag = bool_to_string(p_preset->get("gradle_build/compress_native_libraries"));37053706Vector<String> android_libraries;3707Vector<String> android_dependencies;3708Vector<String> android_dependencies_maven_repos;37093710#ifndef DISABLE_DEPRECATED3711Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);3712PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_LOCAL, enabled_plugins, android_libraries);3713PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_REMOTE, enabled_plugins, android_dependencies);3714PluginConfigAndroid::get_plugins_custom_maven_repos(enabled_plugins, android_dependencies_maven_repos);3715#endif // DISABLE_DEPRECATED37163717bool has_dotnet_project = false;3718Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3719for (int i = 0; i < export_plugins.size(); i++) {3720if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3721PackedStringArray export_plugin_android_libraries = export_plugins[i]->get_android_libraries(Ref<EditorExportPlatform>(this), p_debug);3722for (int k = 0; k < export_plugin_android_libraries.size(); k++) {3723const String resolved_android_library_path = _resolve_export_plugin_android_library_path(export_plugin_android_libraries[k]);3724if (!resolved_android_library_path.is_empty()) {3725android_libraries.push_back(resolved_android_library_path);3726}3727}37283729PackedStringArray export_plugin_android_dependencies = export_plugins[i]->get_android_dependencies(Ref<EditorExportPlatform>(this), p_debug);3730android_dependencies.append_array(export_plugin_android_dependencies);37313732PackedStringArray export_plugin_android_dependencies_maven_repos = export_plugins[i]->get_android_dependencies_maven_repos(Ref<EditorExportPlatform>(this), p_debug);3733android_dependencies_maven_repos.append_array(export_plugin_android_dependencies_maven_repos);3734}37353736PackedStringArray features = export_plugins[i]->get_export_features(Ref<EditorExportPlatform>(this), p_debug);3737if (features.has("dotnet")) {3738has_dotnet_project = true;3739}3740}37413742bool clean_build_required = _is_clean_build_required(p_preset);3743String combined_android_libraries = String("|").join(android_libraries);3744String combined_android_dependencies = String("|").join(android_dependencies);3745String combined_android_dependencies_maven_repos = String("|").join(android_dependencies_maven_repos);37463747List<String> cmdline;3748cmdline.push_back("validateJavaVersion");3749if (clean_build_required) {3750cmdline.push_back("clean");3751}37523753String edition = has_dotnet_project ? "Mono" : "Standard";3754String build_type = p_debug ? "Debug" : "Release";3755if (export_format == EXPORT_FORMAT_AAB) {3756String bundle_build_command = vformat("bundle%s%s", edition, build_type);3757cmdline.push_back(bundle_build_command);3758} else if (export_format == EXPORT_FORMAT_APK) {3759String apk_build_command = vformat("assemble%s%s", edition, build_type);3760cmdline.push_back(apk_build_command);3761}37623763String addons_directory = ProjectSettings::get_singleton()->globalize_path("res://addons");37643765cmdline.push_back("-p"); // argument to specify the start directory.3766cmdline.push_back(build_path); // start directory.3767cmdline.push_back("-Paddons_directory=" + addons_directory); // path to the addon directory as it may contain jar or aar dependencies3768cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.3769cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code.3770cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name.3771cmdline.push_back("-Pexport_version_min_sdk=" + min_sdk_version); // argument to specify the min sdk.3772cmdline.push_back("-Pexport_version_target_sdk=" + target_sdk_version); // argument to specify the target sdk.3773cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs.3774cmdline.push_back("-Pplugins_local_binaries=" + combined_android_libraries); // argument to specify the list of android libraries provided by plugins.3775cmdline.push_back("-Pplugins_remote_binaries=" + combined_android_dependencies); // argument to specify the list of android dependencies provided by plugins.3776cmdline.push_back("-Pplugins_maven_repos=" + combined_android_dependencies_maven_repos); // argument to specify the list of maven repos for android dependencies provided by plugins.3777cmdline.push_back("-Pperform_zipalign=" + zipalign_flag); // argument to specify whether the build should be zipaligned.3778cmdline.push_back("-Pperform_signing=" + sign_flag); // argument to specify whether the build should be signed.3779cmdline.push_back("-Pcompress_native_libraries=" + compress_native_libraries_flag); // argument to specify whether the build should compress native libraries.37803781// NOTE: The release keystore is not included in the verbose logging3782// to avoid accidentally leaking sensitive information when sharing verbose logs for troubleshooting.3783// Any non-sensitive additions to the command line arguments must be done above this section.3784// Sensitive additions must be done below the logging statement.3785print_verbose("Build Android project using gradle command: " + String("\n") + build_command + " " + join_list(cmdline, String(" ")));37863787if (should_sign) {3788if (p_debug) {3789String debug_keystore = _get_keystore_path(p_preset, true);3790String debug_password = p_preset->get_or_env("keystore/debug_password", ENV_ANDROID_KEYSTORE_DEBUG_PASS);3791String debug_user = p_preset->get_or_env("keystore/debug_user", ENV_ANDROID_KEYSTORE_DEBUG_USER);37923793if (debug_keystore.is_empty()) {3794debug_keystore = EDITOR_GET("export/android/debug_keystore");3795debug_password = EDITOR_GET("export/android/debug_keystore_pass");3796debug_user = EDITOR_GET("export/android/debug_keystore_user");3797}3798if (debug_keystore.is_relative_path()) {3799debug_keystore = OS::get_singleton()->get_resource_dir().path_join(debug_keystore).simplify_path();3800}3801if (!FileAccess::exists(debug_keystore)) {3802add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find debug keystore, unable to export."));3803return ERR_FILE_CANT_OPEN;3804}38053806cmdline.push_back("-Pdebug_keystore_file=" + debug_keystore); // argument to specify the debug keystore file.3807cmdline.push_back("-Pdebug_keystore_alias=" + debug_user); // argument to specify the debug keystore alias.3808cmdline.push_back("-Pdebug_keystore_password=" + debug_password); // argument to specify the debug keystore password.3809} else {3810// Pass the release keystore info as well3811String release_keystore = _get_keystore_path(p_preset, false);3812String release_username = p_preset->get_or_env("keystore/release_user", ENV_ANDROID_KEYSTORE_RELEASE_USER);3813String release_password = p_preset->get_or_env("keystore/release_password", ENV_ANDROID_KEYSTORE_RELEASE_PASS);3814if (release_keystore.is_relative_path()) {3815release_keystore = OS::get_singleton()->get_resource_dir().path_join(release_keystore).simplify_path();3816}3817if (!FileAccess::exists(release_keystore)) {3818add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find release keystore, unable to export."));3819return ERR_FILE_CANT_OPEN;3820}38213822cmdline.push_back("-Prelease_keystore_file=" + release_keystore); // argument to specify the release keystore file.3823cmdline.push_back("-Prelease_keystore_alias=" + release_username); // argument to specify the release keystore alias.3824cmdline.push_back("-Prelease_keystore_password=" + release_password); // argument to specify the release keystore password.3825}3826}38273828String build_project_output;3829int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline, true, false, &build_project_output);3830if (result != 0) {3831add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Building of Android project failed, check output for the error:") + "\n\n" + build_project_output);3832return ERR_CANT_CREATE;3833} else {3834print_verbose(build_project_output);3835}38363837List<String> copy_args;3838String copy_command = "copyAndRenameBinary";3839copy_args.push_back(copy_command);38403841copy_args.push_back("-p"); // argument to specify the start directory.3842copy_args.push_back(build_path); // start directory.38433844copy_args.push_back("-Pexport_edition=" + edition.to_lower());38453846copy_args.push_back("-Pexport_build_type=" + build_type.to_lower());38473848String export_format_arg = export_format == EXPORT_FORMAT_AAB ? "aab" : "apk";3849copy_args.push_back("-Pexport_format=" + export_format_arg);38503851String export_filename = p_path.get_file();3852String export_path = p_path.get_base_dir();3853if (export_path.is_relative_path()) {3854export_path = OS::get_singleton()->get_resource_dir().path_join(export_path);3855}3856export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path();38573858copy_args.push_back("-Pexport_path=file:" + export_path);3859copy_args.push_back("-Pexport_filename=" + export_filename);38603861print_verbose("Copying Android binary using gradle command: " + String("\n") + build_command + " " + join_list(copy_args, String(" ")));3862String copy_binary_output;3863int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args, true, false, ©_binary_output);3864if (copy_result != 0) {3865add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to copy and rename export file:") + "\n\n" + copy_binary_output);3866return ERR_CANT_CREATE;3867} else {3868print_verbose(copy_binary_output);3869}38703871print_verbose("Successfully completed Android gradle build.");3872return OK;3873}3874// This is the start of the Legacy build system3875print_verbose("Starting legacy build system...");3876if (p_debug) {3877src_apk = p_preset->get("custom_template/debug");3878} else {3879src_apk = p_preset->get("custom_template/release");3880}3881src_apk = src_apk.strip_edges();3882if (src_apk.is_empty()) {3883if (p_debug) {3884src_apk = find_export_template("android_debug.apk");3885} else {3886src_apk = find_export_template("android_release.apk");3887}3888if (src_apk.is_empty()) {3889add_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));3890return ERR_FILE_NOT_FOUND;3891}3892}38933894Ref<FileAccess> io_fa;3895zlib_filefunc_def io = zipio_create_io(&io_fa);38963897if (ep.step(TTR("Creating APK..."), 0)) {3898return ERR_SKIP;3899}39003901unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);3902if (!pkg) {3903add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not find template APK to export: \"%s\"."), src_apk));3904return ERR_FILE_NOT_FOUND;3905}39063907int ret = unzGoToFirstFile(pkg);39083909Ref<FileAccess> io2_fa;3910zlib_filefunc_def io2 = zipio_create_io(&io2_fa);39113912String tmp_unaligned_path = EditorPaths::get_singleton()->get_temp_dir().path_join("tmpexport-unaligned." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");39133914#define CLEANUP_AND_RETURN(m_err) \3915{ \3916DirAccess::remove_file_or_error(tmp_unaligned_path); \3917return m_err; \3918} \3919((void)0)39203921zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);39223923String cmdline = p_preset->get("command_line/extra_args");39243925String version_name = p_preset->get_version("version/name");3926String package_name = p_preset->get("package/unique_name");39273928String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");39293930Vector<ABI> invalid_abis(enabled_abis);39313932//To temporarily store icon xml data.3933Vector<uint8_t> themed_icon_xml_data;3934int icon_xml_compression_method = -1;39353936while (ret == UNZ_OK) {3937//get filename3938unz_file_info info;3939char fname[16384];3940ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);3941if (ret != UNZ_OK) {3942break;3943}39443945bool skip = false;39463947String file = String::utf8(fname);39483949Vector<uint8_t> data;3950data.resize(info.uncompressed_size);39513952//read3953unzOpenCurrentFile(pkg);3954unzReadCurrentFile(pkg, data.ptrw(), data.size());3955unzCloseCurrentFile(pkg);39563957//write3958if (file == "AndroidManifest.xml") {3959_fix_manifest(p_preset, data, p_give_internet);39603961// Allow editor export plugins to update the prebuilt manifest as needed.3962Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();3963for (int i = 0; i < export_plugins.size(); i++) {3964if (export_plugins[i]->supports_platform(Ref<EditorExportPlatform>(this))) {3965PackedByteArray export_plugin_data = export_plugins[i]->update_android_prebuilt_manifest(Ref<EditorExportPlatform>(this), data);3966if (!export_plugin_data.is_empty()) {3967data = export_plugin_data;3968}3969}3970}3971}3972if (file == "resources.arsc") {3973_fix_resources(p_preset, data);3974}39753976if (file == THEMED_ICON_XML_PATH) {3977// Store themed_icon.xml data.3978themed_icon_xml_data = data;3979skip = true;3980}39813982if (file == ICON_XML_PATH) {3983if (monochrome.is_valid() && !monochrome->is_empty()) {3984// Defer processing of icon.xml until after themed_icon.xml is read.3985icon_xml_compression_method = info.compression_method;3986skip = true;3987}3988}39893990if (file.ends_with(".png") && file.contains("mipmap")) {3991for (int i = 0; i < ICON_DENSITIES_COUNT; ++i) {3992if (main_image.is_valid() && !main_image->is_empty()) {3993if (file == LAUNCHER_ICONS[i].export_path) {3994_process_launcher_icons(file, main_image, LAUNCHER_ICONS[i].dimensions, data);3995}3996}3997if (foreground.is_valid() && !foreground->is_empty()) {3998if (file == LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].export_path) {3999_process_launcher_icons(file, foreground, LAUNCHER_ADAPTIVE_ICON_FOREGROUNDS[i].dimensions, data);4000}4001}4002if (background.is_valid() && !background->is_empty()) {4003if (file == LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].export_path) {4004_process_launcher_icons(file, background, LAUNCHER_ADAPTIVE_ICON_BACKGROUNDS[i].dimensions, data);4005}4006}4007if (monochrome.is_valid() && !monochrome->is_empty()) {4008if (file == LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].export_path) {4009_process_launcher_icons(file, monochrome, LAUNCHER_ADAPTIVE_ICON_MONOCHROMES[i].dimensions, data);4010}4011}4012}4013}40144015if (file.ends_with(".so")) {4016bool enabled = false;4017for (int i = 0; i < enabled_abis.size(); ++i) {4018if (file.begins_with("lib/" + enabled_abis[i].abi + "/")) {4019invalid_abis.erase(enabled_abis[i]);4020enabled = true;4021break;4022}4023}4024if (!enabled) {4025skip = true;4026}4027}40284029if (file.begins_with("META-INF") && should_sign) {4030skip = true;4031}40324033if (!skip) {4034print_line("ADDING: " + file);40354036// Respect decision on compression made by AAPT for the export template4037const bool uncompressed = info.compression_method == 0;40384039zip_fileinfo zipfi = get_zip_fileinfo();40404041zipOpenNewFileInZip(unaligned_apk,4042file.utf8().get_data(),4043&zipfi,4044nullptr,40450,4046nullptr,40470,4048nullptr,4049uncompressed ? 0 : Z_DEFLATED,4050Z_DEFAULT_COMPRESSION);40514052zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());4053zipCloseFileInZip(unaligned_apk);4054}40554056ret = unzGoToNextFile(pkg);4057}40584059// Process deferred icon.xml and replace it's data with themed_icon.xml.4060if (monochrome.is_valid() && !monochrome->is_empty()) {4061print_line("ADDING: " + ICON_XML_PATH + " (replacing with themed_icon.xml data)");40624063const bool uncompressed = icon_xml_compression_method == 0;4064zip_fileinfo zipfi = get_zip_fileinfo();40654066zipOpenNewFileInZip(unaligned_apk,4067ICON_XML_PATH.utf8().get_data(),4068&zipfi,4069nullptr,40700,4071nullptr,40720,4073nullptr,4074uncompressed ? 0 : Z_DEFLATED,4075Z_DEFAULT_COMPRESSION);40764077zipWriteInFileInZip(unaligned_apk, themed_icon_xml_data.ptr(), themed_icon_xml_data.size());4078zipCloseFileInZip(unaligned_apk);4079}40804081if (!invalid_abis.is_empty()) {4082add_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)));4083CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);4084}40854086if (ep.step(TTR("Adding files..."), 1)) {4087CLEANUP_AND_RETURN(ERR_SKIP);4088}4089err = OK;40904091if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {4092APKExportData ed;4093ed.ep = &ep;4094ed.apk = unaligned_apk;4095err = export_project_files(p_preset, p_debug, ignore_apk_file, nullptr, &ed, save_apk_so);4096} else {4097if (apk_expansion) {4098err = save_apk_expansion_file(p_preset, p_debug, p_path);4099if (err != OK) {4100add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));4101return err;4102}4103} else {4104APKExportData ed;4105ed.ep = &ep;4106ed.apk = unaligned_apk;4107ed.pd.path = "assets.sparsepck";4108ed.pd.use_sparse_pck = true;4109err = export_project_files(p_preset, p_debug, save_apk_file, nullptr, &ed, save_apk_so);41104111Vector<uint8_t> enc_data;4112err = _generate_sparse_pck_metadata(p_preset, ed.pd, enc_data);4113if (err != OK) {4114add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Could not generate sparse pck metadata!"));4115return err;4116}41174118store_in_apk(&ed, "assets/assets.sparsepck", enc_data, 0);4119}4120}41214122if (err != OK) {4123unzClose(pkg);4124add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not export project files.")));4125CLEANUP_AND_RETURN(ERR_SKIP);4126}41274128zip_fileinfo zipfi = get_zip_fileinfo();4129zipOpenNewFileInZip(unaligned_apk,4130"assets/_cl_",4131&zipfi,4132nullptr,41330,4134nullptr,41350,4136nullptr,41370, // No compress (little size gain and potentially slower startup)4138Z_DEFAULT_COMPRESSION);4139zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());4140zipCloseFileInZip(unaligned_apk);4141zipClose(unaligned_apk, nullptr);4142unzClose(pkg);41434144// Let's zip-align (must be done before signing)41454146static const int PAGE_SIZE_KB = 16 * 1024;4147static const int ZIP_ALIGNMENT = 4;41484149// If we're not signing the apk, then the next step should be the last.4150const int next_step = should_sign ? 103 : 105;4151if (ep.step(TTR("Aligning APK..."), next_step)) {4152CLEANUP_AND_RETURN(ERR_SKIP);4153}41544155unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);4156if (!tmp_unaligned) {4157add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not unzip temporary unaligned APK.")));4158CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);4159}41604161ret = unzGoToFirstFile(tmp_unaligned);41624163io2 = zipio_create_io(&io2_fa);4164zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);41654166// Take files from the unaligned APK and write them out to the aligned one4167// in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,4168// following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp4169int bias = 0;4170while (ret == UNZ_OK) {4171unz_file_info info;4172memset(&info, 0, sizeof(info));41734174char fname[16384];4175char extra[16384];4176ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0);4177if (ret != UNZ_OK) {4178break;4179}41804181String file = String::utf8(fname);41824183Vector<uint8_t> data;4184data.resize(info.compressed_size);41854186// read4187int method, level;4188unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read4189long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);4190unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());4191unzCloseCurrentFile(tmp_unaligned);41924193// align4194int padding = 0;4195if (!info.compression_method) {4196// Uncompressed file => Align4197long new_offset = file_offset + bias;4198const char *ext = strrchr(fname, '.');4199if (ext && strcmp(ext, ".so") == 0) {4200padding = (PAGE_SIZE_KB - (new_offset % PAGE_SIZE_KB)) % PAGE_SIZE_KB;4201} else {4202padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;4203}4204}42054206memset(extra + info.size_file_extra, 0, padding);42074208zip_fileinfo fileinfo = get_zip_fileinfo();4209zipOpenNewFileInZip2(final_apk,4210file.utf8().get_data(),4211&fileinfo,4212extra,4213info.size_file_extra + padding,4214nullptr,42150,4216nullptr,4217method,4218level,42191); // raw write4220zipWriteInFileInZip(final_apk, data.ptr(), data.size());4221zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);42224223bias += padding;42244225ret = unzGoToNextFile(tmp_unaligned);4226}42274228zipClose(final_apk, nullptr);4229unzClose(tmp_unaligned);42304231if (should_sign) {4232// Signing must be done last as any additional modifications to the4233// file will invalidate the signature.4234err = sign_apk(p_preset, p_debug, p_path, ep);4235if (err != OK) {4236// Message is supplied by the subroutine method.4237CLEANUP_AND_RETURN(err);4238}4239}42404241CLEANUP_AND_RETURN(OK);4242}42434244void EditorExportPlatformAndroid::get_platform_features(List<String> *r_features) const {4245r_features->push_back("mobile");4246r_features->push_back("android");4247}42484249void EditorExportPlatformAndroid::resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, HashSet<String> &p_features) {4250}42514252void EditorExportPlatformAndroid::initialize() {4253if (EditorNode::get_singleton()) {4254Ref<Image> img = memnew(Image);4255const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE);42564257ImageLoaderSVG::create_image_from_string(img, _android_logo_svg, EDSCALE, upsample, false);4258logo = ImageTexture::create_from_image(img);42594260ImageLoaderSVG::create_image_from_string(img, _android_run_icon_svg, EDSCALE, upsample, false);4261run_icon = ImageTexture::create_from_image(img);42624263devices_changed.set();4264#ifndef DISABLE_DEPRECATED4265android_plugins_changed.set();4266#endif // DISABLE_DEPRECATED4267#ifndef ANDROID_ENABLED4268_create_editor_debug_keystore_if_needed();4269_update_preset_status();4270check_for_changes_thread.start(_check_for_changes_poll_thread, this);4271#endif4272}4273}42744275EditorExportPlatformAndroid::~EditorExportPlatformAndroid() {4276#ifndef ANDROID_ENABLED4277quit_request.set();4278if (check_for_changes_thread.is_started()) {4279check_for_changes_thread.wait_to_finish();4280}4281#endif4282}428342844285