export_plugin.cpp 121 KB

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