export_plugin.cpp 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292
  1. /**************************************************************************/
  2. /* export_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "export_plugin.h"
  31. #include "gradle_export_util.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/image_loader.h"
  36. #include "core/io/json.h"
  37. #include "core/io/marshalls.h"
  38. #include "core/version.h"
  39. #include "drivers/png/png_driver_common.h"
  40. #include "editor/editor_log.h"
  41. #include "editor/editor_node.h"
  42. #include "editor/editor_paths.h"
  43. #include "editor/editor_scale.h"
  44. #include "editor/editor_settings.h"
  45. #include "main/splash.gen.h"
  46. #include "platform/android/logo_svg.gen.h"
  47. #include "platform/android/run_icon_svg.gen.h"
  48. #include "modules/modules_enabled.gen.h" // For svg.
  49. #ifdef MODULE_SVG_ENABLED
  50. #include "modules/svg/image_loader_svg.h"
  51. #endif
  52. #include <string.h>
  53. static const char *android_perms[] = {
  54. "ACCESS_CHECKIN_PROPERTIES",
  55. "ACCESS_COARSE_LOCATION",
  56. "ACCESS_FINE_LOCATION",
  57. "ACCESS_LOCATION_EXTRA_COMMANDS",
  58. "ACCESS_MOCK_LOCATION",
  59. "ACCESS_NETWORK_STATE",
  60. "ACCESS_SURFACE_FLINGER",
  61. "ACCESS_WIFI_STATE",
  62. "ACCOUNT_MANAGER",
  63. "ADD_VOICEMAIL",
  64. "AUTHENTICATE_ACCOUNTS",
  65. "BATTERY_STATS",
  66. "BIND_ACCESSIBILITY_SERVICE",
  67. "BIND_APPWIDGET",
  68. "BIND_DEVICE_ADMIN",
  69. "BIND_INPUT_METHOD",
  70. "BIND_NFC_SERVICE",
  71. "BIND_NOTIFICATION_LISTENER_SERVICE",
  72. "BIND_PRINT_SERVICE",
  73. "BIND_REMOTEVIEWS",
  74. "BIND_TEXT_SERVICE",
  75. "BIND_VPN_SERVICE",
  76. "BIND_WALLPAPER",
  77. "BLUETOOTH",
  78. "BLUETOOTH_ADMIN",
  79. "BLUETOOTH_PRIVILEGED",
  80. "BRICK",
  81. "BROADCAST_PACKAGE_REMOVED",
  82. "BROADCAST_SMS",
  83. "BROADCAST_STICKY",
  84. "BROADCAST_WAP_PUSH",
  85. "CALL_PHONE",
  86. "CALL_PRIVILEGED",
  87. "CAMERA",
  88. "CAPTURE_AUDIO_OUTPUT",
  89. "CAPTURE_SECURE_VIDEO_OUTPUT",
  90. "CAPTURE_VIDEO_OUTPUT",
  91. "CHANGE_COMPONENT_ENABLED_STATE",
  92. "CHANGE_CONFIGURATION",
  93. "CHANGE_NETWORK_STATE",
  94. "CHANGE_WIFI_MULTICAST_STATE",
  95. "CHANGE_WIFI_STATE",
  96. "CLEAR_APP_CACHE",
  97. "CLEAR_APP_USER_DATA",
  98. "CONTROL_LOCATION_UPDATES",
  99. "DELETE_CACHE_FILES",
  100. "DELETE_PACKAGES",
  101. "DEVICE_POWER",
  102. "DIAGNOSTIC",
  103. "DISABLE_KEYGUARD",
  104. "DUMP",
  105. "EXPAND_STATUS_BAR",
  106. "FACTORY_TEST",
  107. "FLASHLIGHT",
  108. "FORCE_BACK",
  109. "GET_ACCOUNTS",
  110. "GET_PACKAGE_SIZE",
  111. "GET_TASKS",
  112. "GET_TOP_ACTIVITY_INFO",
  113. "GLOBAL_SEARCH",
  114. "HARDWARE_TEST",
  115. "INJECT_EVENTS",
  116. "INSTALL_LOCATION_PROVIDER",
  117. "INSTALL_PACKAGES",
  118. "INSTALL_SHORTCUT",
  119. "INTERNAL_SYSTEM_WINDOW",
  120. "INTERNET",
  121. "KILL_BACKGROUND_PROCESSES",
  122. "LOCATION_HARDWARE",
  123. "MANAGE_ACCOUNTS",
  124. "MANAGE_APP_TOKENS",
  125. "MANAGE_DOCUMENTS",
  126. "MANAGE_EXTERNAL_STORAGE",
  127. "MASTER_CLEAR",
  128. "MEDIA_CONTENT_CONTROL",
  129. "MODIFY_AUDIO_SETTINGS",
  130. "MODIFY_PHONE_STATE",
  131. "MOUNT_FORMAT_FILESYSTEMS",
  132. "MOUNT_UNMOUNT_FILESYSTEMS",
  133. "NFC",
  134. "PERSISTENT_ACTIVITY",
  135. "PROCESS_OUTGOING_CALLS",
  136. "READ_CALENDAR",
  137. "READ_CALL_LOG",
  138. "READ_CONTACTS",
  139. "READ_EXTERNAL_STORAGE",
  140. "READ_FRAME_BUFFER",
  141. "READ_HISTORY_BOOKMARKS",
  142. "READ_INPUT_STATE",
  143. "READ_LOGS",
  144. "READ_PHONE_STATE",
  145. "READ_PROFILE",
  146. "READ_SMS",
  147. "READ_SOCIAL_STREAM",
  148. "READ_SYNC_SETTINGS",
  149. "READ_SYNC_STATS",
  150. "READ_USER_DICTIONARY",
  151. "REBOOT",
  152. "RECEIVE_BOOT_COMPLETED",
  153. "RECEIVE_MMS",
  154. "RECEIVE_SMS",
  155. "RECEIVE_WAP_PUSH",
  156. "RECORD_AUDIO",
  157. "REORDER_TASKS",
  158. "RESTART_PACKAGES",
  159. "SEND_RESPOND_VIA_MESSAGE",
  160. "SEND_SMS",
  161. "SET_ACTIVITY_WATCHER",
  162. "SET_ALARM",
  163. "SET_ALWAYS_FINISH",
  164. "SET_ANIMATION_SCALE",
  165. "SET_DEBUG_APP",
  166. "SET_ORIENTATION",
  167. "SET_POINTER_SPEED",
  168. "SET_PREFERRED_APPLICATIONS",
  169. "SET_PROCESS_LIMIT",
  170. "SET_TIME",
  171. "SET_TIME_ZONE",
  172. "SET_WALLPAPER",
  173. "SET_WALLPAPER_HINTS",
  174. "SIGNAL_PERSISTENT_PROCESSES",
  175. "STATUS_BAR",
  176. "SUBSCRIBED_FEEDS_READ",
  177. "SUBSCRIBED_FEEDS_WRITE",
  178. "SYSTEM_ALERT_WINDOW",
  179. "TRANSMIT_IR",
  180. "UNINSTALL_SHORTCUT",
  181. "UPDATE_DEVICE_STATS",
  182. "USE_CREDENTIALS",
  183. "USE_SIP",
  184. "VIBRATE",
  185. "WAKE_LOCK",
  186. "WRITE_APN_SETTINGS",
  187. "WRITE_CALENDAR",
  188. "WRITE_CALL_LOG",
  189. "WRITE_CONTACTS",
  190. "WRITE_EXTERNAL_STORAGE",
  191. "WRITE_GSERVICES",
  192. "WRITE_HISTORY_BOOKMARKS",
  193. "WRITE_PROFILE",
  194. "WRITE_SECURE_SETTINGS",
  195. "WRITE_SETTINGS",
  196. "WRITE_SMS",
  197. "WRITE_SOCIAL_STREAM",
  198. "WRITE_SYNC_SETTINGS",
  199. "WRITE_USER_DICTIONARY",
  200. nullptr
  201. };
  202. static const char *SPLASH_IMAGE_EXPORT_PATH = "res/drawable-nodpi/splash.png";
  203. static const char *LEGACY_BUILD_SPLASH_IMAGE_EXPORT_PATH = "res/drawable-nodpi-v4/splash.png";
  204. static const char *SPLASH_BG_COLOR_PATH = "res/drawable-nodpi/splash_bg_color.png";
  205. static const char *LEGACY_BUILD_SPLASH_BG_COLOR_PATH = "res/drawable-nodpi-v4/splash_bg_color.png";
  206. static const char *SPLASH_CONFIG_PATH = "res://android/build/res/drawable/splash_drawable.xml";
  207. static const char *GDEXTENSION_LIBS_PATH = "res://android/build/libs/gdextensionlibs.json";
  208. static const int icon_densities_count = 6;
  209. static const char *launcher_icon_option = PNAME("launcher_icons/main_192x192");
  210. static const char *launcher_adaptive_icon_foreground_option = PNAME("launcher_icons/adaptive_foreground_432x432");
  211. static const char *launcher_adaptive_icon_background_option = PNAME("launcher_icons/adaptive_background_432x432");
  212. static const LauncherIcon launcher_icons[icon_densities_count] = {
  213. { "res/mipmap-xxxhdpi-v4/icon.png", 192 },
  214. { "res/mipmap-xxhdpi-v4/icon.png", 144 },
  215. { "res/mipmap-xhdpi-v4/icon.png", 96 },
  216. { "res/mipmap-hdpi-v4/icon.png", 72 },
  217. { "res/mipmap-mdpi-v4/icon.png", 48 },
  218. { "res/mipmap/icon.png", 192 }
  219. };
  220. static const LauncherIcon launcher_adaptive_icon_foregrounds[icon_densities_count] = {
  221. { "res/mipmap-xxxhdpi-v4/icon_foreground.png", 432 },
  222. { "res/mipmap-xxhdpi-v4/icon_foreground.png", 324 },
  223. { "res/mipmap-xhdpi-v4/icon_foreground.png", 216 },
  224. { "res/mipmap-hdpi-v4/icon_foreground.png", 162 },
  225. { "res/mipmap-mdpi-v4/icon_foreground.png", 108 },
  226. { "res/mipmap/icon_foreground.png", 432 }
  227. };
  228. static const LauncherIcon launcher_adaptive_icon_backgrounds[icon_densities_count] = {
  229. { "res/mipmap-xxxhdpi-v4/icon_background.png", 432 },
  230. { "res/mipmap-xxhdpi-v4/icon_background.png", 324 },
  231. { "res/mipmap-xhdpi-v4/icon_background.png", 216 },
  232. { "res/mipmap-hdpi-v4/icon_background.png", 162 },
  233. { "res/mipmap-mdpi-v4/icon_background.png", 108 },
  234. { "res/mipmap/icon_background.png", 432 }
  235. };
  236. static const int EXPORT_FORMAT_APK = 0;
  237. static const int EXPORT_FORMAT_AAB = 1;
  238. static const char *APK_ASSETS_DIRECTORY = "res://android/build/assets";
  239. static const char *AAB_ASSETS_DIRECTORY = "res://android/build/assetPacks/installTime/src/main/assets";
  240. static const int DEFAULT_MIN_SDK_VERSION = 21; // Should match the value in 'platform/android/java/app/config.gradle#minSdk'
  241. static const int DEFAULT_TARGET_SDK_VERSION = 32; // Should match the value in 'platform/android/java/app/config.gradle#targetSdk'
  242. #ifndef ANDROID_ENABLED
  243. void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) {
  244. EditorExportPlatformAndroid *ea = static_cast<EditorExportPlatformAndroid *>(ud);
  245. while (!ea->quit_request.is_set()) {
  246. // Check for plugins updates
  247. {
  248. // Nothing to do if we already know the plugins have changed.
  249. if (!ea->plugins_changed.is_set()) {
  250. Vector<PluginConfigAndroid> loaded_plugins = get_plugins();
  251. MutexLock lock(ea->plugins_lock);
  252. if (ea->plugins.size() != loaded_plugins.size()) {
  253. ea->plugins_changed.set();
  254. } else {
  255. for (int i = 0; i < ea->plugins.size(); i++) {
  256. if (ea->plugins[i].name != loaded_plugins[i].name) {
  257. ea->plugins_changed.set();
  258. break;
  259. }
  260. }
  261. }
  262. if (ea->plugins_changed.is_set()) {
  263. ea->plugins = loaded_plugins;
  264. }
  265. }
  266. }
  267. // Check for devices updates
  268. String adb = get_adb_path();
  269. if (FileAccess::exists(adb)) {
  270. String devices;
  271. List<String> args;
  272. args.push_back("devices");
  273. int ec;
  274. OS::get_singleton()->execute(adb, args, &devices, &ec);
  275. Vector<String> ds = devices.split("\n");
  276. Vector<String> ldevices;
  277. for (int i = 1; i < ds.size(); i++) {
  278. String d = ds[i];
  279. int dpos = d.find("device");
  280. if (dpos == -1) {
  281. continue;
  282. }
  283. d = d.substr(0, dpos).strip_edges();
  284. ldevices.push_back(d);
  285. }
  286. MutexLock lock(ea->device_lock);
  287. bool different = false;
  288. if (ea->devices.size() != ldevices.size()) {
  289. different = true;
  290. } else {
  291. for (int i = 0; i < ea->devices.size(); i++) {
  292. if (ea->devices[i].id != ldevices[i]) {
  293. different = true;
  294. break;
  295. }
  296. }
  297. }
  298. if (different) {
  299. Vector<Device> ndevices;
  300. for (int i = 0; i < ldevices.size(); i++) {
  301. Device d;
  302. d.id = ldevices[i];
  303. for (int j = 0; j < ea->devices.size(); j++) {
  304. if (ea->devices[j].id == ldevices[i]) {
  305. d.description = ea->devices[j].description;
  306. d.name = ea->devices[j].name;
  307. d.api_level = ea->devices[j].api_level;
  308. }
  309. }
  310. if (d.description.is_empty()) {
  311. //in the oven, request!
  312. args.clear();
  313. args.push_back("-s");
  314. args.push_back(d.id);
  315. args.push_back("shell");
  316. args.push_back("getprop");
  317. int ec2;
  318. String dp;
  319. OS::get_singleton()->execute(adb, args, &dp, &ec2);
  320. Vector<String> props = dp.split("\n");
  321. String vendor;
  322. String device;
  323. d.description = "Device ID: " + d.id + "\n";
  324. d.api_level = 0;
  325. for (int j = 0; j < props.size(); j++) {
  326. // got information by `shell cat /system/build.prop` before and its format is "property=value"
  327. // it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above
  328. // its format is "[property]: [value]" so changed it as like build.prop
  329. String p = props[j];
  330. p = p.replace("]: ", "=");
  331. p = p.replace("[", "");
  332. p = p.replace("]", "");
  333. if (p.begins_with("ro.product.model=")) {
  334. device = p.get_slice("=", 1).strip_edges();
  335. } else if (p.begins_with("ro.product.brand=")) {
  336. vendor = p.get_slice("=", 1).strip_edges().capitalize();
  337. } else if (p.begins_with("ro.build.display.id=")) {
  338. d.description += "Build: " + p.get_slice("=", 1).strip_edges() + "\n";
  339. } else if (p.begins_with("ro.build.version.release=")) {
  340. d.description += "Release: " + p.get_slice("=", 1).strip_edges() + "\n";
  341. } else if (p.begins_with("ro.build.version.sdk=")) {
  342. d.api_level = p.get_slice("=", 1).to_int();
  343. } else if (p.begins_with("ro.product.cpu.abi=")) {
  344. d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n";
  345. } else if (p.begins_with("ro.product.manufacturer=")) {
  346. d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n";
  347. } else if (p.begins_with("ro.board.platform=")) {
  348. d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n";
  349. } else if (p.begins_with("ro.opengles.version=")) {
  350. uint32_t opengl = p.get_slice("=", 1).to_int();
  351. d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n";
  352. }
  353. }
  354. d.name = vendor + " " + device;
  355. if (device.is_empty()) {
  356. continue;
  357. }
  358. }
  359. ndevices.push_back(d);
  360. }
  361. ea->devices = ndevices;
  362. ea->devices_changed.set();
  363. }
  364. }
  365. uint64_t sleep = 200;
  366. uint64_t wait = 3000000;
  367. uint64_t time = OS::get_singleton()->get_ticks_usec();
  368. while (OS::get_singleton()->get_ticks_usec() - time < wait) {
  369. OS::get_singleton()->delay_usec(1000 * sleep);
  370. if (ea->quit_request.is_set()) {
  371. break;
  372. }
  373. }
  374. }
  375. if (EDITOR_GET("export/android/shutdown_adb_on_exit")) {
  376. String adb = get_adb_path();
  377. if (!FileAccess::exists(adb)) {
  378. return; //adb not configured
  379. }
  380. List<String> args;
  381. args.push_back("kill-server");
  382. OS::get_singleton()->execute(adb, args);
  383. }
  384. }
  385. #endif
  386. String EditorExportPlatformAndroid::get_project_name(const String &p_name) const {
  387. String aname;
  388. if (!p_name.is_empty()) {
  389. aname = p_name;
  390. } else {
  391. aname = GLOBAL_GET("application/config/name");
  392. }
  393. if (aname.is_empty()) {
  394. aname = VERSION_NAME;
  395. }
  396. return aname;
  397. }
  398. String EditorExportPlatformAndroid::get_package_name(const String &p_package) const {
  399. String pname = p_package;
  400. String name = get_valid_basename();
  401. pname = pname.replace("$genname", name);
  402. return pname;
  403. }
  404. // Returns the project name without invalid characters
  405. // or the "noname" string if all characters are invalid.
  406. String EditorExportPlatformAndroid::get_valid_basename() const {
  407. String basename = GLOBAL_GET("application/config/name");
  408. basename = basename.to_lower();
  409. String name;
  410. bool first = true;
  411. for (int i = 0; i < basename.length(); i++) {
  412. char32_t c = basename[i];
  413. if (is_digit(c) && first) {
  414. continue;
  415. }
  416. if (is_ascii_alphanumeric_char(c)) {
  417. name += String::chr(c);
  418. first = false;
  419. }
  420. }
  421. if (name.is_empty()) {
  422. name = "noname";
  423. }
  424. return name;
  425. }
  426. String EditorExportPlatformAndroid::get_assets_directory(const Ref<EditorExportPreset> &p_preset, int p_export_format) const {
  427. return p_export_format == EXPORT_FORMAT_AAB ? AAB_ASSETS_DIRECTORY : APK_ASSETS_DIRECTORY;
  428. }
  429. bool EditorExportPlatformAndroid::is_package_name_valid(const String &p_package, String *r_error) const {
  430. String pname = get_package_name(p_package);
  431. if (pname.length() == 0) {
  432. if (r_error) {
  433. *r_error = TTR("Package name is missing.");
  434. }
  435. return false;
  436. }
  437. int segments = 0;
  438. bool first = true;
  439. for (int i = 0; i < pname.length(); i++) {
  440. char32_t c = pname[i];
  441. if (first && c == '.') {
  442. if (r_error) {
  443. *r_error = TTR("Package segments must be of non-zero length.");
  444. }
  445. return false;
  446. }
  447. if (c == '.') {
  448. segments++;
  449. first = true;
  450. continue;
  451. }
  452. if (!is_ascii_identifier_char(c)) {
  453. if (r_error) {
  454. *r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c));
  455. }
  456. return false;
  457. }
  458. if (first && is_digit(c)) {
  459. if (r_error) {
  460. *r_error = TTR("A digit cannot be the first character in a package segment.");
  461. }
  462. return false;
  463. }
  464. if (first && is_underscore(c)) {
  465. if (r_error) {
  466. *r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c));
  467. }
  468. return false;
  469. }
  470. first = false;
  471. }
  472. if (segments == 0) {
  473. if (r_error) {
  474. *r_error = TTR("The package must have at least one '.' separator.");
  475. }
  476. return false;
  477. }
  478. if (first) {
  479. if (r_error) {
  480. *r_error = TTR("Package segments must be of non-zero length.");
  481. }
  482. return false;
  483. }
  484. if (p_package.find("$genname") >= 0 && !is_project_name_valid()) {
  485. if (r_error) {
  486. *r_error = TTR("The project name does not meet the requirement for the package name format. Please explicitly specify the package name.");
  487. }
  488. return false;
  489. }
  490. return true;
  491. }
  492. bool EditorExportPlatformAndroid::is_project_name_valid() const {
  493. // Get the original project name and convert to lowercase.
  494. String basename = GLOBAL_GET("application/config/name");
  495. basename = basename.to_lower();
  496. // Check if there are invalid characters.
  497. if (basename != get_valid_basename()) {
  498. return false;
  499. }
  500. return true;
  501. }
  502. bool EditorExportPlatformAndroid::_should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) {
  503. /*
  504. * By not compressing files with little or no benefit in doing so,
  505. * a performance gain is expected at runtime. Moreover, if the APK is
  506. * zip-aligned, assets stored as they are can be efficiently read by
  507. * Android by memory-mapping them.
  508. */
  509. // -- Unconditional uncompress to mimic AAPT plus some other
  510. static const char *unconditional_compress_ext[] = {
  511. // From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp
  512. // These formats are already compressed, or don't compress well:
  513. ".jpg", ".jpeg", ".png", ".gif",
  514. ".wav", ".mp2", ".mp3", ".ogg", ".aac",
  515. ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
  516. ".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
  517. ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
  518. ".amr", ".awb", ".wma", ".wmv",
  519. // Godot-specific:
  520. ".webp", // Same reasoning as .png
  521. ".cfb", // Don't let small config files slow-down startup
  522. ".scn", // Binary scenes are usually already compressed
  523. ".ctex", // Streamable textures are usually already compressed
  524. // Trailer for easier processing
  525. nullptr
  526. };
  527. for (const char **ext = unconditional_compress_ext; *ext; ++ext) {
  528. if (p_path.to_lower().ends_with(String(*ext))) {
  529. return false;
  530. }
  531. }
  532. // -- Compressed resource?
  533. if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') {
  534. // Already compressed
  535. return false;
  536. }
  537. // --- TODO: Decide on texture resources according to their image compression setting
  538. return true;
  539. }
  540. zip_fileinfo EditorExportPlatformAndroid::get_zip_fileinfo() {
  541. OS::DateTime dt = OS::get_singleton()->get_datetime();
  542. zip_fileinfo zipfi;
  543. zipfi.tmz_date.tm_year = dt.year;
  544. zipfi.tmz_date.tm_mon = dt.month - 1; // tm_mon is zero indexed
  545. zipfi.tmz_date.tm_mday = dt.day;
  546. zipfi.tmz_date.tm_hour = dt.hour;
  547. zipfi.tmz_date.tm_min = dt.minute;
  548. zipfi.tmz_date.tm_sec = dt.second;
  549. zipfi.dosDate = 0;
  550. zipfi.external_fa = 0;
  551. zipfi.internal_fa = 0;
  552. return zipfi;
  553. }
  554. Vector<EditorExportPlatformAndroid::ABI> EditorExportPlatformAndroid::get_abis() {
  555. // Should have the same order and size as get_archs.
  556. Vector<ABI> abis;
  557. abis.push_back(ABI("armeabi-v7a", "arm32"));
  558. abis.push_back(ABI("arm64-v8a", "arm64"));
  559. abis.push_back(ABI("x86", "x86_32"));
  560. abis.push_back(ABI("x86_64", "x86_64"));
  561. return abis;
  562. }
  563. /// List the gdap files in the directory specified by the p_path parameter.
  564. Vector<String> EditorExportPlatformAndroid::list_gdap_files(const String &p_path) {
  565. Vector<String> dir_files;
  566. Ref<DirAccess> da = DirAccess::open(p_path);
  567. if (da.is_valid()) {
  568. da->list_dir_begin();
  569. while (true) {
  570. String file = da->get_next();
  571. if (file.is_empty()) {
  572. break;
  573. }
  574. if (da->current_is_dir() || da->current_is_hidden()) {
  575. continue;
  576. }
  577. if (file.ends_with(PluginConfigAndroid::PLUGIN_CONFIG_EXT)) {
  578. dir_files.push_back(file);
  579. }
  580. }
  581. da->list_dir_end();
  582. }
  583. return dir_files;
  584. }
  585. Vector<PluginConfigAndroid> EditorExportPlatformAndroid::get_plugins() {
  586. Vector<PluginConfigAndroid> loaded_plugins;
  587. String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().path_join("android/plugins");
  588. // Add the prebuilt plugins
  589. loaded_plugins.append_array(PluginConfigAndroid::get_prebuilt_plugins(plugins_dir));
  590. if (DirAccess::exists(plugins_dir)) {
  591. Vector<String> plugins_filenames = list_gdap_files(plugins_dir);
  592. if (!plugins_filenames.is_empty()) {
  593. Ref<ConfigFile> config_file = memnew(ConfigFile);
  594. for (int i = 0; i < plugins_filenames.size(); i++) {
  595. PluginConfigAndroid config = PluginConfigAndroid::load_plugin_config(config_file, plugins_dir.path_join(plugins_filenames[i]));
  596. if (config.valid_config) {
  597. loaded_plugins.push_back(config);
  598. } else {
  599. print_error("Invalid plugin config file " + plugins_filenames[i]);
  600. }
  601. }
  602. }
  603. }
  604. return loaded_plugins;
  605. }
  606. Vector<PluginConfigAndroid> EditorExportPlatformAndroid::get_enabled_plugins(const Ref<EditorExportPreset> &p_presets) {
  607. Vector<PluginConfigAndroid> enabled_plugins;
  608. Vector<PluginConfigAndroid> all_plugins = get_plugins();
  609. for (int i = 0; i < all_plugins.size(); i++) {
  610. PluginConfigAndroid plugin = all_plugins[i];
  611. bool enabled = p_presets->get("plugins/" + plugin.name);
  612. if (enabled) {
  613. enabled_plugins.push_back(plugin);
  614. }
  615. }
  616. return enabled_plugins;
  617. }
  618. Error EditorExportPlatformAndroid::store_in_apk(APKExportData *ed, const String &p_path, const Vector<uint8_t> &p_data, int compression_method) {
  619. zip_fileinfo zipfi = get_zip_fileinfo();
  620. zipOpenNewFileInZip(ed->apk,
  621. p_path.utf8().get_data(),
  622. &zipfi,
  623. nullptr,
  624. 0,
  625. nullptr,
  626. 0,
  627. nullptr,
  628. compression_method,
  629. Z_DEFAULT_COMPRESSION);
  630. zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size());
  631. zipCloseFileInZip(ed->apk);
  632. return OK;
  633. }
  634. Error EditorExportPlatformAndroid::save_apk_so(void *p_userdata, const SharedObject &p_so) {
  635. if (!p_so.path.get_file().begins_with("lib")) {
  636. String err = "Android .so file names must start with \"lib\", but got: " + p_so.path;
  637. ERR_PRINT(err);
  638. return FAILED;
  639. }
  640. APKExportData *ed = static_cast<APKExportData *>(p_userdata);
  641. Vector<ABI> abis = get_abis();
  642. bool exported = false;
  643. for (int i = 0; i < p_so.tags.size(); ++i) {
  644. // shared objects can be fat (compatible with multiple ABIs)
  645. int abi_index = -1;
  646. for (int j = 0; j < abis.size(); ++j) {
  647. if (abis[j].abi == p_so.tags[i] || abis[j].arch == p_so.tags[i]) {
  648. abi_index = j;
  649. break;
  650. }
  651. }
  652. if (abi_index != -1) {
  653. exported = true;
  654. String abi = abis[abi_index].abi;
  655. String dst_path = String("lib").path_join(abi).path_join(p_so.path.get_file());
  656. Vector<uint8_t> array = FileAccess::get_file_as_bytes(p_so.path);
  657. Error store_err = store_in_apk(ed, dst_path, array);
  658. ERR_FAIL_COND_V_MSG(store_err, store_err, "Cannot store in apk file '" + dst_path + "'.");
  659. }
  660. }
  661. if (!exported) {
  662. ERR_PRINT("Cannot determine architecture for library \"" + p_so.path + "\". One of the supported architectures must be used as a tag: " + join_abis(abis, " ", true));
  663. return FAILED;
  664. }
  665. return OK;
  666. }
  667. Error 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) {
  668. APKExportData *ed = static_cast<APKExportData *>(p_userdata);
  669. String dst_path = p_path.replace_first("res://", "assets/");
  670. store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0);
  671. return OK;
  672. }
  673. Error 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) {
  674. return OK;
  675. }
  676. Error EditorExportPlatformAndroid::copy_gradle_so(void *p_userdata, const SharedObject &p_so) {
  677. ERR_FAIL_COND_V_MSG(!p_so.path.get_file().begins_with("lib"), FAILED,
  678. "Android .so file names must start with \"lib\", but got: " + p_so.path);
  679. Vector<ABI> abis = get_abis();
  680. CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata);
  681. bool exported = false;
  682. for (int i = 0; i < p_so.tags.size(); ++i) {
  683. int abi_index = -1;
  684. for (int j = 0; j < abis.size(); ++j) {
  685. if (abis[j].abi == p_so.tags[i] || abis[j].arch == p_so.tags[i]) {
  686. abi_index = j;
  687. break;
  688. }
  689. }
  690. if (abi_index != -1) {
  691. exported = true;
  692. String base = "res://android/build/libs";
  693. String type = export_data->debug ? "debug" : "release";
  694. String abi = abis[abi_index].abi;
  695. String filename = p_so.path.get_file();
  696. String dst_path = base.path_join(type).path_join(abi).path_join(filename);
  697. Vector<uint8_t> data = FileAccess::get_file_as_bytes(p_so.path);
  698. print_verbose("Copying .so file from " + p_so.path + " to " + dst_path);
  699. Error err = store_file_at_path(dst_path, data);
  700. ERR_FAIL_COND_V_MSG(err, err, "Failed to copy .so file from " + p_so.path + " to " + dst_path);
  701. export_data->libs.push_back(dst_path);
  702. }
  703. }
  704. ERR_FAIL_COND_V_MSG(!exported, FAILED,
  705. "Cannot determine architecture for library \"" + p_so.path + "\". One of the supported architectures must be used as a tag:" + join_abis(abis, " ", true));
  706. return OK;
  707. }
  708. bool EditorExportPlatformAndroid::_has_read_write_storage_permission(const Vector<String> &p_permissions) {
  709. return p_permissions.find("android.permission.READ_EXTERNAL_STORAGE") != -1 || p_permissions.find("android.permission.WRITE_EXTERNAL_STORAGE") != -1;
  710. }
  711. bool EditorExportPlatformAndroid::_has_manage_external_storage_permission(const Vector<String> &p_permissions) {
  712. return p_permissions.find("android.permission.MANAGE_EXTERNAL_STORAGE") != -1;
  713. }
  714. void EditorExportPlatformAndroid::_get_permissions(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, Vector<String> &r_permissions) {
  715. const char **aperms = android_perms;
  716. while (*aperms) {
  717. bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());
  718. if (enabled) {
  719. r_permissions.push_back("android.permission." + String(*aperms));
  720. }
  721. aperms++;
  722. }
  723. PackedStringArray user_perms = p_preset->get("permissions/custom_permissions");
  724. for (int i = 0; i < user_perms.size(); i++) {
  725. String user_perm = user_perms[i].strip_edges();
  726. if (!user_perm.is_empty()) {
  727. r_permissions.push_back(user_perm);
  728. }
  729. }
  730. if (p_give_internet) {
  731. if (r_permissions.find("android.permission.INTERNET") == -1) {
  732. r_permissions.push_back("android.permission.INTERNET");
  733. }
  734. }
  735. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  736. if (xr_mode_index == XR_MODE_OPENXR) {
  737. int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required
  738. if (hand_tracking_index > XR_HAND_TRACKING_NONE) {
  739. if (r_permissions.find("com.oculus.permission.HAND_TRACKING") == -1) {
  740. r_permissions.push_back("com.oculus.permission.HAND_TRACKING");
  741. }
  742. }
  743. }
  744. }
  745. void EditorExportPlatformAndroid::_write_tmp_manifest(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, bool p_debug) {
  746. print_verbose("Building temporary manifest...");
  747. String manifest_text =
  748. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  749. "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
  750. " xmlns:tools=\"http://schemas.android.com/tools\">\n";
  751. manifest_text += _get_screen_sizes_tag(p_preset);
  752. manifest_text += _get_gles_tag();
  753. Vector<String> perms;
  754. _get_permissions(p_preset, p_give_internet, perms);
  755. for (int i = 0; i < perms.size(); i++) {
  756. String permission = perms.get(i);
  757. if (permission == "android.permission.WRITE_EXTERNAL_STORAGE" || (permission == "android.permission.READ_EXTERNAL_STORAGE" && _has_manage_external_storage_permission(perms))) {
  758. manifest_text += vformat(" <uses-permission android:name=\"%s\" android:maxSdkVersion=\"29\" />\n", permission);
  759. } else {
  760. manifest_text += vformat(" <uses-permission android:name=\"%s\" />\n", permission);
  761. }
  762. }
  763. manifest_text += _get_xr_features_tag(p_preset);
  764. manifest_text += _get_application_tag(p_preset, _has_read_write_storage_permission(perms));
  765. manifest_text += "</manifest>\n";
  766. String manifest_path = vformat("res://android/build/src/%s/AndroidManifest.xml", (p_debug ? "debug" : "release"));
  767. print_verbose("Storing manifest into " + manifest_path + ": " + "\n" + manifest_text);
  768. store_string_at_path(manifest_path, manifest_text);
  769. }
  770. void EditorExportPlatformAndroid::_fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {
  771. // Leaving the unused types commented because looking these constants up
  772. // again later would be annoying
  773. // const int CHUNK_AXML_FILE = 0x00080003;
  774. // const int CHUNK_RESOURCEIDS = 0x00080180;
  775. const int CHUNK_STRINGS = 0x001C0001;
  776. // const int CHUNK_XML_END_NAMESPACE = 0x00100101;
  777. const int CHUNK_XML_END_TAG = 0x00100103;
  778. // const int CHUNK_XML_START_NAMESPACE = 0x00100100;
  779. const int CHUNK_XML_START_TAG = 0x00100102;
  780. // const int CHUNK_XML_TEXT = 0x00100104;
  781. const int UTF8_FLAG = 0x00000100;
  782. Vector<String> string_table;
  783. uint32_t ofs = 8;
  784. uint32_t string_count = 0;
  785. uint32_t string_flags = 0;
  786. uint32_t string_data_offset = 0;
  787. uint32_t string_table_begins = 0;
  788. uint32_t string_table_ends = 0;
  789. Vector<uint8_t> stable_extra;
  790. String version_name = p_preset->get("version/name");
  791. int version_code = p_preset->get("version/code");
  792. String package_name = p_preset->get("package/unique_name");
  793. const int screen_orientation =
  794. _get_android_orientation_value(DisplayServer::ScreenOrientation(int(GLOBAL_GET("display/window/handheld/orientation"))));
  795. bool screen_support_small = p_preset->get("screen/support_small");
  796. bool screen_support_normal = p_preset->get("screen/support_normal");
  797. bool screen_support_large = p_preset->get("screen/support_large");
  798. bool screen_support_xlarge = p_preset->get("screen/support_xlarge");
  799. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  800. int hand_tracking_index = p_preset->get("xr_features/hand_tracking");
  801. int hand_tracking_frequency_index = p_preset->get("xr_features/hand_tracking_frequency");
  802. bool backup_allowed = p_preset->get("user_data_backup/allow");
  803. int app_category = p_preset->get("package/app_category");
  804. bool retain_data_on_uninstall = p_preset->get("package/retain_data_on_uninstall");
  805. bool exclude_from_recents = p_preset->get("package/exclude_from_recents");
  806. bool is_resizeable = bool(GLOBAL_GET("display/window/size/resizable"));
  807. Vector<String> perms;
  808. // Write permissions into the perms variable.
  809. _get_permissions(p_preset, p_give_internet, perms);
  810. bool has_read_write_storage_permission = _has_read_write_storage_permission(perms);
  811. while (ofs < (uint32_t)p_manifest.size()) {
  812. uint32_t chunk = decode_uint32(&p_manifest[ofs]);
  813. uint32_t size = decode_uint32(&p_manifest[ofs + 4]);
  814. switch (chunk) {
  815. case CHUNK_STRINGS: {
  816. int iofs = ofs + 8;
  817. string_count = decode_uint32(&p_manifest[iofs]);
  818. string_flags = decode_uint32(&p_manifest[iofs + 8]);
  819. string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
  820. uint32_t st_offset = iofs + 20;
  821. string_table.resize(string_count);
  822. uint32_t string_end = 0;
  823. string_table_begins = st_offset;
  824. for (uint32_t i = 0; i < string_count; i++) {
  825. uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
  826. string_at += st_offset + string_count * 4;
  827. ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table.");
  828. if (string_flags & UTF8_FLAG) {
  829. } else {
  830. uint32_t len = decode_uint16(&p_manifest[string_at]);
  831. Vector<char32_t> ucstring;
  832. ucstring.resize(len + 1);
  833. for (uint32_t j = 0; j < len; j++) {
  834. uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
  835. ucstring.write[j] = c;
  836. }
  837. string_end = MAX(string_at + 2 + 2 * len, string_end);
  838. ucstring.write[len] = 0;
  839. string_table.write[i] = ucstring.ptr();
  840. }
  841. }
  842. for (uint32_t i = string_end; i < (ofs + size); i++) {
  843. stable_extra.push_back(p_manifest[i]);
  844. }
  845. string_table_ends = ofs + size;
  846. } break;
  847. case CHUNK_XML_START_TAG: {
  848. int iofs = ofs + 8;
  849. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  850. String tname = string_table[name];
  851. uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
  852. iofs += 28;
  853. for (uint32_t i = 0; i < attrcount; i++) {
  854. uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
  855. uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
  856. uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
  857. uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);
  858. const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid);
  859. String attrname = string_table[attr_name];
  860. const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : "";
  861. //replace project information
  862. if (tname == "manifest" && attrname == "package") {
  863. string_table.write[attr_value] = get_package_name(package_name);
  864. }
  865. if (tname == "manifest" && attrname == "versionCode") {
  866. encode_uint32(version_code, &p_manifest.write[iofs + 16]);
  867. }
  868. if (tname == "manifest" && attrname == "versionName") {
  869. if (attr_value == 0xFFFFFFFF) {
  870. WARN_PRINT("Version name in a resource, should be plain text");
  871. } else {
  872. string_table.write[attr_value] = version_name;
  873. }
  874. }
  875. if (tname == "application" && attrname == "requestLegacyExternalStorage") {
  876. encode_uint32(has_read_write_storage_permission ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  877. }
  878. if (tname == "application" && attrname == "allowBackup") {
  879. encode_uint32(backup_allowed, &p_manifest.write[iofs + 16]);
  880. }
  881. if (tname == "application" && attrname == "appCategory") {
  882. encode_uint32(_get_app_category_value(app_category), &p_manifest.write[iofs + 16]);
  883. }
  884. if (tname == "application" && attrname == "isGame") {
  885. encode_uint32(app_category == APP_CATEGORY_GAME, &p_manifest.write[iofs + 16]);
  886. }
  887. if (tname == "application" && attrname == "hasFragileUserData") {
  888. encode_uint32(retain_data_on_uninstall, &p_manifest.write[iofs + 16]);
  889. }
  890. if (tname == "activity" && attrname == "screenOrientation") {
  891. encode_uint32(screen_orientation, &p_manifest.write[iofs + 16]);
  892. }
  893. if (tname == "activity" && attrname == "excludeFromRecents") {
  894. encode_uint32(exclude_from_recents, &p_manifest.write[iofs + 16]);
  895. }
  896. if (tname == "activity" && attrname == "resizeableActivity") {
  897. encode_uint32(is_resizeable, &p_manifest.write[iofs + 16]);
  898. }
  899. if (tname == "supports-screens") {
  900. if (attrname == "smallScreens") {
  901. encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  902. } else if (attrname == "normalScreens") {
  903. encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  904. } else if (attrname == "largeScreens") {
  905. encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  906. } else if (attrname == "xlargeScreens") {
  907. encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  908. }
  909. }
  910. // Hand tracking related configurations
  911. if (xr_mode_index == XR_MODE_OPENXR && hand_tracking_index > XR_HAND_TRACKING_NONE) {
  912. if (tname == "meta-data" && attrname == "name" && value == "xr_hand_tracking_metadata_name") {
  913. string_table.write[attr_value] = "com.oculus.handtracking.frequency";
  914. }
  915. if (tname == "meta-data" && attrname == "value" && value == "xr_hand_tracking_metadata_value") {
  916. string_table.write[attr_value] = (hand_tracking_frequency_index == XR_HAND_TRACKING_FREQUENCY_LOW ? "LOW" : "HIGH");
  917. }
  918. if (tname == "meta-data" && attrname == "name" && value == "xr_hand_tracking_version_name") {
  919. string_table.write[attr_value] = "com.oculus.handtracking.version";
  920. }
  921. if (tname == "meta-data" && attrname == "value" && value == "xr_hand_tracking_version_value") {
  922. string_table.write[attr_value] = "V2.0";
  923. }
  924. }
  925. iofs += 20;
  926. }
  927. } break;
  928. case CHUNK_XML_END_TAG: {
  929. int iofs = ofs + 8;
  930. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  931. String tname = string_table[name];
  932. if (tname == "uses-feature") {
  933. Vector<String> feature_names;
  934. Vector<bool> feature_required_list;
  935. Vector<int> feature_versions;
  936. if (xr_mode_index == XR_MODE_OPENXR) {
  937. // Check for hand tracking
  938. if (hand_tracking_index > XR_HAND_TRACKING_NONE) {
  939. feature_names.push_back("oculus.software.handtracking");
  940. feature_required_list.push_back(hand_tracking_index == XR_HAND_TRACKING_REQUIRED);
  941. feature_versions.push_back(-1); // no version attribute should be added.
  942. }
  943. // Check for passthrough
  944. int passthrough_mode = p_preset->get("xr_features/passthrough");
  945. if (passthrough_mode > XR_PASSTHROUGH_NONE) {
  946. feature_names.push_back("com.oculus.feature.PASSTHROUGH");
  947. feature_required_list.push_back(passthrough_mode == XR_PASSTHROUGH_REQUIRED);
  948. feature_versions.push_back(-1);
  949. }
  950. }
  951. if (feature_names.size() > 0) {
  952. ofs += 24; // skip over end tag
  953. // save manifest ending so we can restore it
  954. Vector<uint8_t> manifest_end;
  955. uint32_t manifest_cur_size = p_manifest.size();
  956. manifest_end.resize(p_manifest.size() - ofs);
  957. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  958. int32_t attr_name_string = string_table.find("name");
  959. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  960. int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android");
  961. if (ns_android_string == -1) {
  962. string_table.push_back("http://schemas.android.com/apk/res/android");
  963. ns_android_string = string_table.size() - 1;
  964. }
  965. int32_t attr_uses_feature_string = string_table.find("uses-feature");
  966. if (attr_uses_feature_string == -1) {
  967. string_table.push_back("uses-feature");
  968. attr_uses_feature_string = string_table.size() - 1;
  969. }
  970. int32_t attr_required_string = string_table.find("required");
  971. if (attr_required_string == -1) {
  972. string_table.push_back("required");
  973. attr_required_string = string_table.size() - 1;
  974. }
  975. for (int i = 0; i < feature_names.size(); i++) {
  976. String feature_name = feature_names[i];
  977. bool feature_required = feature_required_list[i];
  978. int feature_version = feature_versions[i];
  979. bool has_version_attribute = feature_version != -1;
  980. print_line("Adding feature " + feature_name);
  981. int32_t feature_string = string_table.find(feature_name);
  982. if (feature_string == -1) {
  983. string_table.push_back(feature_name);
  984. feature_string = string_table.size() - 1;
  985. }
  986. String required_value_string = feature_required ? "true" : "false";
  987. int32_t required_value = string_table.find(required_value_string);
  988. if (required_value == -1) {
  989. string_table.push_back(required_value_string);
  990. required_value = string_table.size() - 1;
  991. }
  992. int32_t attr_version_string = -1;
  993. int32_t version_value = -1;
  994. int tag_size;
  995. int attr_count;
  996. if (has_version_attribute) {
  997. attr_version_string = string_table.find("version");
  998. if (attr_version_string == -1) {
  999. string_table.push_back("version");
  1000. attr_version_string = string_table.size() - 1;
  1001. }
  1002. version_value = string_table.find(itos(feature_version));
  1003. if (version_value == -1) {
  1004. string_table.push_back(itos(feature_version));
  1005. version_value = string_table.size() - 1;
  1006. }
  1007. tag_size = 96; // node and three attrs + end node
  1008. attr_count = 3;
  1009. } else {
  1010. tag_size = 76; // node and two attrs + end node
  1011. attr_count = 2;
  1012. }
  1013. manifest_cur_size += tag_size + 24;
  1014. p_manifest.resize(manifest_cur_size);
  1015. // start tag
  1016. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  1017. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1018. encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size
  1019. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1020. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1021. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1022. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  1023. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  1024. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  1025. encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs
  1026. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  1027. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  1028. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  1029. // android:name attribute
  1030. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  1031. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  1032. encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value
  1033. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  1034. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  1035. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  1036. encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  1037. // android:required attribute
  1038. encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns
  1039. encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name'
  1040. encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value
  1041. encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size
  1042. p_manifest.write[ofs + 70] = 0; // typedvalue_always0
  1043. p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)
  1044. encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference
  1045. ofs += 76;
  1046. if (has_version_attribute) {
  1047. // android:version attribute
  1048. encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns
  1049. encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name'
  1050. encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value
  1051. encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size
  1052. p_manifest.write[ofs + 14] = 0; // typedvalue_always0
  1053. p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string)
  1054. encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference
  1055. ofs += 20;
  1056. }
  1057. // end tag
  1058. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  1059. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1060. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  1061. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1062. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1063. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1064. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  1065. ofs += 24;
  1066. }
  1067. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  1068. ofs -= 24; // go back over back end
  1069. }
  1070. }
  1071. if (tname == "manifest") {
  1072. // save manifest ending so we can restore it
  1073. Vector<uint8_t> manifest_end;
  1074. uint32_t manifest_cur_size = p_manifest.size();
  1075. manifest_end.resize(p_manifest.size() - ofs);
  1076. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  1077. int32_t attr_name_string = string_table.find("name");
  1078. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  1079. int32_t ns_android_string = string_table.find("android");
  1080. ERR_FAIL_COND_MSG(ns_android_string == -1, "Template does not have 'android' namespace.");
  1081. int32_t attr_uses_permission_string = string_table.find("uses-permission");
  1082. if (attr_uses_permission_string == -1) {
  1083. string_table.push_back("uses-permission");
  1084. attr_uses_permission_string = string_table.size() - 1;
  1085. }
  1086. for (int i = 0; i < perms.size(); ++i) {
  1087. print_line("Adding permission " + perms[i]);
  1088. manifest_cur_size += 56 + 24; // node + end node
  1089. p_manifest.resize(manifest_cur_size);
  1090. // Add permission to the string pool
  1091. int32_t perm_string = string_table.find(perms[i]);
  1092. if (perm_string == -1) {
  1093. string_table.push_back(perms[i]);
  1094. perm_string = string_table.size() - 1;
  1095. }
  1096. // start tag
  1097. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  1098. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1099. encode_uint32(56, &p_manifest.write[ofs + 4]); // size
  1100. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1101. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1102. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1103. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1104. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  1105. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  1106. encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
  1107. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  1108. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  1109. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  1110. // attribute
  1111. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  1112. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  1113. encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
  1114. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  1115. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  1116. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  1117. encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  1118. ofs += 56;
  1119. // end tag
  1120. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  1121. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1122. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  1123. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1124. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1125. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1126. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1127. ofs += 24;
  1128. }
  1129. // copy footer back in
  1130. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  1131. }
  1132. } break;
  1133. }
  1134. ofs += size;
  1135. }
  1136. //create new andriodmanifest binary
  1137. Vector<uint8_t> ret;
  1138. ret.resize(string_table_begins + string_table.size() * 4);
  1139. for (uint32_t i = 0; i < string_table_begins; i++) {
  1140. ret.write[i] = p_manifest[i];
  1141. }
  1142. ofs = 0;
  1143. for (int i = 0; i < string_table.size(); i++) {
  1144. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1145. ofs += string_table[i].length() * 2 + 2 + 2;
  1146. }
  1147. ret.resize(ret.size() + ofs);
  1148. string_data_offset = ret.size() - ofs;
  1149. uint8_t *chars = &ret.write[string_data_offset];
  1150. for (int i = 0; i < string_table.size(); i++) {
  1151. String s = string_table[i];
  1152. encode_uint16(s.length(), chars);
  1153. chars += 2;
  1154. for (int j = 0; j < s.length(); j++) {
  1155. encode_uint16(s[j], chars);
  1156. chars += 2;
  1157. }
  1158. encode_uint16(0, chars);
  1159. chars += 2;
  1160. }
  1161. for (int i = 0; i < stable_extra.size(); i++) {
  1162. ret.push_back(stable_extra[i]);
  1163. }
  1164. //pad
  1165. while (ret.size() % 4) {
  1166. ret.push_back(0);
  1167. }
  1168. uint32_t new_stable_end = ret.size();
  1169. uint32_t extra = (p_manifest.size() - string_table_ends);
  1170. ret.resize(new_stable_end + extra);
  1171. for (uint32_t i = 0; i < extra; i++) {
  1172. ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
  1173. }
  1174. while (ret.size() % 4) {
  1175. ret.push_back(0);
  1176. }
  1177. encode_uint32(ret.size(), &ret.write[4]); //update new file size
  1178. encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
  1179. encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
  1180. encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset
  1181. p_manifest = ret;
  1182. }
  1183. String EditorExportPlatformAndroid::_parse_string(const uint8_t *p_bytes, bool p_utf8) {
  1184. uint32_t offset = 0;
  1185. uint32_t len = 0;
  1186. if (p_utf8) {
  1187. uint8_t byte = p_bytes[offset];
  1188. if (byte & 0x80) {
  1189. offset += 2;
  1190. } else {
  1191. offset += 1;
  1192. }
  1193. byte = p_bytes[offset];
  1194. offset++;
  1195. if (byte & 0x80) {
  1196. len = byte & 0x7F;
  1197. len = (len << 8) + p_bytes[offset];
  1198. offset++;
  1199. } else {
  1200. len = byte;
  1201. }
  1202. } else {
  1203. len = decode_uint16(&p_bytes[offset]);
  1204. offset += 2;
  1205. if (len & 0x8000) {
  1206. len &= 0x7FFF;
  1207. len = (len << 16) + decode_uint16(&p_bytes[offset]);
  1208. offset += 2;
  1209. }
  1210. }
  1211. if (p_utf8) {
  1212. Vector<uint8_t> str8;
  1213. str8.resize(len + 1);
  1214. for (uint32_t i = 0; i < len; i++) {
  1215. str8.write[i] = p_bytes[offset + i];
  1216. }
  1217. str8.write[len] = 0;
  1218. String str;
  1219. str.parse_utf8((const char *)str8.ptr());
  1220. return str;
  1221. } else {
  1222. String str;
  1223. for (uint32_t i = 0; i < len; i++) {
  1224. char32_t c = decode_uint16(&p_bytes[offset + i * 2]);
  1225. if (c == 0) {
  1226. break;
  1227. }
  1228. str += String::chr(c);
  1229. }
  1230. return str;
  1231. }
  1232. }
  1233. void EditorExportPlatformAndroid::_fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &r_manifest) {
  1234. const int UTF8_FLAG = 0x00000100;
  1235. uint32_t string_block_len = decode_uint32(&r_manifest[16]);
  1236. uint32_t string_count = decode_uint32(&r_manifest[20]);
  1237. uint32_t string_flags = decode_uint32(&r_manifest[28]);
  1238. const uint32_t string_table_begins = 40;
  1239. Vector<String> string_table;
  1240. String package_name = p_preset->get("package/name");
  1241. Dictionary appnames = GLOBAL_GET("application/config/name_localized");
  1242. for (uint32_t i = 0; i < string_count; i++) {
  1243. uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]);
  1244. offset += string_table_begins + string_count * 4;
  1245. String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG);
  1246. if (str.begins_with("godot-project-name")) {
  1247. if (str == "godot-project-name") {
  1248. //project name
  1249. str = get_project_name(package_name);
  1250. } else {
  1251. String lang = str.substr(str.rfind("-") + 1, str.length()).replace("-", "_");
  1252. if (appnames.has(lang)) {
  1253. str = appnames[lang];
  1254. } else {
  1255. str = get_project_name(package_name);
  1256. }
  1257. }
  1258. }
  1259. string_table.push_back(str);
  1260. }
  1261. //write a new string table, but use 16 bits
  1262. Vector<uint8_t> ret;
  1263. ret.resize(string_table_begins + string_table.size() * 4);
  1264. for (uint32_t i = 0; i < string_table_begins; i++) {
  1265. ret.write[i] = r_manifest[i];
  1266. }
  1267. int ofs = 0;
  1268. for (int i = 0; i < string_table.size(); i++) {
  1269. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1270. ofs += string_table[i].length() * 2 + 2 + 2;
  1271. }
  1272. ret.resize(ret.size() + ofs);
  1273. uint8_t *chars = &ret.write[ret.size() - ofs];
  1274. for (int i = 0; i < string_table.size(); i++) {
  1275. String s = string_table[i];
  1276. encode_uint16(s.length(), chars);
  1277. chars += 2;
  1278. for (int j = 0; j < s.length(); j++) {
  1279. encode_uint16(s[j], chars);
  1280. chars += 2;
  1281. }
  1282. encode_uint16(0, chars);
  1283. chars += 2;
  1284. }
  1285. //pad
  1286. while (ret.size() % 4) {
  1287. ret.push_back(0);
  1288. }
  1289. //change flags to not use utf8
  1290. encode_uint32(string_flags & ~0x100, &ret.write[28]);
  1291. //change length
  1292. encode_uint32(ret.size() - 12, &ret.write[16]);
  1293. //append the rest...
  1294. int rest_from = 12 + string_block_len;
  1295. int rest_to = ret.size();
  1296. int rest_len = (r_manifest.size() - rest_from);
  1297. ret.resize(ret.size() + (r_manifest.size() - rest_from));
  1298. for (int i = 0; i < rest_len; i++) {
  1299. ret.write[rest_to + i] = r_manifest[rest_from + i];
  1300. }
  1301. //finally update the size
  1302. encode_uint32(ret.size(), &ret.write[4]);
  1303. r_manifest = ret;
  1304. //printf("end\n");
  1305. }
  1306. void EditorExportPlatformAndroid::_load_image_data(const Ref<Image> &p_splash_image, Vector<uint8_t> &p_data) {
  1307. Vector<uint8_t> png_buffer;
  1308. Error err = PNGDriverCommon::image_to_png(p_splash_image, png_buffer);
  1309. if (err == OK) {
  1310. p_data.resize(png_buffer.size());
  1311. memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());
  1312. } else {
  1313. String err_str = String("Failed to convert splash image to png.");
  1314. WARN_PRINT(err_str.utf8().get_data());
  1315. }
  1316. }
  1317. void EditorExportPlatformAndroid::_process_launcher_icons(const String &p_file_name, const Ref<Image> &p_source_image, int dimension, Vector<uint8_t> &p_data) {
  1318. Ref<Image> working_image = p_source_image;
  1319. if (p_source_image->get_width() != dimension || p_source_image->get_height() != dimension) {
  1320. working_image = p_source_image->duplicate();
  1321. working_image->resize(dimension, dimension, Image::Interpolation::INTERPOLATE_LANCZOS);
  1322. }
  1323. Vector<uint8_t> png_buffer;
  1324. Error err = PNGDriverCommon::image_to_png(working_image, png_buffer);
  1325. if (err == OK) {
  1326. p_data.resize(png_buffer.size());
  1327. memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());
  1328. } else {
  1329. String err_str = String("Failed to convert resized icon (") + p_file_name + ") to png.";
  1330. WARN_PRINT(err_str.utf8().get_data());
  1331. }
  1332. }
  1333. String EditorExportPlatformAndroid::load_splash_refs(Ref<Image> &splash_image, Ref<Image> &splash_bg_color_image) {
  1334. bool scale_splash = GLOBAL_GET("application/boot_splash/fullsize");
  1335. bool apply_filter = GLOBAL_GET("application/boot_splash/use_filter");
  1336. String project_splash_path = GLOBAL_GET("application/boot_splash/image");
  1337. if (!project_splash_path.is_empty()) {
  1338. splash_image.instantiate();
  1339. print_verbose("Loading splash image: " + project_splash_path);
  1340. const Error err = ImageLoader::load_image(project_splash_path, splash_image);
  1341. if (err) {
  1342. if (OS::get_singleton()->is_stdout_verbose()) {
  1343. print_error("- unable to load splash image from " + project_splash_path + " (" + itos(err) + ")");
  1344. }
  1345. splash_image.unref();
  1346. }
  1347. }
  1348. if (splash_image.is_null()) {
  1349. // Use the default
  1350. print_verbose("Using default splash image.");
  1351. splash_image = Ref<Image>(memnew(Image(boot_splash_png)));
  1352. }
  1353. if (scale_splash) {
  1354. Size2 screen_size = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
  1355. int width, height;
  1356. if (screen_size.width > screen_size.height) {
  1357. // scale horizontally
  1358. height = screen_size.height;
  1359. width = splash_image->get_width() * screen_size.height / splash_image->get_height();
  1360. } else {
  1361. // scale vertically
  1362. width = screen_size.width;
  1363. height = splash_image->get_height() * screen_size.width / splash_image->get_width();
  1364. }
  1365. splash_image->resize(width, height);
  1366. }
  1367. // Setup the splash bg color
  1368. bool bg_color_valid;
  1369. Color bg_color = ProjectSettings::get_singleton()->get("application/boot_splash/bg_color", &bg_color_valid);
  1370. if (!bg_color_valid) {
  1371. bg_color = boot_splash_bg_color;
  1372. }
  1373. print_verbose("Creating splash background color image.");
  1374. splash_bg_color_image.instantiate();
  1375. splash_bg_color_image->initialize_data(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format());
  1376. splash_bg_color_image->fill(bg_color);
  1377. String processed_splash_config_xml = vformat(SPLASH_CONFIG_XML_CONTENT, bool_to_string(apply_filter));
  1378. return processed_splash_config_xml;
  1379. }
  1380. void EditorExportPlatformAndroid::load_icon_refs(const Ref<EditorExportPreset> &p_preset, Ref<Image> &icon, Ref<Image> &foreground, Ref<Image> &background) {
  1381. String project_icon_path = GLOBAL_GET("application/config/icon");
  1382. icon.instantiate();
  1383. foreground.instantiate();
  1384. background.instantiate();
  1385. // Regular icon: user selection -> project icon -> default.
  1386. String path = static_cast<String>(p_preset->get(launcher_icon_option)).strip_edges();
  1387. print_verbose("Loading regular icon from " + path);
  1388. if (path.is_empty() || ImageLoader::load_image(path, icon) != OK) {
  1389. print_verbose("- falling back to project icon: " + project_icon_path);
  1390. ImageLoader::load_image(project_icon_path, icon);
  1391. }
  1392. // Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default).
  1393. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_foreground_option)).strip_edges();
  1394. print_verbose("Loading adaptive foreground icon from " + path);
  1395. if (path.is_empty() || ImageLoader::load_image(path, foreground) != OK) {
  1396. print_verbose("- falling back to using the regular icon");
  1397. foreground = icon;
  1398. }
  1399. // Adaptive background: user selection -> default.
  1400. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_background_option)).strip_edges();
  1401. if (!path.is_empty()) {
  1402. print_verbose("Loading adaptive background icon from " + path);
  1403. ImageLoader::load_image(path, background);
  1404. }
  1405. }
  1406. void EditorExportPlatformAndroid::store_image(const LauncherIcon launcher_icon, const Vector<uint8_t> &data) {
  1407. store_image(launcher_icon.export_path, data);
  1408. }
  1409. void EditorExportPlatformAndroid::store_image(const String &export_path, const Vector<uint8_t> &data) {
  1410. String img_path = export_path.insert(0, "res://android/build/");
  1411. store_file_at_path(img_path, data);
  1412. }
  1413. void EditorExportPlatformAndroid::_copy_icons_to_gradle_project(const Ref<EditorExportPreset> &p_preset,
  1414. const String &processed_splash_config_xml,
  1415. const Ref<Image> &splash_image,
  1416. const Ref<Image> &splash_bg_color_image,
  1417. const Ref<Image> &main_image,
  1418. const Ref<Image> &foreground,
  1419. const Ref<Image> &background) {
  1420. // Store the splash configuration
  1421. if (!processed_splash_config_xml.is_empty()) {
  1422. print_verbose("Storing processed splash configuration: " + String("\n") + processed_splash_config_xml);
  1423. store_string_at_path(SPLASH_CONFIG_PATH, processed_splash_config_xml);
  1424. }
  1425. // Store the splash image
  1426. if (splash_image.is_valid() && !splash_image->is_empty()) {
  1427. print_verbose("Storing splash image in " + String(SPLASH_IMAGE_EXPORT_PATH));
  1428. Vector<uint8_t> data;
  1429. _load_image_data(splash_image, data);
  1430. store_image(SPLASH_IMAGE_EXPORT_PATH, data);
  1431. }
  1432. // Store the splash bg color image
  1433. if (splash_bg_color_image.is_valid() && !splash_bg_color_image->is_empty()) {
  1434. print_verbose("Storing splash background image in " + String(SPLASH_BG_COLOR_PATH));
  1435. Vector<uint8_t> data;
  1436. _load_image_data(splash_bg_color_image, data);
  1437. store_image(SPLASH_BG_COLOR_PATH, data);
  1438. }
  1439. // Prepare images to be resized for the icons. If some image ends up being uninitialized,
  1440. // the default image from the export template will be used.
  1441. for (int i = 0; i < icon_densities_count; ++i) {
  1442. if (main_image.is_valid() && !main_image->is_empty()) {
  1443. print_verbose("Processing launcher icon for dimension " + itos(launcher_icons[i].dimensions) + " into " + launcher_icons[i].export_path);
  1444. Vector<uint8_t> data;
  1445. _process_launcher_icons(launcher_icons[i].export_path, main_image, launcher_icons[i].dimensions, data);
  1446. store_image(launcher_icons[i], data);
  1447. }
  1448. if (foreground.is_valid() && !foreground->is_empty()) {
  1449. print_verbose("Processing launcher adaptive icon foreground for dimension " + itos(launcher_adaptive_icon_foregrounds[i].dimensions) + " into " + launcher_adaptive_icon_foregrounds[i].export_path);
  1450. Vector<uint8_t> data;
  1451. _process_launcher_icons(launcher_adaptive_icon_foregrounds[i].export_path, foreground,
  1452. launcher_adaptive_icon_foregrounds[i].dimensions, data);
  1453. store_image(launcher_adaptive_icon_foregrounds[i], data);
  1454. }
  1455. if (background.is_valid() && !background->is_empty()) {
  1456. print_verbose("Processing launcher adaptive icon background for dimension " + itos(launcher_adaptive_icon_backgrounds[i].dimensions) + " into " + launcher_adaptive_icon_backgrounds[i].export_path);
  1457. Vector<uint8_t> data;
  1458. _process_launcher_icons(launcher_adaptive_icon_backgrounds[i].export_path, background,
  1459. launcher_adaptive_icon_backgrounds[i].dimensions, data);
  1460. store_image(launcher_adaptive_icon_backgrounds[i], data);
  1461. }
  1462. }
  1463. }
  1464. Vector<EditorExportPlatformAndroid::ABI> EditorExportPlatformAndroid::get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
  1465. Vector<ABI> abis = get_abis();
  1466. Vector<ABI> enabled_abis;
  1467. for (int i = 0; i < abis.size(); ++i) {
  1468. bool is_enabled = p_preset->get("architectures/" + abis[i].abi);
  1469. if (is_enabled) {
  1470. enabled_abis.push_back(abis[i]);
  1471. }
  1472. }
  1473. return enabled_abis;
  1474. }
  1475. void EditorExportPlatformAndroid::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const {
  1476. r_features->push_back("etc2");
  1477. r_features->push_back("astc");
  1478. Vector<ABI> abis = get_enabled_abis(p_preset);
  1479. for (int i = 0; i < abis.size(); ++i) {
  1480. r_features->push_back(abis[i].arch);
  1481. r_features->push_back(abis[i].abi);
  1482. }
  1483. }
  1484. void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_options) {
  1485. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1486. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1487. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_build/use_custom_build"), false));
  1488. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "custom_build/export_format", PROPERTY_HINT_ENUM, "Export APK,Export AAB"), EXPORT_FORMAT_APK));
  1489. // Using String instead of int to default to an empty string (no override) with placeholder for instructions (see GH-62465).
  1490. // This implies doing validation that the string is a proper int.
  1491. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_build/min_sdk", PROPERTY_HINT_PLACEHOLDER_TEXT, vformat("%d (default)", DEFAULT_MIN_SDK_VERSION)), ""));
  1492. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_build/target_sdk", PROPERTY_HINT_PLACEHOLDER_TEXT, vformat("%d (default)", DEFAULT_TARGET_SDK_VERSION)), ""));
  1493. Vector<PluginConfigAndroid> plugins_configs = get_plugins();
  1494. for (int i = 0; i < plugins_configs.size(); i++) {
  1495. print_verbose("Found Android plugin " + plugins_configs[i].name);
  1496. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("plugins"), plugins_configs[i].name)), false));
  1497. }
  1498. plugins_changed.clear();
  1499. // Android supports multiple architectures in an app bundle, so
  1500. // we expose each option as a checkbox in the export dialog.
  1501. const Vector<ABI> abis = get_abis();
  1502. for (int i = 0; i < abis.size(); ++i) {
  1503. const String abi = abis[i].abi;
  1504. // All Android devices supporting Vulkan run 64-bit Android,
  1505. // so there is usually no point in exporting for 32-bit Android.
  1506. const bool is_default = abi == "arm64-v8a";
  1507. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("architectures"), abi)), is_default));
  1508. }
  1509. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
  1510. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
  1511. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
  1512. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
  1513. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
  1514. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
  1515. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
  1516. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
  1517. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
  1518. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
  1519. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
  1520. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "package/app_category", PROPERTY_HINT_ENUM, "Accessibility,Audio,Game,Image,Maps,News,Productivity,Social,Video"), APP_CATEGORY_GAME));
  1521. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/retain_data_on_uninstall"), false));
  1522. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/exclude_from_recents"), false));
  1523. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icon_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1524. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_foreground_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1525. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_background_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1526. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/opengl_debug"), false));
  1527. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,OpenXR"), XR_MODE_REGULAR));
  1528. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking", PROPERTY_HINT_ENUM, "None,Optional,Required"), XR_HAND_TRACKING_NONE));
  1529. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking_frequency", PROPERTY_HINT_ENUM, "Low,High"), XR_HAND_TRACKING_FREQUENCY_LOW));
  1530. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/passthrough", PROPERTY_HINT_ENUM, "None,Optional,Required"), XR_PASSTHROUGH_NONE));
  1531. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
  1532. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
  1533. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
  1534. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
  1535. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
  1536. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data_backup/allow"), false));
  1537. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
  1538. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
  1539. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
  1540. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));
  1541. r_options->push_back(ExportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "permissions/custom_permissions"), PackedStringArray()));
  1542. const char **perms = android_perms;
  1543. while (*perms) {
  1544. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, vformat("%s/%s", PNAME("permissions"), String(*perms).to_lower())), false));
  1545. perms++;
  1546. }
  1547. }
  1548. String EditorExportPlatformAndroid::get_name() const {
  1549. return "Android";
  1550. }
  1551. String EditorExportPlatformAndroid::get_os_name() const {
  1552. return "Android";
  1553. }
  1554. Ref<Texture2D> EditorExportPlatformAndroid::get_logo() const {
  1555. return logo;
  1556. }
  1557. bool EditorExportPlatformAndroid::should_update_export_options() {
  1558. bool export_options_changed = plugins_changed.is_set();
  1559. if (export_options_changed) {
  1560. // don't clear unless we're reporting true, to avoid race
  1561. plugins_changed.clear();
  1562. }
  1563. return export_options_changed;
  1564. }
  1565. bool EditorExportPlatformAndroid::poll_export() {
  1566. bool dc = devices_changed.is_set();
  1567. if (dc) {
  1568. // don't clear unless we're reporting true, to avoid race
  1569. devices_changed.clear();
  1570. }
  1571. return dc;
  1572. }
  1573. int EditorExportPlatformAndroid::get_options_count() const {
  1574. MutexLock lock(device_lock);
  1575. return devices.size();
  1576. }
  1577. String EditorExportPlatformAndroid::get_options_tooltip() const {
  1578. return TTR("Select device from the list");
  1579. }
  1580. String EditorExportPlatformAndroid::get_option_label(int p_index) const {
  1581. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1582. MutexLock lock(device_lock);
  1583. return devices[p_index].name;
  1584. }
  1585. String EditorExportPlatformAndroid::get_option_tooltip(int p_index) const {
  1586. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1587. MutexLock lock(device_lock);
  1588. String s = devices[p_index].description;
  1589. if (devices.size() == 1) {
  1590. // Tooltip will be:
  1591. // Name
  1592. // Description
  1593. s = devices[p_index].name + "\n\n" + s;
  1594. }
  1595. return s;
  1596. }
  1597. Error EditorExportPlatformAndroid::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
  1598. ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
  1599. String can_export_error;
  1600. bool can_export_missing_templates;
  1601. if (!can_export(p_preset, can_export_error, can_export_missing_templates)) {
  1602. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), can_export_error);
  1603. return ERR_UNCONFIGURED;
  1604. }
  1605. MutexLock lock(device_lock);
  1606. EditorProgress ep("run", vformat(TTR("Running on %s"), devices[p_device].name), 3);
  1607. String adb = get_adb_path();
  1608. // Export_temp APK.
  1609. if (ep.step(TTR("Exporting APK..."), 0)) {
  1610. return ERR_SKIP;
  1611. }
  1612. const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
  1613. const bool use_reverse = devices[p_device].api_level >= 21;
  1614. if (use_reverse) {
  1615. p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
  1616. }
  1617. String tmp_export_path = EditorPaths::get_singleton()->get_cache_dir().path_join("tmpexport." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");
  1618. #define CLEANUP_AND_RETURN(m_err) \
  1619. { \
  1620. DirAccess::remove_file_or_error(tmp_export_path); \
  1621. return m_err; \
  1622. } \
  1623. ((void)0)
  1624. // Export to temporary APK before sending to device.
  1625. Error err = export_project_helper(p_preset, true, tmp_export_path, EXPORT_FORMAT_APK, true, p_debug_flags);
  1626. if (err != OK) {
  1627. CLEANUP_AND_RETURN(err);
  1628. }
  1629. List<String> args;
  1630. int rv;
  1631. String output;
  1632. bool remove_prev = EDITOR_GET("export/android/one_click_deploy_clear_previous_install");
  1633. String version_name = p_preset->get("version/name");
  1634. String package_name = p_preset->get("package/unique_name");
  1635. if (remove_prev) {
  1636. if (ep.step(TTR("Uninstalling..."), 1)) {
  1637. CLEANUP_AND_RETURN(ERR_SKIP);
  1638. }
  1639. print_line("Uninstalling previous version: " + devices[p_device].name);
  1640. args.push_back("-s");
  1641. args.push_back(devices[p_device].id);
  1642. args.push_back("uninstall");
  1643. args.push_back(get_package_name(package_name));
  1644. output.clear();
  1645. err = OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1646. print_verbose(output);
  1647. }
  1648. print_line("Installing to device (please wait...): " + devices[p_device].name);
  1649. if (ep.step(TTR("Installing to device, please wait..."), 2)) {
  1650. CLEANUP_AND_RETURN(ERR_SKIP);
  1651. }
  1652. args.clear();
  1653. args.push_back("-s");
  1654. args.push_back(devices[p_device].id);
  1655. args.push_back("install");
  1656. args.push_back("-r");
  1657. args.push_back(tmp_export_path);
  1658. output.clear();
  1659. err = OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1660. print_verbose(output);
  1661. if (err || rv != 0) {
  1662. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Could not install to device: %s"), output));
  1663. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  1664. }
  1665. if (use_remote) {
  1666. if (use_reverse) {
  1667. static const char *const msg = "--- Device API >= 21; debugging over USB ---";
  1668. EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
  1669. print_line(String(msg).to_upper());
  1670. args.clear();
  1671. args.push_back("-s");
  1672. args.push_back(devices[p_device].id);
  1673. args.push_back("reverse");
  1674. args.push_back("--remove-all");
  1675. output.clear();
  1676. OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1677. print_verbose(output);
  1678. if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) {
  1679. int dbg_port = EDITOR_GET("network/debug/remote_port");
  1680. args.clear();
  1681. args.push_back("-s");
  1682. args.push_back(devices[p_device].id);
  1683. args.push_back("reverse");
  1684. args.push_back("tcp:" + itos(dbg_port));
  1685. args.push_back("tcp:" + itos(dbg_port));
  1686. output.clear();
  1687. OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1688. print_verbose(output);
  1689. print_line("Reverse result: " + itos(rv));
  1690. }
  1691. if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) {
  1692. int fs_port = EDITOR_GET("filesystem/file_server/port");
  1693. args.clear();
  1694. args.push_back("-s");
  1695. args.push_back(devices[p_device].id);
  1696. args.push_back("reverse");
  1697. args.push_back("tcp:" + itos(fs_port));
  1698. args.push_back("tcp:" + itos(fs_port));
  1699. output.clear();
  1700. err = OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1701. print_verbose(output);
  1702. print_line("Reverse result2: " + itos(rv));
  1703. }
  1704. } else {
  1705. static const char *const msg = "--- Device API < 21; debugging over Wi-Fi ---";
  1706. EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
  1707. print_line(String(msg).to_upper());
  1708. }
  1709. }
  1710. if (ep.step(TTR("Running on device..."), 3)) {
  1711. CLEANUP_AND_RETURN(ERR_SKIP);
  1712. }
  1713. args.clear();
  1714. args.push_back("-s");
  1715. args.push_back(devices[p_device].id);
  1716. args.push_back("shell");
  1717. args.push_back("am");
  1718. args.push_back("start");
  1719. if ((bool)EDITOR_GET("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17
  1720. args.push_back("--user");
  1721. args.push_back("0");
  1722. }
  1723. args.push_back("-a");
  1724. args.push_back("android.intent.action.MAIN");
  1725. args.push_back("-n");
  1726. args.push_back(get_package_name(package_name) + "/com.godot.game.GodotApp");
  1727. output.clear();
  1728. err = OS::get_singleton()->execute(adb, args, &output, &rv, true);
  1729. print_verbose(output);
  1730. if (err || rv != 0) {
  1731. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), TTR("Could not execute on device."));
  1732. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  1733. }
  1734. CLEANUP_AND_RETURN(OK);
  1735. #undef CLEANUP_AND_RETURN
  1736. }
  1737. Ref<Texture2D> EditorExportPlatformAndroid::get_run_icon() const {
  1738. return run_icon;
  1739. }
  1740. String EditorExportPlatformAndroid::get_adb_path() {
  1741. String exe_ext = "";
  1742. if (OS::get_singleton()->get_name() == "Windows") {
  1743. exe_ext = ".exe";
  1744. }
  1745. String sdk_path = EDITOR_GET("export/android/android_sdk_path");
  1746. return sdk_path.path_join("platform-tools/adb" + exe_ext);
  1747. }
  1748. String EditorExportPlatformAndroid::get_apksigner_path(int p_target_sdk, bool p_check_executes) {
  1749. if (p_target_sdk == -1) {
  1750. p_target_sdk = DEFAULT_TARGET_SDK_VERSION;
  1751. }
  1752. String exe_ext = "";
  1753. if (OS::get_singleton()->get_name() == "Windows") {
  1754. exe_ext = ".bat";
  1755. }
  1756. String apksigner_command_name = "apksigner" + exe_ext;
  1757. String sdk_path = EDITOR_GET("export/android/android_sdk_path");
  1758. String apksigner_path = "";
  1759. Error errn;
  1760. String build_tools_dir = sdk_path.path_join("build-tools");
  1761. Ref<DirAccess> da = DirAccess::open(build_tools_dir, &errn);
  1762. if (errn != OK) {
  1763. print_error("Unable to open Android 'build-tools' directory.");
  1764. return apksigner_path;
  1765. }
  1766. // There are additional versions directories we need to go through.
  1767. Vector<String> dir_list = da->get_directories();
  1768. // We need to use the version of build_tools that matches the Target SDK
  1769. // If somehow we can't find that, we see if a version between 28 and the default target SDK exists.
  1770. // We need to avoid versions <= 27 because they fail on Java versions >9
  1771. // If we can't find that, we just use the first valid version.
  1772. Vector<String> ideal_versions;
  1773. Vector<String> other_versions;
  1774. Vector<String> versions;
  1775. bool found_target_sdk = false;
  1776. // We only allow for versions <= 27 if specifically set
  1777. int min_version = p_target_sdk <= 27 ? p_target_sdk : 28;
  1778. for (String sub_dir : dir_list) {
  1779. if (!sub_dir.begins_with(".")) {
  1780. Vector<String> ver_numbers = sub_dir.split(".");
  1781. // Dir not a version number, will use as last resort
  1782. if (!ver_numbers.size() || !ver_numbers[0].is_valid_int()) {
  1783. other_versions.push_back(sub_dir);
  1784. continue;
  1785. }
  1786. int ver_number = ver_numbers[0].to_int();
  1787. if (ver_number == p_target_sdk) {
  1788. found_target_sdk = true;
  1789. //ensure this is in front of the ones we check
  1790. versions.push_back(sub_dir);
  1791. } else {
  1792. if (ver_number >= min_version && ver_number <= DEFAULT_TARGET_SDK_VERSION) {
  1793. ideal_versions.push_back(sub_dir);
  1794. } else {
  1795. other_versions.push_back(sub_dir);
  1796. }
  1797. }
  1798. }
  1799. }
  1800. // we will check ideal versions first, then other versions.
  1801. versions.append_array(ideal_versions);
  1802. versions.append_array(other_versions);
  1803. if (!versions.size()) {
  1804. print_error("Unable to find the 'apksigner' tool.");
  1805. return apksigner_path;
  1806. }
  1807. int i;
  1808. bool failed = false;
  1809. String version_to_use;
  1810. List<String> args;
  1811. args.push_back("--version");
  1812. String output;
  1813. int retval;
  1814. Error err;
  1815. for (i = 0; i < versions.size(); i++) {
  1816. // Check if the tool is here.
  1817. apksigner_path = build_tools_dir.path_join(versions[i]).path_join(apksigner_command_name);
  1818. if (FileAccess::exists(apksigner_path)) {
  1819. version_to_use = versions[i];
  1820. // If we aren't exporting, just break here.
  1821. if (!p_check_executes) {
  1822. break;
  1823. }
  1824. // we only check to see if it executes on export because it is slow to load
  1825. err = OS::get_singleton()->execute(apksigner_path, args, &output, &retval, false);
  1826. if (err || retval) {
  1827. failed = true;
  1828. } else {
  1829. break;
  1830. }
  1831. }
  1832. }
  1833. if (i == versions.size()) {
  1834. if (failed) {
  1835. print_error("All located 'apksigner' tools in " + build_tools_dir + " failed to execute");
  1836. return "<FAILED>";
  1837. } else {
  1838. print_error("Unable to find the 'apksigner' tool.");
  1839. return "";
  1840. }
  1841. }
  1842. if (!found_target_sdk) {
  1843. print_line("Could not find version of build tools that matches Target SDK, using " + version_to_use);
  1844. } else if (failed && found_target_sdk) {
  1845. print_line("Version of build tools that matches Target SDK failed to execute, using " + version_to_use);
  1846. }
  1847. return apksigner_path;
  1848. }
  1849. bool EditorExportPlatformAndroid::has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  1850. String err;
  1851. bool valid = false;
  1852. const bool custom_build_enabled = p_preset->get("custom_build/use_custom_build");
  1853. // Look for export templates (first official, and if defined custom templates).
  1854. if (!custom_build_enabled) {
  1855. String template_err;
  1856. bool dvalid = false;
  1857. bool rvalid = false;
  1858. bool has_export_templates = false;
  1859. if (p_preset->get("custom_template/debug") != "") {
  1860. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  1861. if (!dvalid) {
  1862. template_err += TTR("Custom debug template not found.") + "\n";
  1863. }
  1864. } else {
  1865. has_export_templates |= exists_export_template("android_debug.apk", &template_err);
  1866. }
  1867. if (p_preset->get("custom_template/release") != "") {
  1868. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  1869. if (!rvalid) {
  1870. template_err += TTR("Custom release template not found.") + "\n";
  1871. }
  1872. } else {
  1873. has_export_templates |= exists_export_template("android_release.apk", &template_err);
  1874. }
  1875. r_missing_templates = !has_export_templates;
  1876. valid = dvalid || rvalid || has_export_templates;
  1877. if (!valid) {
  1878. err += template_err;
  1879. }
  1880. } else {
  1881. bool installed_android_build_template = FileAccess::exists("res://android/build/build.gradle");
  1882. if (!installed_android_build_template) {
  1883. r_missing_templates = !exists_export_template("android_source.zip", &err);
  1884. err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n";
  1885. } else {
  1886. r_missing_templates = false;
  1887. }
  1888. valid = installed_android_build_template && !r_missing_templates;
  1889. }
  1890. // Validate the rest of the export configuration.
  1891. String dk = p_preset->get("keystore/debug");
  1892. String dk_user = p_preset->get("keystore/debug_user");
  1893. String dk_password = p_preset->get("keystore/debug_password");
  1894. if ((dk.is_empty() || dk_user.is_empty() || dk_password.is_empty()) && (!dk.is_empty() || !dk_user.is_empty() || !dk_password.is_empty())) {
  1895. valid = false;
  1896. err += TTR("Either Debug Keystore, Debug User AND Debug Password settings must be configured OR none of them.") + "\n";
  1897. }
  1898. if (!FileAccess::exists(dk)) {
  1899. dk = EDITOR_GET("export/android/debug_keystore");
  1900. if (!FileAccess::exists(dk)) {
  1901. valid = false;
  1902. err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";
  1903. }
  1904. }
  1905. String rk = p_preset->get("keystore/release");
  1906. String rk_user = p_preset->get("keystore/release_user");
  1907. String rk_password = p_preset->get("keystore/release_password");
  1908. if ((rk.is_empty() || rk_user.is_empty() || rk_password.is_empty()) && (!rk.is_empty() || !rk_user.is_empty() || !rk_password.is_empty())) {
  1909. valid = false;
  1910. err += TTR("Either Release Keystore, Release User AND Release Password settings must be configured OR none of them.") + "\n";
  1911. }
  1912. if (!rk.is_empty() && !FileAccess::exists(rk)) {
  1913. valid = false;
  1914. err += TTR("Release keystore incorrectly configured in the export preset.") + "\n";
  1915. }
  1916. String sdk_path = EDITOR_GET("export/android/android_sdk_path");
  1917. if (sdk_path.is_empty()) {
  1918. err += TTR("A valid Android SDK path is required in Editor Settings.") + "\n";
  1919. valid = false;
  1920. } else {
  1921. Error errn;
  1922. // Check for the platform-tools directory.
  1923. Ref<DirAccess> da = DirAccess::open(sdk_path.path_join("platform-tools"), &errn);
  1924. if (errn != OK) {
  1925. err += TTR("Invalid Android SDK path in Editor Settings.");
  1926. err += TTR("Missing 'platform-tools' directory!");
  1927. err += "\n";
  1928. valid = false;
  1929. }
  1930. // Validate that adb is available
  1931. String adb_path = get_adb_path();
  1932. if (!FileAccess::exists(adb_path)) {
  1933. err += TTR("Unable to find Android SDK platform-tools' adb command.");
  1934. err += TTR("Please check in the Android SDK directory specified in Editor Settings.");
  1935. err += "\n";
  1936. valid = false;
  1937. }
  1938. // Check for the build-tools directory.
  1939. Ref<DirAccess> build_tools_da = DirAccess::open(sdk_path.path_join("build-tools"), &errn);
  1940. if (errn != OK) {
  1941. err += TTR("Invalid Android SDK path in Editor Settings.");
  1942. err += TTR("Missing 'build-tools' directory!");
  1943. err += "\n";
  1944. valid = false;
  1945. }
  1946. String target_sdk_version = p_preset->get("custom_build/target_sdk");
  1947. if (!target_sdk_version.is_valid_int()) {
  1948. target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);
  1949. }
  1950. // Validate that apksigner is available
  1951. String apksigner_path = get_apksigner_path(target_sdk_version.to_int());
  1952. if (!FileAccess::exists(apksigner_path)) {
  1953. err += TTR("Unable to find Android SDK build-tools' apksigner command.");
  1954. err += TTR("Please check in the Android SDK directory specified in Editor Settings.");
  1955. err += "\n";
  1956. valid = false;
  1957. }
  1958. }
  1959. if (!err.is_empty()) {
  1960. r_error = err;
  1961. }
  1962. return valid;
  1963. }
  1964. bool EditorExportPlatformAndroid::has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const {
  1965. String err;
  1966. bool valid = true;
  1967. const bool custom_build_enabled = p_preset->get("custom_build/use_custom_build");
  1968. // Validate the project configuration.
  1969. bool apk_expansion = p_preset->get("apk_expansion/enable");
  1970. if (apk_expansion) {
  1971. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  1972. if (apk_expansion_pkey.is_empty()) {
  1973. valid = false;
  1974. err += TTR("Invalid public key for APK expansion.") + "\n";
  1975. }
  1976. }
  1977. String pn = p_preset->get("package/unique_name");
  1978. String pn_err;
  1979. if (!is_package_name_valid(pn, &pn_err)) {
  1980. valid = false;
  1981. err += TTR("Invalid package name:") + " " + pn_err + "\n";
  1982. }
  1983. String etc_error = test_etc2();
  1984. if (!etc_error.is_empty()) {
  1985. valid = false;
  1986. err += etc_error;
  1987. }
  1988. // Ensure that `Use Custom Build` is enabled if a plugin is selected.
  1989. String enabled_plugins_names = PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset));
  1990. if (!enabled_plugins_names.is_empty() && !custom_build_enabled) {
  1991. valid = false;
  1992. err += TTR("\"Use Custom Build\" must be enabled to use the plugins.");
  1993. err += "\n";
  1994. }
  1995. // Validate the Xr features are properly populated
  1996. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  1997. int hand_tracking = p_preset->get("xr_features/hand_tracking");
  1998. int passthrough_mode = p_preset->get("xr_features/passthrough");
  1999. if (xr_mode_index != XR_MODE_OPENXR) {
  2000. if (hand_tracking > XR_HAND_TRACKING_NONE) {
  2001. valid = false;
  2002. err += TTR("\"Hand Tracking\" is only valid when \"XR Mode\" is \"OpenXR\".");
  2003. err += "\n";
  2004. }
  2005. if (passthrough_mode > XR_PASSTHROUGH_NONE) {
  2006. valid = false;
  2007. err += TTR("\"Passthrough\" is only valid when \"XR Mode\" is \"OpenXR\".");
  2008. err += "\n";
  2009. }
  2010. }
  2011. if (int(p_preset->get("custom_build/export_format")) == EXPORT_FORMAT_AAB &&
  2012. !custom_build_enabled) {
  2013. valid = false;
  2014. err += TTR("\"Export AAB\" is only valid when \"Use Custom Build\" is enabled.");
  2015. err += "\n";
  2016. }
  2017. // Check the min sdk version.
  2018. String min_sdk_str = p_preset->get("custom_build/min_sdk");
  2019. int min_sdk_int = DEFAULT_MIN_SDK_VERSION;
  2020. if (!min_sdk_str.is_empty()) { // Empty means no override, nothing to do.
  2021. if (!custom_build_enabled) {
  2022. valid = false;
  2023. err += TTR("\"Min SDK\" can only be overridden when \"Use Custom Build\" is enabled.");
  2024. err += "\n";
  2025. }
  2026. if (!min_sdk_str.is_valid_int()) {
  2027. valid = false;
  2028. err += vformat(TTR("\"Min SDK\" should be a valid integer, but got \"%s\" which is invalid."), min_sdk_str);
  2029. err += "\n";
  2030. } else {
  2031. min_sdk_int = min_sdk_str.to_int();
  2032. if (min_sdk_int < DEFAULT_MIN_SDK_VERSION) {
  2033. valid = false;
  2034. err += vformat(TTR("\"Min SDK\" cannot be lower than %d, which is the version needed by the Godot library."), DEFAULT_MIN_SDK_VERSION);
  2035. err += "\n";
  2036. }
  2037. }
  2038. }
  2039. // Check the target sdk version.
  2040. String target_sdk_str = p_preset->get("custom_build/target_sdk");
  2041. int target_sdk_int = DEFAULT_TARGET_SDK_VERSION;
  2042. if (!target_sdk_str.is_empty()) { // Empty means no override, nothing to do.
  2043. if (!custom_build_enabled) {
  2044. valid = false;
  2045. err += TTR("\"Target SDK\" can only be overridden when \"Use Custom Build\" is enabled.");
  2046. err += "\n";
  2047. }
  2048. if (!target_sdk_str.is_valid_int()) {
  2049. valid = false;
  2050. err += vformat(TTR("\"Target SDK\" should be a valid integer, but got \"%s\" which is invalid."), target_sdk_str);
  2051. err += "\n";
  2052. } else {
  2053. target_sdk_int = target_sdk_str.to_int();
  2054. if (target_sdk_int > DEFAULT_TARGET_SDK_VERSION) {
  2055. // Warning only, so don't override `valid`.
  2056. err += 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);
  2057. err += "\n";
  2058. }
  2059. }
  2060. }
  2061. if (target_sdk_int < min_sdk_int) {
  2062. valid = false;
  2063. err += TTR("\"Target SDK\" version must be greater or equal to \"Min SDK\" version.");
  2064. err += "\n";
  2065. }
  2066. r_error = err;
  2067. return valid;
  2068. }
  2069. List<String> EditorExportPlatformAndroid::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  2070. List<String> list;
  2071. list.push_back("apk");
  2072. list.push_back("aab");
  2073. return list;
  2074. }
  2075. String EditorExportPlatformAndroid::get_apk_expansion_fullpath(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
  2076. int version_code = p_preset->get("version/code");
  2077. String package_name = p_preset->get("package/unique_name");
  2078. String apk_file_name = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
  2079. String fullpath = p_path.get_base_dir().path_join(apk_file_name);
  2080. return fullpath;
  2081. }
  2082. Error EditorExportPlatformAndroid::save_apk_expansion_file(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
  2083. String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
  2084. Error err = save_pack(p_preset, p_debug, fullpath);
  2085. return err;
  2086. }
  2087. void EditorExportPlatformAndroid::get_command_line_flags(const Ref<EditorExportPreset> &p_preset, const String &p_path, int p_flags, Vector<uint8_t> &r_command_line_flags) {
  2088. String cmdline = p_preset->get("command_line/extra_args");
  2089. Vector<String> command_line_strings = cmdline.strip_edges().split(" ");
  2090. for (int i = 0; i < command_line_strings.size(); i++) {
  2091. if (command_line_strings[i].strip_edges().length() == 0) {
  2092. command_line_strings.remove_at(i);
  2093. i--;
  2094. }
  2095. }
  2096. gen_export_flags(command_line_strings, p_flags);
  2097. bool apk_expansion = p_preset->get("apk_expansion/enable");
  2098. if (apk_expansion) {
  2099. String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
  2100. String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");
  2101. command_line_strings.push_back("--use_apk_expansion");
  2102. command_line_strings.push_back("--apk_expansion_md5");
  2103. command_line_strings.push_back(FileAccess::get_md5(fullpath));
  2104. command_line_strings.push_back("--apk_expansion_key");
  2105. command_line_strings.push_back(apk_expansion_public_key.strip_edges());
  2106. }
  2107. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  2108. if (xr_mode_index == XR_MODE_OPENXR) {
  2109. command_line_strings.push_back("--xr_mode_openxr");
  2110. } else { // XRMode.REGULAR is the default.
  2111. command_line_strings.push_back("--xr_mode_regular");
  2112. }
  2113. bool immersive = p_preset->get("screen/immersive_mode");
  2114. if (immersive) {
  2115. command_line_strings.push_back("--use_immersive");
  2116. }
  2117. bool debug_opengl = p_preset->get("graphics/opengl_debug");
  2118. if (debug_opengl) {
  2119. command_line_strings.push_back("--debug_opengl");
  2120. }
  2121. if (command_line_strings.size()) {
  2122. r_command_line_flags.resize(4);
  2123. encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);
  2124. for (int i = 0; i < command_line_strings.size(); i++) {
  2125. print_line(itos(i) + " param: " + command_line_strings[i]);
  2126. CharString command_line_argument = command_line_strings[i].utf8();
  2127. int base = r_command_line_flags.size();
  2128. int length = command_line_argument.length();
  2129. if (length == 0) {
  2130. continue;
  2131. }
  2132. r_command_line_flags.resize(base + 4 + length);
  2133. encode_uint32(length, &r_command_line_flags.write[base]);
  2134. memcpy(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);
  2135. }
  2136. }
  2137. }
  2138. Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &export_path, EditorProgress &ep) {
  2139. int export_format = int(p_preset->get("custom_build/export_format"));
  2140. String export_label = export_format == EXPORT_FORMAT_AAB ? "AAB" : "APK";
  2141. String release_keystore = p_preset->get("keystore/release");
  2142. String release_username = p_preset->get("keystore/release_user");
  2143. String release_password = p_preset->get("keystore/release_password");
  2144. String target_sdk_version = p_preset->get("custom_build/target_sdk");
  2145. if (!target_sdk_version.is_valid_int()) {
  2146. target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);
  2147. }
  2148. String apksigner = get_apksigner_path(target_sdk_version.to_int(), true);
  2149. print_verbose("Starting signing of the " + export_label + " binary using " + apksigner);
  2150. if (apksigner == "<FAILED>") {
  2151. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(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 %s is unsigned."), export_label));
  2152. return OK;
  2153. }
  2154. if (!FileAccess::exists(apksigner)) {
  2155. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("'apksigner' could not be found. Please check that the command is available in the Android SDK build-tools directory. The resulting %s is unsigned."), export_label));
  2156. return OK;
  2157. }
  2158. String keystore;
  2159. String password;
  2160. String user;
  2161. if (p_debug) {
  2162. keystore = p_preset->get("keystore/debug");
  2163. password = p_preset->get("keystore/debug_password");
  2164. user = p_preset->get("keystore/debug_user");
  2165. if (keystore.is_empty()) {
  2166. keystore = EDITOR_GET("export/android/debug_keystore");
  2167. password = EDITOR_GET("export/android/debug_keystore_pass");
  2168. user = EDITOR_GET("export/android/debug_keystore_user");
  2169. }
  2170. if (ep.step(vformat(TTR("Signing debug %s..."), export_label), 104)) {
  2171. return ERR_SKIP;
  2172. }
  2173. } else {
  2174. keystore = release_keystore;
  2175. password = release_password;
  2176. user = release_username;
  2177. if (ep.step(vformat(TTR("Signing release %s..."), export_label), 104)) {
  2178. return ERR_SKIP;
  2179. }
  2180. }
  2181. if (!FileAccess::exists(keystore)) {
  2182. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not find keystore, unable to export."));
  2183. return ERR_FILE_CANT_OPEN;
  2184. }
  2185. String output;
  2186. List<String> args;
  2187. args.push_back("sign");
  2188. args.push_back("--verbose");
  2189. args.push_back("--ks");
  2190. args.push_back(keystore);
  2191. args.push_back("--ks-pass");
  2192. args.push_back("pass:" + password);
  2193. args.push_back("--ks-key-alias");
  2194. args.push_back(user);
  2195. args.push_back(export_path);
  2196. if (OS::get_singleton()->is_stdout_verbose() && p_debug) {
  2197. // We only print verbose logs with credentials for debug builds to avoid leaking release keystore credentials.
  2198. print_verbose("Signing debug binary using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));
  2199. } else {
  2200. List<String> redacted_args = List<String>(args);
  2201. redacted_args.find(keystore)->set("<REDACTED>");
  2202. redacted_args.find("pass:" + password)->set("pass:<REDACTED>");
  2203. redacted_args.find(user)->set("<REDACTED>");
  2204. print_line("Signing binary using: " + String("\n") + apksigner + " " + join_list(redacted_args, String(" ")));
  2205. }
  2206. int retval;
  2207. Error err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);
  2208. if (err != OK) {
  2209. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));
  2210. return err;
  2211. }
  2212. // By design, apksigner does not output credentials in its output unless --verbose is used
  2213. print_line(output);
  2214. if (retval) {
  2215. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("'apksigner' returned with error #%d"), retval));
  2216. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));
  2217. return ERR_CANT_CREATE;
  2218. }
  2219. if (ep.step(vformat(TTR("Verifying %s..."), export_label), 105)) {
  2220. return ERR_SKIP;
  2221. }
  2222. args.clear();
  2223. args.push_back("verify");
  2224. args.push_back("--verbose");
  2225. args.push_back(export_path);
  2226. if (p_debug) {
  2227. print_verbose("Verifying signed build using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));
  2228. }
  2229. output.clear();
  2230. err = OS::get_singleton()->execute(apksigner, args, &output, &retval, true);
  2231. if (err != OK) {
  2232. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), TTR("Could not start apksigner executable."));
  2233. return err;
  2234. }
  2235. print_verbose(output);
  2236. if (retval) {
  2237. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("'apksigner' verification of %s failed."), export_label));
  2238. add_message(EXPORT_MESSAGE_WARNING, TTR("Code Signing"), vformat(TTR("output: \n%s"), output));
  2239. return ERR_CANT_CREATE;
  2240. }
  2241. print_verbose("Successfully completed signing build.");
  2242. return OK;
  2243. }
  2244. void EditorExportPlatformAndroid::_clear_assets_directory() {
  2245. Ref<DirAccess> da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  2246. // Clear the APK assets directory
  2247. if (da_res->dir_exists(APK_ASSETS_DIRECTORY)) {
  2248. print_verbose("Clearing APK assets directory...");
  2249. Ref<DirAccess> da_assets = DirAccess::open(APK_ASSETS_DIRECTORY);
  2250. da_assets->erase_contents_recursive();
  2251. da_res->remove(APK_ASSETS_DIRECTORY);
  2252. }
  2253. // Clear the AAB assets directory
  2254. if (da_res->dir_exists(AAB_ASSETS_DIRECTORY)) {
  2255. print_verbose("Clearing AAB assets directory...");
  2256. Ref<DirAccess> da_assets = DirAccess::open(AAB_ASSETS_DIRECTORY);
  2257. da_assets->erase_contents_recursive();
  2258. da_res->remove(AAB_ASSETS_DIRECTORY);
  2259. }
  2260. }
  2261. void EditorExportPlatformAndroid::_remove_copied_libs() {
  2262. print_verbose("Removing previously installed libraries...");
  2263. Error error;
  2264. String libs_json = FileAccess::get_file_as_string(GDEXTENSION_LIBS_PATH, &error);
  2265. if (error || libs_json.is_empty()) {
  2266. print_verbose("No previously installed libraries found");
  2267. return;
  2268. }
  2269. JSON json;
  2270. error = json.parse(libs_json);
  2271. ERR_FAIL_COND_MSG(error, "Error parsing \"" + libs_json + "\" on line " + itos(json.get_error_line()) + ": " + json.get_error_message());
  2272. Vector<String> libs = json.get_data();
  2273. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  2274. for (int i = 0; i < libs.size(); i++) {
  2275. print_verbose("Removing previously installed library " + libs[i]);
  2276. da->remove(libs[i]);
  2277. }
  2278. da->remove(GDEXTENSION_LIBS_PATH);
  2279. }
  2280. String EditorExportPlatformAndroid::join_list(const List<String> &p_parts, const String &p_separator) {
  2281. String ret;
  2282. for (int i = 0; i < p_parts.size(); ++i) {
  2283. if (i > 0) {
  2284. ret += p_separator;
  2285. }
  2286. ret += p_parts[i];
  2287. }
  2288. return ret;
  2289. }
  2290. String EditorExportPlatformAndroid::join_abis(const Vector<EditorExportPlatformAndroid::ABI> &p_parts, const String &p_separator, bool p_use_arch) {
  2291. String ret;
  2292. for (int i = 0; i < p_parts.size(); ++i) {
  2293. if (i > 0) {
  2294. ret += p_separator;
  2295. }
  2296. ret += (p_use_arch) ? p_parts[i].arch : p_parts[i].abi;
  2297. }
  2298. return ret;
  2299. }
  2300. Error EditorExportPlatformAndroid::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  2301. int export_format = int(p_preset->get("custom_build/export_format"));
  2302. bool should_sign = p_preset->get("package/signed");
  2303. return export_project_helper(p_preset, p_debug, p_path, export_format, should_sign, p_flags);
  2304. }
  2305. Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int export_format, bool should_sign, int p_flags) {
  2306. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  2307. String src_apk;
  2308. Error err;
  2309. EditorProgress ep("export", TTR("Exporting for Android"), 105, true);
  2310. bool use_custom_build = bool(p_preset->get("custom_build/use_custom_build"));
  2311. bool p_give_internet = p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG);
  2312. bool apk_expansion = p_preset->get("apk_expansion/enable");
  2313. Vector<ABI> enabled_abis = get_enabled_abis(p_preset);
  2314. print_verbose("Exporting for Android...");
  2315. print_verbose("- debug build: " + bool_to_string(p_debug));
  2316. print_verbose("- export path: " + p_path);
  2317. print_verbose("- export format: " + itos(export_format));
  2318. print_verbose("- sign build: " + bool_to_string(should_sign));
  2319. print_verbose("- custom build enabled: " + bool_to_string(use_custom_build));
  2320. print_verbose("- apk expansion enabled: " + bool_to_string(apk_expansion));
  2321. print_verbose("- enabled abis: " + join_abis(enabled_abis, ",", false));
  2322. print_verbose("- export filter: " + itos(p_preset->get_export_filter()));
  2323. print_verbose("- include filter: " + p_preset->get_include_filter());
  2324. print_verbose("- exclude filter: " + p_preset->get_exclude_filter());
  2325. Ref<Image> splash_image;
  2326. Ref<Image> splash_bg_color_image;
  2327. String processed_splash_config_xml = load_splash_refs(splash_image, splash_bg_color_image);
  2328. Ref<Image> main_image;
  2329. Ref<Image> foreground;
  2330. Ref<Image> background;
  2331. load_icon_refs(p_preset, main_image, foreground, background);
  2332. Vector<uint8_t> command_line_flags;
  2333. // Write command line flags into the command_line_flags variable.
  2334. get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);
  2335. if (export_format == EXPORT_FORMAT_AAB) {
  2336. if (!p_path.ends_with(".aab")) {
  2337. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android App Bundle requires the *.aab extension."));
  2338. return ERR_UNCONFIGURED;
  2339. }
  2340. if (apk_expansion) {
  2341. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("APK Expansion not compatible with Android App Bundle."));
  2342. return ERR_UNCONFIGURED;
  2343. }
  2344. }
  2345. if (export_format == EXPORT_FORMAT_APK && !p_path.ends_with(".apk")) {
  2346. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Invalid filename! Android APK requires the *.apk extension."));
  2347. return ERR_UNCONFIGURED;
  2348. }
  2349. if (export_format > EXPORT_FORMAT_AAB || export_format < EXPORT_FORMAT_APK) {
  2350. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unsupported export format!"));
  2351. return ERR_UNCONFIGURED;
  2352. }
  2353. if (use_custom_build) {
  2354. print_verbose("Starting custom build...");
  2355. //test that installed build version is alright
  2356. {
  2357. print_verbose("Checking build version...");
  2358. Ref<FileAccess> f = FileAccess::open("res://android/.build_version", FileAccess::READ);
  2359. if (f.is_null()) {
  2360. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu."));
  2361. return ERR_UNCONFIGURED;
  2362. }
  2363. String version = f->get_line().strip_edges();
  2364. print_verbose("- build version: " + version);
  2365. if (version != VERSION_FULL_CONFIG) {
  2366. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Android build version mismatch: Template installed: %s, Godot version: %s. Please reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG));
  2367. return ERR_UNCONFIGURED;
  2368. }
  2369. }
  2370. const String assets_directory = get_assets_directory(p_preset, export_format);
  2371. String sdk_path = EDITOR_GET("export/android/android_sdk_path");
  2372. ERR_FAIL_COND_V_MSG(sdk_path.is_empty(), ERR_UNCONFIGURED, "Android SDK path must be configured in Editor Settings at 'export/android/android_sdk_path'.");
  2373. print_verbose("Android sdk path: " + sdk_path);
  2374. // TODO: should we use "package/name" or "application/config/name"?
  2375. String project_name = get_project_name(p_preset->get("package/name"));
  2376. err = _create_project_name_strings_files(p_preset, project_name); //project name localization.
  2377. if (err != OK) {
  2378. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to overwrite res://android/build/res/*.xml files with project name."));
  2379. }
  2380. // Copies the project icon files into the appropriate Gradle project directory.
  2381. _copy_icons_to_gradle_project(p_preset, processed_splash_config_xml, splash_image, splash_bg_color_image, main_image, foreground, background);
  2382. // Write an AndroidManifest.xml file into the Gradle project directory.
  2383. _write_tmp_manifest(p_preset, p_give_internet, p_debug);
  2384. //stores all the project files inside the Gradle project directory. Also includes all ABIs
  2385. _clear_assets_directory();
  2386. _remove_copied_libs();
  2387. if (!apk_expansion) {
  2388. print_verbose("Exporting project files...");
  2389. CustomExportData user_data;
  2390. user_data.assets_directory = assets_directory;
  2391. user_data.debug = p_debug;
  2392. err = export_project_files(p_preset, p_debug, rename_and_store_file_in_gradle_project, &user_data, copy_gradle_so);
  2393. if (err != OK) {
  2394. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not export project files to gradle project."));
  2395. return err;
  2396. }
  2397. if (user_data.libs.size() > 0) {
  2398. Ref<FileAccess> fa = FileAccess::open(GDEXTENSION_LIBS_PATH, FileAccess::WRITE);
  2399. fa->store_string(JSON::stringify(user_data.libs, "\t"));
  2400. }
  2401. } else {
  2402. print_verbose("Saving apk expansion file...");
  2403. err = save_apk_expansion_file(p_preset, p_debug, p_path);
  2404. if (err != OK) {
  2405. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));
  2406. return err;
  2407. }
  2408. }
  2409. print_verbose("Storing command line flags...");
  2410. store_file_at_path(assets_directory + "/_cl_", command_line_flags);
  2411. print_verbose("Updating ANDROID_HOME environment to " + sdk_path);
  2412. OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
  2413. String build_command;
  2414. #ifdef WINDOWS_ENABLED
  2415. build_command = "gradlew.bat";
  2416. #else
  2417. build_command = "gradlew";
  2418. #endif
  2419. String build_path = ProjectSettings::get_singleton()->get_resource_path().path_join("android/build");
  2420. build_command = build_path.path_join(build_command);
  2421. String package_name = get_package_name(p_preset->get("package/unique_name"));
  2422. String version_code = itos(p_preset->get("version/code"));
  2423. String version_name = p_preset->get("version/name");
  2424. String min_sdk_version = p_preset->get("custom_build/min_sdk");
  2425. if (!min_sdk_version.is_valid_int()) {
  2426. min_sdk_version = itos(DEFAULT_MIN_SDK_VERSION);
  2427. }
  2428. String target_sdk_version = p_preset->get("custom_build/target_sdk");
  2429. if (!target_sdk_version.is_valid_int()) {
  2430. target_sdk_version = itos(DEFAULT_TARGET_SDK_VERSION);
  2431. }
  2432. String enabled_abi_string = join_abis(enabled_abis, "|", false);
  2433. String sign_flag = should_sign ? "true" : "false";
  2434. String zipalign_flag = "true";
  2435. Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);
  2436. String local_plugins_binaries = PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_LOCAL, enabled_plugins);
  2437. String remote_plugins_binaries = PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_REMOTE, enabled_plugins);
  2438. String custom_maven_repos = PluginConfigAndroid::get_plugins_custom_maven_repos(enabled_plugins);
  2439. bool clean_build_required = is_clean_build_required(enabled_plugins);
  2440. List<String> cmdline;
  2441. if (clean_build_required) {
  2442. cmdline.push_back("clean");
  2443. }
  2444. String build_type = p_debug ? "Debug" : "Release";
  2445. if (export_format == EXPORT_FORMAT_AAB) {
  2446. String bundle_build_command = vformat("bundle%s", build_type);
  2447. cmdline.push_back(bundle_build_command);
  2448. } else if (export_format == EXPORT_FORMAT_APK) {
  2449. String apk_build_command = vformat("assemble%s", build_type);
  2450. cmdline.push_back(apk_build_command);
  2451. }
  2452. cmdline.push_back("-p"); // argument to specify the start directory.
  2453. cmdline.push_back(build_path); // start directory.
  2454. cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.
  2455. cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code.
  2456. cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name.
  2457. cmdline.push_back("-Pexport_version_min_sdk=" + min_sdk_version); // argument to specify the min sdk.
  2458. cmdline.push_back("-Pexport_version_target_sdk=" + target_sdk_version); // argument to specify the target sdk.
  2459. cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs.
  2460. cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies.
  2461. cmdline.push_back("-Pplugins_remote_binaries=" + remote_plugins_binaries); // argument to specify the list of plugins remote dependencies.
  2462. cmdline.push_back("-Pplugins_maven_repos=" + custom_maven_repos); // argument to specify the list of custom maven repos for the plugins dependencies.
  2463. cmdline.push_back("-Pperform_zipalign=" + zipalign_flag); // argument to specify whether the build should be zipaligned.
  2464. cmdline.push_back("-Pperform_signing=" + sign_flag); // argument to specify whether the build should be signed.
  2465. cmdline.push_back("-Pgodot_editor_version=" + String(VERSION_FULL_CONFIG));
  2466. // NOTE: The release keystore is not included in the verbose logging
  2467. // to avoid accidentally leaking sensitive information when sharing verbose logs for troubleshooting.
  2468. // Any non-sensitive additions to the command line arguments must be done above this section.
  2469. // Sensitive additions must be done below the logging statement.
  2470. print_verbose("Build Android project using gradle command: " + String("\n") + build_command + " " + join_list(cmdline, String(" ")));
  2471. if (should_sign) {
  2472. if (p_debug) {
  2473. String debug_keystore = p_preset->get("keystore/debug");
  2474. String debug_password = p_preset->get("keystore/debug_password");
  2475. String debug_user = p_preset->get("keystore/debug_user");
  2476. if (debug_keystore.is_empty()) {
  2477. debug_keystore = EDITOR_GET("export/android/debug_keystore");
  2478. debug_password = EDITOR_GET("export/android/debug_keystore_pass");
  2479. debug_user = EDITOR_GET("export/android/debug_keystore_user");
  2480. }
  2481. if (debug_keystore.is_relative_path()) {
  2482. debug_keystore = OS::get_singleton()->get_resource_dir().path_join(debug_keystore).simplify_path();
  2483. }
  2484. if (!FileAccess::exists(debug_keystore)) {
  2485. add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find keystore, unable to export."));
  2486. return ERR_FILE_CANT_OPEN;
  2487. }
  2488. cmdline.push_back("-Pdebug_keystore_file=" + debug_keystore); // argument to specify the debug keystore file.
  2489. cmdline.push_back("-Pdebug_keystore_alias=" + debug_user); // argument to specify the debug keystore alias.
  2490. cmdline.push_back("-Pdebug_keystore_password=" + debug_password); // argument to specify the debug keystore password.
  2491. } else {
  2492. // Pass the release keystore info as well
  2493. String release_keystore = p_preset->get("keystore/release");
  2494. String release_username = p_preset->get("keystore/release_user");
  2495. String release_password = p_preset->get("keystore/release_password");
  2496. if (release_keystore.is_relative_path()) {
  2497. release_keystore = OS::get_singleton()->get_resource_dir().path_join(release_keystore).simplify_path();
  2498. }
  2499. if (!FileAccess::exists(release_keystore)) {
  2500. add_message(EXPORT_MESSAGE_ERROR, TTR("Code Signing"), TTR("Could not find keystore, unable to export."));
  2501. return ERR_FILE_CANT_OPEN;
  2502. }
  2503. cmdline.push_back("-Prelease_keystore_file=" + release_keystore); // argument to specify the release keystore file.
  2504. cmdline.push_back("-Prelease_keystore_alias=" + release_username); // argument to specify the release keystore alias.
  2505. cmdline.push_back("-Prelease_keystore_password=" + release_password); // argument to specify the release keystore password.
  2506. }
  2507. }
  2508. int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
  2509. if (result != 0) {
  2510. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Building of Android project failed, check output for the error. Alternatively visit docs.godotengine.org for Android build documentation."));
  2511. return ERR_CANT_CREATE;
  2512. }
  2513. List<String> copy_args;
  2514. String copy_command;
  2515. if (export_format == EXPORT_FORMAT_AAB) {
  2516. copy_command = vformat("copyAndRename%sAab", build_type);
  2517. } else if (export_format == EXPORT_FORMAT_APK) {
  2518. copy_command = vformat("copyAndRename%sApk", build_type);
  2519. }
  2520. copy_args.push_back(copy_command);
  2521. copy_args.push_back("-p"); // argument to specify the start directory.
  2522. copy_args.push_back(build_path); // start directory.
  2523. String export_filename = p_path.get_file();
  2524. String export_path = p_path.get_base_dir();
  2525. if (export_path.is_relative_path()) {
  2526. export_path = OS::get_singleton()->get_resource_dir().path_join(export_path);
  2527. }
  2528. export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path();
  2529. copy_args.push_back("-Pexport_path=file:" + export_path);
  2530. copy_args.push_back("-Pexport_filename=" + export_filename);
  2531. print_verbose("Copying Android binary using gradle command: " + String("\n") + build_command + " " + join_list(copy_args, String(" ")));
  2532. int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args);
  2533. if (copy_result != 0) {
  2534. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Unable to copy and rename export file, check gradle project directory for outputs."));
  2535. return ERR_CANT_CREATE;
  2536. }
  2537. print_verbose("Successfully completed Android custom build.");
  2538. return OK;
  2539. }
  2540. // This is the start of the Legacy build system
  2541. print_verbose("Starting legacy build system...");
  2542. if (p_debug) {
  2543. src_apk = p_preset->get("custom_template/debug");
  2544. } else {
  2545. src_apk = p_preset->get("custom_template/release");
  2546. }
  2547. src_apk = src_apk.strip_edges();
  2548. if (src_apk.is_empty()) {
  2549. if (p_debug) {
  2550. src_apk = find_export_template("android_debug.apk");
  2551. } else {
  2552. src_apk = find_export_template("android_release.apk");
  2553. }
  2554. if (src_apk.is_empty()) {
  2555. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Package not found: \"%s\"."), src_apk));
  2556. return ERR_FILE_NOT_FOUND;
  2557. }
  2558. }
  2559. if (!DirAccess::exists(p_path.get_base_dir())) {
  2560. return ERR_FILE_BAD_PATH;
  2561. }
  2562. Ref<FileAccess> io_fa;
  2563. zlib_filefunc_def io = zipio_create_io(&io_fa);
  2564. if (ep.step(TTR("Creating APK..."), 0)) {
  2565. return ERR_SKIP;
  2566. }
  2567. unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
  2568. if (!pkg) {
  2569. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not find template APK to export: \"%s\"."), src_apk));
  2570. return ERR_FILE_NOT_FOUND;
  2571. }
  2572. int ret = unzGoToFirstFile(pkg);
  2573. Ref<FileAccess> io2_fa;
  2574. zlib_filefunc_def io2 = zipio_create_io(&io2_fa);
  2575. String tmp_unaligned_path = EditorPaths::get_singleton()->get_cache_dir().path_join("tmpexport-unaligned." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");
  2576. #define CLEANUP_AND_RETURN(m_err) \
  2577. { \
  2578. DirAccess::remove_file_or_error(tmp_unaligned_path); \
  2579. return m_err; \
  2580. } \
  2581. ((void)0)
  2582. zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);
  2583. String cmdline = p_preset->get("command_line/extra_args");
  2584. String version_name = p_preset->get("version/name");
  2585. String package_name = p_preset->get("package/unique_name");
  2586. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  2587. Vector<ABI> invalid_abis(enabled_abis);
  2588. while (ret == UNZ_OK) {
  2589. //get filename
  2590. unz_file_info info;
  2591. char fname[16384];
  2592. ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  2593. if (ret != UNZ_OK) {
  2594. break;
  2595. }
  2596. bool skip = false;
  2597. String file = String::utf8(fname);
  2598. Vector<uint8_t> data;
  2599. data.resize(info.uncompressed_size);
  2600. //read
  2601. unzOpenCurrentFile(pkg);
  2602. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  2603. unzCloseCurrentFile(pkg);
  2604. //write
  2605. if (file == "AndroidManifest.xml") {
  2606. _fix_manifest(p_preset, data, p_give_internet);
  2607. }
  2608. if (file == "resources.arsc") {
  2609. _fix_resources(p_preset, data);
  2610. }
  2611. // Process the splash image
  2612. if ((file == SPLASH_IMAGE_EXPORT_PATH || file == LEGACY_BUILD_SPLASH_IMAGE_EXPORT_PATH) && splash_image.is_valid() && !splash_image->is_empty()) {
  2613. _load_image_data(splash_image, data);
  2614. }
  2615. // Process the splash bg color image
  2616. if ((file == SPLASH_BG_COLOR_PATH || file == LEGACY_BUILD_SPLASH_BG_COLOR_PATH) && splash_bg_color_image.is_valid() && !splash_bg_color_image->is_empty()) {
  2617. _load_image_data(splash_bg_color_image, data);
  2618. }
  2619. if (file.ends_with(".png") && file.contains("mipmap")) {
  2620. for (int i = 0; i < icon_densities_count; ++i) {
  2621. if (main_image.is_valid() && !main_image->is_empty()) {
  2622. if (file == launcher_icons[i].export_path) {
  2623. _process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data);
  2624. }
  2625. }
  2626. if (foreground.is_valid() && !foreground->is_empty()) {
  2627. if (file == launcher_adaptive_icon_foregrounds[i].export_path) {
  2628. _process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data);
  2629. }
  2630. }
  2631. if (background.is_valid() && !background->is_empty()) {
  2632. if (file == launcher_adaptive_icon_backgrounds[i].export_path) {
  2633. _process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data);
  2634. }
  2635. }
  2636. }
  2637. }
  2638. if (file.ends_with(".so")) {
  2639. bool enabled = false;
  2640. for (int i = 0; i < enabled_abis.size(); ++i) {
  2641. if (file.begins_with("lib/" + enabled_abis[i].abi + "/")) {
  2642. invalid_abis.erase(enabled_abis[i]);
  2643. enabled = true;
  2644. break;
  2645. }
  2646. }
  2647. if (!enabled) {
  2648. skip = true;
  2649. }
  2650. }
  2651. if (file.begins_with("META-INF") && should_sign) {
  2652. skip = true;
  2653. }
  2654. if (!skip) {
  2655. print_line("ADDING: " + file);
  2656. // Respect decision on compression made by AAPT for the export template
  2657. const bool uncompressed = info.compression_method == 0;
  2658. zip_fileinfo zipfi = get_zip_fileinfo();
  2659. zipOpenNewFileInZip(unaligned_apk,
  2660. file.utf8().get_data(),
  2661. &zipfi,
  2662. nullptr,
  2663. 0,
  2664. nullptr,
  2665. 0,
  2666. nullptr,
  2667. uncompressed ? 0 : Z_DEFLATED,
  2668. Z_DEFAULT_COMPRESSION);
  2669. zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
  2670. zipCloseFileInZip(unaligned_apk);
  2671. }
  2672. ret = unzGoToNextFile(pkg);
  2673. }
  2674. if (!invalid_abis.is_empty()) {
  2675. add_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)));
  2676. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2677. }
  2678. if (ep.step(TTR("Adding files..."), 1)) {
  2679. CLEANUP_AND_RETURN(ERR_SKIP);
  2680. }
  2681. err = OK;
  2682. if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
  2683. APKExportData ed;
  2684. ed.ep = &ep;
  2685. ed.apk = unaligned_apk;
  2686. err = export_project_files(p_preset, p_debug, ignore_apk_file, &ed, save_apk_so);
  2687. } else {
  2688. if (apk_expansion) {
  2689. err = save_apk_expansion_file(p_preset, p_debug, p_path);
  2690. if (err != OK) {
  2691. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), TTR("Could not write expansion package file!"));
  2692. return err;
  2693. }
  2694. } else {
  2695. APKExportData ed;
  2696. ed.ep = &ep;
  2697. ed.apk = unaligned_apk;
  2698. err = export_project_files(p_preset, p_debug, save_apk_file, &ed, save_apk_so);
  2699. }
  2700. }
  2701. if (err != OK) {
  2702. unzClose(pkg);
  2703. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not export project files.")));
  2704. CLEANUP_AND_RETURN(ERR_SKIP);
  2705. }
  2706. zip_fileinfo zipfi = get_zip_fileinfo();
  2707. zipOpenNewFileInZip(unaligned_apk,
  2708. "assets/_cl_",
  2709. &zipfi,
  2710. nullptr,
  2711. 0,
  2712. nullptr,
  2713. 0,
  2714. nullptr,
  2715. 0, // No compress (little size gain and potentially slower startup)
  2716. Z_DEFAULT_COMPRESSION);
  2717. zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());
  2718. zipCloseFileInZip(unaligned_apk);
  2719. zipClose(unaligned_apk, nullptr);
  2720. unzClose(pkg);
  2721. if (err != OK) {
  2722. CLEANUP_AND_RETURN(err);
  2723. }
  2724. // Let's zip-align (must be done before signing)
  2725. static const int ZIP_ALIGNMENT = 4;
  2726. // If we're not signing the apk, then the next step should be the last.
  2727. const int next_step = should_sign ? 103 : 105;
  2728. if (ep.step(TTR("Aligning APK..."), next_step)) {
  2729. CLEANUP_AND_RETURN(ERR_SKIP);
  2730. }
  2731. unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);
  2732. if (!tmp_unaligned) {
  2733. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not unzip temporary unaligned APK.")));
  2734. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2735. }
  2736. ret = unzGoToFirstFile(tmp_unaligned);
  2737. io2 = zipio_create_io(&io2_fa);
  2738. zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);
  2739. // Take files from the unaligned APK and write them out to the aligned one
  2740. // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
  2741. // following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
  2742. int bias = 0;
  2743. while (ret == UNZ_OK) {
  2744. unz_file_info info;
  2745. memset(&info, 0, sizeof(info));
  2746. char fname[16384];
  2747. char extra[16384];
  2748. ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0);
  2749. if (ret != UNZ_OK) {
  2750. break;
  2751. }
  2752. String file = String::utf8(fname);
  2753. Vector<uint8_t> data;
  2754. data.resize(info.compressed_size);
  2755. // read
  2756. int method, level;
  2757. unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
  2758. long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
  2759. unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
  2760. unzCloseCurrentFile(tmp_unaligned);
  2761. // align
  2762. int padding = 0;
  2763. if (!info.compression_method) {
  2764. // Uncompressed file => Align
  2765. long new_offset = file_offset + bias;
  2766. padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
  2767. }
  2768. memset(extra + info.size_file_extra, 0, padding);
  2769. zip_fileinfo fileinfo = get_zip_fileinfo();
  2770. zipOpenNewFileInZip2(final_apk,
  2771. file.utf8().get_data(),
  2772. &fileinfo,
  2773. extra,
  2774. info.size_file_extra + padding,
  2775. nullptr,
  2776. 0,
  2777. nullptr,
  2778. method,
  2779. level,
  2780. 1); // raw write
  2781. zipWriteInFileInZip(final_apk, data.ptr(), data.size());
  2782. zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);
  2783. bias += padding;
  2784. ret = unzGoToNextFile(tmp_unaligned);
  2785. }
  2786. zipClose(final_apk, nullptr);
  2787. unzClose(tmp_unaligned);
  2788. if (should_sign) {
  2789. // Signing must be done last as any additional modifications to the
  2790. // file will invalidate the signature.
  2791. err = sign_apk(p_preset, p_debug, p_path, ep);
  2792. if (err != OK) {
  2793. CLEANUP_AND_RETURN(err);
  2794. }
  2795. }
  2796. CLEANUP_AND_RETURN(OK);
  2797. }
  2798. void EditorExportPlatformAndroid::get_platform_features(List<String> *r_features) const {
  2799. r_features->push_back("mobile");
  2800. r_features->push_back("android");
  2801. }
  2802. void EditorExportPlatformAndroid::resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, HashSet<String> &p_features) {
  2803. }
  2804. EditorExportPlatformAndroid::EditorExportPlatformAndroid() {
  2805. #ifdef MODULE_SVG_ENABLED
  2806. Ref<Image> img = memnew(Image);
  2807. const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE);
  2808. ImageLoaderSVG img_loader;
  2809. img_loader.create_image_from_string(img, _android_logo_svg, EDSCALE, upsample, false);
  2810. logo = ImageTexture::create_from_image(img);
  2811. img_loader.create_image_from_string(img, _android_run_icon_svg, EDSCALE, upsample, false);
  2812. run_icon = ImageTexture::create_from_image(img);
  2813. #endif
  2814. devices_changed.set();
  2815. plugins_changed.set();
  2816. #ifndef ANDROID_ENABLED
  2817. check_for_changes_thread.start(_check_for_changes_poll_thread, this);
  2818. #endif
  2819. }
  2820. EditorExportPlatformAndroid::~EditorExportPlatformAndroid() {
  2821. #ifndef ANDROID_ENABLED
  2822. quit_request.set();
  2823. check_for_changes_thread.wait_to_finish();
  2824. #endif
  2825. }