export_plugin.cpp 124 KB

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