export_plugin.cpp 125 KB

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