export_plugin.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382
  1. /*************************************************************************/
  2. /* export_plugin.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 = "launcher_icons/main_192x192";
  187. static const char *launcher_adaptive_icon_foreground_option = "launcher_icons/adaptive_foreground_432x432";
  188. static const char *launcher_adaptive_icon_background_option = "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 = OS::get_singleton()->get_power_state() == OS::POWERSTATE_ON_BATTERY ? 1000 : 100;
  345. uint64_t wait = 3000000;
  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(1000 * 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 not benefit in doing so,
  461. * a performance gain is expected attime. 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_instrumentation_tag(p_preset);
  708. manifest_text += _get_application_tag(p_preset, _has_storage_permission(perms));
  709. manifest_text += "</manifest>\n";
  710. String manifest_path = vformat("res://android/build/src/%s/AndroidManifest.xml", (p_debug ? "debug" : "release"));
  711. print_verbose("Storing manifest into " + manifest_path + ": " + "\n" + manifest_text);
  712. store_string_at_path(manifest_path, manifest_text);
  713. }
  714. void EditorExportPlatformAndroid::_fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {
  715. // Leaving the unused types commented because looking these constants up
  716. // again later would be annoying
  717. // const int CHUNK_AXML_FILE = 0x00080003;
  718. // const int CHUNK_RESOURCEIDS = 0x00080180;
  719. const int CHUNK_STRINGS = 0x001C0001;
  720. // const int CHUNK_XML_END_NAMESPACE = 0x00100101;
  721. const int CHUNK_XML_END_TAG = 0x00100103;
  722. // const int CHUNK_XML_START_NAMESPACE = 0x00100100;
  723. const int CHUNK_XML_START_TAG = 0x00100102;
  724. // const int CHUNK_XML_TEXT = 0x00100104;
  725. const int UTF8_FLAG = 0x00000100;
  726. Vector<String> string_table;
  727. uint32_t ofs = 8;
  728. uint32_t string_count = 0;
  729. //uint32_t styles_count = 0;
  730. uint32_t string_flags = 0;
  731. uint32_t string_data_offset = 0;
  732. //uint32_t styles_offset = 0;
  733. uint32_t string_table_begins = 0;
  734. uint32_t string_table_ends = 0;
  735. Vector<uint8_t> stable_extra;
  736. String version_name = p_preset->get("version/name");
  737. int version_code = p_preset->get("version/code");
  738. String package_name = p_preset->get("package/unique_name");
  739. const int screen_orientation = _get_android_orientation_value(
  740. OS::get_singleton()->get_screen_orientation_from_string(GLOBAL_GET("display/window/handheld/orientation")));
  741. bool min_gles3 = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name") == "GLES3" &&
  742. !ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2");
  743. bool screen_support_small = p_preset->get("screen/support_small");
  744. bool screen_support_normal = p_preset->get("screen/support_normal");
  745. bool screen_support_large = p_preset->get("screen/support_large");
  746. bool screen_support_xlarge = p_preset->get("screen/support_xlarge");
  747. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  748. int hand_tracking_index = p_preset->get("xr_features/hand_tracking");
  749. int hand_tracking_frequency_index = p_preset->get("xr_features/hand_tracking_frequency");
  750. bool backup_allowed = p_preset->get("user_data_backup/allow");
  751. bool classify_as_game = p_preset->get("package/classify_as_game");
  752. bool retain_data_on_uninstall = p_preset->get("package/retain_data_on_uninstall");
  753. bool exclude_from_recents = p_preset->get("package/exclude_from_recents");
  754. Vector<String> perms;
  755. // Write permissions into the perms variable.
  756. _get_permissions(p_preset, p_give_internet, perms);
  757. bool has_storage_permission = _has_storage_permission(perms);
  758. while (ofs < (uint32_t)p_manifest.size()) {
  759. uint32_t chunk = decode_uint32(&p_manifest[ofs]);
  760. uint32_t size = decode_uint32(&p_manifest[ofs + 4]);
  761. switch (chunk) {
  762. case CHUNK_STRINGS: {
  763. int iofs = ofs + 8;
  764. string_count = decode_uint32(&p_manifest[iofs]);
  765. // iofs + 4 is `styles_count`.
  766. string_flags = decode_uint32(&p_manifest[iofs + 8]);
  767. string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
  768. // iofs + 16 is `styles_offset`.
  769. uint32_t st_offset = iofs + 20;
  770. string_table.resize(string_count);
  771. uint32_t string_end = 0;
  772. string_table_begins = st_offset;
  773. for (uint32_t i = 0; i < string_count; i++) {
  774. uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
  775. string_at += st_offset + string_count * 4;
  776. ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table.");
  777. if (string_flags & UTF8_FLAG) {
  778. } else {
  779. uint32_t len = decode_uint16(&p_manifest[string_at]);
  780. Vector<CharType> ucstring;
  781. ucstring.resize(len + 1);
  782. for (uint32_t j = 0; j < len; j++) {
  783. uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
  784. ucstring.write[j] = c;
  785. }
  786. string_end = MAX(string_at + 2 + 2 * len, string_end);
  787. ucstring.write[len] = 0;
  788. string_table.write[i] = ucstring.ptr();
  789. }
  790. }
  791. for (uint32_t i = string_end; i < (ofs + size); i++) {
  792. stable_extra.push_back(p_manifest[i]);
  793. }
  794. string_table_ends = ofs + size;
  795. } break;
  796. case CHUNK_XML_START_TAG: {
  797. int iofs = ofs + 8;
  798. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  799. String tname = string_table[name];
  800. uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
  801. iofs += 28;
  802. for (uint32_t i = 0; i < attrcount; i++) {
  803. uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
  804. uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
  805. uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
  806. uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);
  807. const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid);
  808. String attrname = string_table[attr_name];
  809. const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : "";
  810. //replace project information
  811. if (tname == "manifest" && attrname == "package") {
  812. string_table.write[attr_value] = get_package_name(package_name);
  813. }
  814. if (tname == "manifest" && attrname == "versionCode") {
  815. encode_uint32(version_code, &p_manifest.write[iofs + 16]);
  816. }
  817. if (tname == "manifest" && attrname == "versionName") {
  818. if (attr_value == 0xFFFFFFFF) {
  819. WARN_PRINT("Version name in a resource, should be plain text");
  820. } else {
  821. string_table.write[attr_value] = version_name;
  822. }
  823. }
  824. if (tname == "application" && attrname == "requestLegacyExternalStorage") {
  825. encode_uint32(has_storage_permission ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  826. }
  827. if (tname == "application" && attrname == "allowBackup") {
  828. encode_uint32(backup_allowed, &p_manifest.write[iofs + 16]);
  829. }
  830. if (tname == "application" && attrname == "isGame") {
  831. encode_uint32(classify_as_game, &p_manifest.write[iofs + 16]);
  832. }
  833. if (tname == "application" && attrname == "hasFragileUserData") {
  834. encode_uint32(retain_data_on_uninstall, &p_manifest.write[iofs + 16]);
  835. }
  836. if (tname == "instrumentation" && attrname == "targetPackage") {
  837. string_table.write[attr_value] = get_package_name(package_name);
  838. }
  839. if (tname == "activity" && attrname == "screenOrientation") {
  840. encode_uint32(screen_orientation, &p_manifest.write[iofs + 16]);
  841. }
  842. if (tname == "activity" && attrname == "excludeFromRecents") {
  843. encode_uint32(exclude_from_recents, &p_manifest.write[iofs + 16]);
  844. }
  845. if (tname == "supports-screens") {
  846. if (attrname == "smallScreens") {
  847. encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  848. } else if (attrname == "normalScreens") {
  849. encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  850. } else if (attrname == "largeScreens") {
  851. encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  852. } else if (attrname == "xlargeScreens") {
  853. encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  854. }
  855. }
  856. if (tname == "uses-feature" && attrname == "glEsVersion") {
  857. encode_uint32(min_gles3 ? 0x00030000 : 0x00020000, &p_manifest.write[iofs + 16]);
  858. }
  859. if (tname == "meta-data" && attrname == "name" && value == "xr_mode_metadata_name") {
  860. // Update the meta-data 'android:name' attribute based on the selected XR mode.
  861. if (xr_mode_index == XR_MODE_OVR || xr_mode_index == XR_MODE_OPENXR) {
  862. string_table.write[attr_value] = "com.samsung.android.vr.application.mode";
  863. }
  864. }
  865. if (tname == "meta-data" && attrname == "value" && value == "xr_mode_metadata_value") {
  866. // Update the meta-data 'android:value' attribute based on the selected XR mode.
  867. if (xr_mode_index == XR_MODE_OVR || xr_mode_index == XR_MODE_OPENXR) {
  868. string_table.write[attr_value] = "vr_only";
  869. }
  870. }
  871. if (tname == "meta-data" && attrname == "name" && value == "xr_hand_tracking_metadata_name") {
  872. if ((xr_mode_index == XR_MODE_OVR || xr_mode_index == XR_MODE_OPENXR) && hand_tracking_index > XR_HAND_TRACKING_NONE) {
  873. string_table.write[attr_value] = "com.oculus.handtracking.frequency";
  874. }
  875. }
  876. if (tname == "meta-data" && attrname == "value" && value == "xr_hand_tracking_metadata_value") {
  877. if ((xr_mode_index == XR_MODE_OVR || xr_mode_index == XR_MODE_OPENXR) && hand_tracking_index > XR_HAND_TRACKING_NONE) {
  878. string_table.write[attr_value] = (hand_tracking_frequency_index == XR_HAND_TRACKING_FREQUENCY_LOW ? "LOW" : "HIGH");
  879. }
  880. }
  881. iofs += 20;
  882. }
  883. } break;
  884. case CHUNK_XML_END_TAG: {
  885. int iofs = ofs + 8;
  886. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  887. String tname = string_table[name];
  888. if (tname == "uses-feature") {
  889. Vector<String> feature_names;
  890. Vector<bool> feature_required_list;
  891. Vector<int> feature_versions;
  892. if (xr_mode_index == XR_MODE_OVR || xr_mode_index == XR_MODE_OPENXR) {
  893. // Set degrees of freedom
  894. feature_names.push_back("android.hardware.vr.headtracking");
  895. feature_required_list.push_back(true);
  896. feature_versions.push_back(1);
  897. // Check for hand tracking
  898. if (hand_tracking_index > XR_HAND_TRACKING_NONE) {
  899. feature_names.push_back("oculus.software.handtracking");
  900. feature_required_list.push_back(hand_tracking_index == XR_HAND_TRACKING_REQUIRED);
  901. feature_versions.push_back(-1); // no version attribute should be added.
  902. }
  903. if (xr_mode_index == XR_MODE_OPENXR) {
  904. // Check for passthrough
  905. int passthrough_mode = p_preset->get("xr_features/passthrough");
  906. if (passthrough_mode > XR_PASSTHROUGH_NONE) {
  907. feature_names.push_back("com.oculus.feature.PASSTHROUGH");
  908. feature_required_list.push_back(passthrough_mode == XR_PASSTHROUGH_REQUIRED);
  909. feature_versions.push_back(-1);
  910. }
  911. }
  912. }
  913. if (feature_names.size() > 0) {
  914. ofs += 24; // skip over end tag
  915. // save manifest ending so we can restore it
  916. Vector<uint8_t> manifest_end;
  917. uint32_t manifest_cur_size = p_manifest.size();
  918. manifest_end.resize(p_manifest.size() - ofs);
  919. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  920. int32_t attr_name_string = string_table.find("name");
  921. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  922. int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android");
  923. if (ns_android_string == -1) {
  924. string_table.push_back("http://schemas.android.com/apk/res/android");
  925. ns_android_string = string_table.size() - 1;
  926. }
  927. int32_t attr_uses_feature_string = string_table.find("uses-feature");
  928. if (attr_uses_feature_string == -1) {
  929. string_table.push_back("uses-feature");
  930. attr_uses_feature_string = string_table.size() - 1;
  931. }
  932. int32_t attr_required_string = string_table.find("required");
  933. if (attr_required_string == -1) {
  934. string_table.push_back("required");
  935. attr_required_string = string_table.size() - 1;
  936. }
  937. for (int i = 0; i < feature_names.size(); i++) {
  938. String feature_name = feature_names[i];
  939. bool feature_required = feature_required_list[i];
  940. int feature_version = feature_versions[i];
  941. bool has_version_attribute = feature_version != -1;
  942. print_line("Adding feature " + feature_name);
  943. int32_t feature_string = string_table.find(feature_name);
  944. if (feature_string == -1) {
  945. string_table.push_back(feature_name);
  946. feature_string = string_table.size() - 1;
  947. }
  948. String required_value_string = feature_required ? "true" : "false";
  949. int32_t required_value = string_table.find(required_value_string);
  950. if (required_value == -1) {
  951. string_table.push_back(required_value_string);
  952. required_value = string_table.size() - 1;
  953. }
  954. int32_t attr_version_string = -1;
  955. int32_t version_value = -1;
  956. int tag_size;
  957. int attr_count;
  958. if (has_version_attribute) {
  959. attr_version_string = string_table.find("version");
  960. if (attr_version_string == -1) {
  961. string_table.push_back("version");
  962. attr_version_string = string_table.size() - 1;
  963. }
  964. version_value = string_table.find(itos(feature_version));
  965. if (version_value == -1) {
  966. string_table.push_back(itos(feature_version));
  967. version_value = string_table.size() - 1;
  968. }
  969. tag_size = 96; // node and three attrs + end node
  970. attr_count = 3;
  971. } else {
  972. tag_size = 76; // node and two attrs + end node
  973. attr_count = 2;
  974. }
  975. manifest_cur_size += tag_size + 24;
  976. p_manifest.resize(manifest_cur_size);
  977. // start tag
  978. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  979. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  980. encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size
  981. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  982. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  983. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  984. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  985. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  986. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  987. encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs
  988. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  989. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  990. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  991. // android:name attribute
  992. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  993. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  994. encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value
  995. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  996. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  997. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  998. encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  999. // android:required attribute
  1000. encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns
  1001. encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name'
  1002. encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value
  1003. encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size
  1004. p_manifest.write[ofs + 70] = 0; // typedvalue_always0
  1005. p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)
  1006. encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference
  1007. ofs += 76;
  1008. if (has_version_attribute) {
  1009. // android:version attribute
  1010. encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns
  1011. encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name'
  1012. encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value
  1013. encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size
  1014. p_manifest.write[ofs + 14] = 0; // typedvalue_always0
  1015. p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string)
  1016. encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference
  1017. ofs += 20;
  1018. }
  1019. // end tag
  1020. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  1021. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1022. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  1023. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1024. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1025. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1026. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  1027. ofs += 24;
  1028. }
  1029. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  1030. ofs -= 24; // go back over back end
  1031. }
  1032. }
  1033. if (tname == "manifest") {
  1034. // save manifest ending so we can restore it
  1035. Vector<uint8_t> manifest_end;
  1036. uint32_t manifest_cur_size = p_manifest.size();
  1037. manifest_end.resize(p_manifest.size() - ofs);
  1038. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  1039. int32_t attr_name_string = string_table.find("name");
  1040. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  1041. int32_t ns_android_string = string_table.find("android");
  1042. ERR_FAIL_COND_MSG(ns_android_string == -1, "Template does not have 'android' namespace.");
  1043. int32_t attr_uses_permission_string = string_table.find("uses-permission");
  1044. if (attr_uses_permission_string == -1) {
  1045. string_table.push_back("uses-permission");
  1046. attr_uses_permission_string = string_table.size() - 1;
  1047. }
  1048. for (int i = 0; i < perms.size(); ++i) {
  1049. print_line("Adding permission " + perms[i]);
  1050. manifest_cur_size += 56 + 24; // node + end node
  1051. p_manifest.resize(manifest_cur_size);
  1052. // Add permission to the string pool
  1053. int32_t perm_string = string_table.find(perms[i]);
  1054. if (perm_string == -1) {
  1055. string_table.push_back(perms[i]);
  1056. perm_string = string_table.size() - 1;
  1057. }
  1058. // start tag
  1059. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  1060. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1061. encode_uint32(56, &p_manifest.write[ofs + 4]); // size
  1062. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1063. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1064. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1065. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1066. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  1067. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  1068. encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
  1069. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  1070. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  1071. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  1072. // attribute
  1073. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  1074. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  1075. encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
  1076. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  1077. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  1078. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  1079. encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  1080. ofs += 56;
  1081. // end tag
  1082. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  1083. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1084. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  1085. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1086. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1087. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1088. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1089. ofs += 24;
  1090. }
  1091. // copy footer back in
  1092. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  1093. }
  1094. } break;
  1095. }
  1096. ofs += size;
  1097. }
  1098. //create new andriodmanifest binary
  1099. Vector<uint8_t> ret;
  1100. ret.resize(string_table_begins + string_table.size() * 4);
  1101. for (uint32_t i = 0; i < string_table_begins; i++) {
  1102. ret.write[i] = p_manifest[i];
  1103. }
  1104. ofs = 0;
  1105. for (int i = 0; i < string_table.size(); i++) {
  1106. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1107. ofs += string_table[i].length() * 2 + 2 + 2;
  1108. }
  1109. ret.resize(ret.size() + ofs);
  1110. string_data_offset = ret.size() - ofs;
  1111. uint8_t *chars = &ret.write[string_data_offset];
  1112. for (int i = 0; i < string_table.size(); i++) {
  1113. String s = string_table[i];
  1114. encode_uint16(s.length(), chars);
  1115. chars += 2;
  1116. for (int j = 0; j < s.length(); j++) {
  1117. encode_uint16(s[j], chars);
  1118. chars += 2;
  1119. }
  1120. encode_uint16(0, chars);
  1121. chars += 2;
  1122. }
  1123. for (int i = 0; i < stable_extra.size(); i++) {
  1124. ret.push_back(stable_extra[i]);
  1125. }
  1126. //pad
  1127. while (ret.size() % 4) {
  1128. ret.push_back(0);
  1129. }
  1130. uint32_t new_stable_end = ret.size();
  1131. uint32_t extra = (p_manifest.size() - string_table_ends);
  1132. ret.resize(new_stable_end + extra);
  1133. for (uint32_t i = 0; i < extra; i++) {
  1134. ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
  1135. }
  1136. while (ret.size() % 4) {
  1137. ret.push_back(0);
  1138. }
  1139. encode_uint32(ret.size(), &ret.write[4]); //update new file size
  1140. encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
  1141. encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
  1142. encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset
  1143. p_manifest = ret;
  1144. }
  1145. String EditorExportPlatformAndroid::_parse_string(const uint8_t *p_bytes, bool p_utf8) {
  1146. uint32_t offset = 0;
  1147. uint32_t len = 0;
  1148. if (p_utf8) {
  1149. uint8_t byte = p_bytes[offset];
  1150. if (byte & 0x80) {
  1151. offset += 2;
  1152. } else {
  1153. offset += 1;
  1154. }
  1155. byte = p_bytes[offset];
  1156. offset++;
  1157. if (byte & 0x80) {
  1158. len = byte & 0x7F;
  1159. len = (len << 8) + p_bytes[offset];
  1160. offset++;
  1161. } else {
  1162. len = byte;
  1163. }
  1164. } else {
  1165. len = decode_uint16(&p_bytes[offset]);
  1166. offset += 2;
  1167. if (len & 0x8000) {
  1168. len &= 0x7FFF;
  1169. len = (len << 16) + decode_uint16(&p_bytes[offset]);
  1170. offset += 2;
  1171. }
  1172. }
  1173. if (p_utf8) {
  1174. Vector<uint8_t> str8;
  1175. str8.resize(len + 1);
  1176. for (uint32_t i = 0; i < len; i++) {
  1177. str8.write[i] = p_bytes[offset + i];
  1178. }
  1179. str8.write[len] = 0;
  1180. String str;
  1181. str.parse_utf8((const char *)str8.ptr());
  1182. return str;
  1183. } else {
  1184. String str;
  1185. for (uint32_t i = 0; i < len; i++) {
  1186. CharType c = decode_uint16(&p_bytes[offset + i * 2]);
  1187. if (c == 0) {
  1188. break;
  1189. }
  1190. str += String::chr(c);
  1191. }
  1192. return str;
  1193. }
  1194. }
  1195. void EditorExportPlatformAndroid::_fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &r_manifest) {
  1196. const int UTF8_FLAG = 0x00000100;
  1197. uint32_t string_block_len = decode_uint32(&r_manifest[16]);
  1198. uint32_t string_count = decode_uint32(&r_manifest[20]);
  1199. uint32_t string_flags = decode_uint32(&r_manifest[28]);
  1200. const uint32_t string_table_begins = 40;
  1201. Vector<String> string_table;
  1202. String package_name = p_preset->get("package/name");
  1203. for (uint32_t i = 0; i < string_count; i++) {
  1204. uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]);
  1205. offset += string_table_begins + string_count * 4;
  1206. String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG);
  1207. if (str.begins_with("godot-project-name")) {
  1208. if (str == "godot-project-name") {
  1209. //project name
  1210. str = get_project_name(package_name);
  1211. } else {
  1212. String lang = str.substr(str.find_last("-") + 1, str.length()).replace("-", "_");
  1213. String prop = "application/config/name_" + lang;
  1214. if (ProjectSettings::get_singleton()->has_setting(prop)) {
  1215. str = ProjectSettings::get_singleton()->get(prop);
  1216. } else {
  1217. str = get_project_name(package_name);
  1218. }
  1219. }
  1220. }
  1221. string_table.push_back(str);
  1222. }
  1223. //write a new string table, but use 16 bits
  1224. Vector<uint8_t> ret;
  1225. ret.resize(string_table_begins + string_table.size() * 4);
  1226. for (uint32_t i = 0; i < string_table_begins; i++) {
  1227. ret.write[i] = r_manifest[i];
  1228. }
  1229. int ofs = 0;
  1230. for (int i = 0; i < string_table.size(); i++) {
  1231. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1232. ofs += string_table[i].length() * 2 + 2 + 2;
  1233. }
  1234. ret.resize(ret.size() + ofs);
  1235. uint8_t *chars = &ret.write[ret.size() - ofs];
  1236. for (int i = 0; i < string_table.size(); i++) {
  1237. String s = string_table[i];
  1238. encode_uint16(s.length(), chars);
  1239. chars += 2;
  1240. for (int j = 0; j < s.length(); j++) {
  1241. encode_uint16(s[j], chars);
  1242. chars += 2;
  1243. }
  1244. encode_uint16(0, chars);
  1245. chars += 2;
  1246. }
  1247. //pad
  1248. while (ret.size() % 4) {
  1249. ret.push_back(0);
  1250. }
  1251. //change flags to not use utf8
  1252. encode_uint32(string_flags & ~0x100, &ret.write[28]);
  1253. //change length
  1254. encode_uint32(ret.size() - 12, &ret.write[16]);
  1255. //append the rest...
  1256. int rest_from = 12 + string_block_len;
  1257. int rest_to = ret.size();
  1258. int rest_len = (r_manifest.size() - rest_from);
  1259. ret.resize(ret.size() + (r_manifest.size() - rest_from));
  1260. for (int i = 0; i < rest_len; i++) {
  1261. ret.write[rest_to + i] = r_manifest[rest_from + i];
  1262. }
  1263. //finally update the size
  1264. encode_uint32(ret.size(), &ret.write[4]);
  1265. r_manifest = ret;
  1266. }
  1267. void EditorExportPlatformAndroid::_load_image_data(const Ref<Image> &p_splash_image, Vector<uint8_t> &p_data) {
  1268. PoolVector<uint8_t> png_buffer;
  1269. Error err = PNGDriverCommon::image_to_png(p_splash_image, png_buffer);
  1270. if (err == OK) {
  1271. p_data.resize(png_buffer.size());
  1272. memcpy(p_data.ptrw(), png_buffer.read().ptr(), p_data.size());
  1273. } else {
  1274. String err_str = String("Failed to convert splash image to png.");
  1275. WARN_PRINT(err_str.utf8().get_data());
  1276. }
  1277. }
  1278. void EditorExportPlatformAndroid::_process_launcher_icons(const String &p_file_name, const Ref<Image> &p_source_image, int dimension, Vector<uint8_t> &p_data) {
  1279. Ref<Image> working_image = p_source_image;
  1280. if (p_source_image->get_width() != dimension || p_source_image->get_height() != dimension) {
  1281. working_image = p_source_image->duplicate();
  1282. working_image->resize(dimension, dimension, Image::Interpolation::INTERPOLATE_LANCZOS);
  1283. }
  1284. PoolVector<uint8_t> png_buffer;
  1285. Error err = PNGDriverCommon::image_to_png(working_image, png_buffer);
  1286. if (err == OK) {
  1287. p_data.resize(png_buffer.size());
  1288. memcpy(p_data.ptrw(), png_buffer.read().ptr(), p_data.size());
  1289. } else {
  1290. String err_str = String("Failed to convert resized icon (") + p_file_name + ") to png.";
  1291. WARN_PRINT(err_str.utf8().get_data());
  1292. }
  1293. }
  1294. String EditorExportPlatformAndroid::load_splash_refs(Ref<Image> &splash_image, Ref<Image> &splash_bg_color_image) {
  1295. bool scale_splash = ProjectSettings::get_singleton()->get("application/boot_splash/fullsize");
  1296. bool apply_filter = ProjectSettings::get_singleton()->get("application/boot_splash/use_filter");
  1297. String project_splash_path = ProjectSettings::get_singleton()->get("application/boot_splash/image");
  1298. if (!project_splash_path.empty()) {
  1299. splash_image.instance();
  1300. print_verbose("Loading splash image: " + project_splash_path);
  1301. const Error err = ImageLoader::load_image(project_splash_path, splash_image);
  1302. if (err) {
  1303. if (OS::get_singleton()->is_stdout_verbose()) {
  1304. print_error("- unable to load splash image from " + project_splash_path + " (" + itos(err) + ")");
  1305. }
  1306. splash_image.unref();
  1307. }
  1308. }
  1309. if (splash_image.is_null()) {
  1310. // Use the default
  1311. print_verbose("Using default splash image.");
  1312. splash_image = Ref<Image>(memnew(Image(boot_splash_png)));
  1313. }
  1314. if (scale_splash) {
  1315. Size2 screen_size = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
  1316. int width, height;
  1317. if (screen_size.width > screen_size.height) {
  1318. // scale horizontally
  1319. height = screen_size.height;
  1320. width = splash_image->get_width() * screen_size.height / splash_image->get_height();
  1321. } else {
  1322. // scale vertically
  1323. width = screen_size.width;
  1324. height = splash_image->get_height() * screen_size.width / splash_image->get_width();
  1325. }
  1326. splash_image->resize(width, height);
  1327. }
  1328. // Setup the splash bg color
  1329. bool bg_color_valid;
  1330. Color bg_color = ProjectSettings::get_singleton()->get("application/boot_splash/bg_color", &bg_color_valid);
  1331. if (!bg_color_valid) {
  1332. bg_color = boot_splash_bg_color;
  1333. }
  1334. print_verbose("Creating splash background color image.");
  1335. splash_bg_color_image.instance();
  1336. splash_bg_color_image->create(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format());
  1337. splash_bg_color_image->fill(bg_color);
  1338. String processed_splash_config_xml = vformat(SPLASH_CONFIG_XML_CONTENT, bool_to_string(apply_filter));
  1339. return processed_splash_config_xml;
  1340. }
  1341. void EditorExportPlatformAndroid::load_icon_refs(const Ref<EditorExportPreset> &p_preset, Ref<Image> &icon, Ref<Image> &foreground, Ref<Image> &background) {
  1342. String project_icon_path = ProjectSettings::get_singleton()->get("application/config/icon");
  1343. icon.instance();
  1344. foreground.instance();
  1345. background.instance();
  1346. // Regular icon: user selection -> project icon -> default.
  1347. String path = static_cast<String>(p_preset->get(launcher_icon_option)).strip_edges();
  1348. print_verbose("Loading regular icon from " + path);
  1349. if (path.empty() || ImageLoader::load_image(path, icon) != OK) {
  1350. print_verbose("- falling back to project icon: " + project_icon_path);
  1351. ImageLoader::load_image(project_icon_path, icon);
  1352. }
  1353. // Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default).
  1354. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_foreground_option)).strip_edges();
  1355. print_verbose("Loading adaptive foreground icon from " + path);
  1356. if (path.empty() || ImageLoader::load_image(path, foreground) != OK) {
  1357. print_verbose("- falling back to using the regular icon");
  1358. foreground = icon;
  1359. }
  1360. // Adaptive background: user selection -> default.
  1361. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_background_option)).strip_edges();
  1362. if (!path.empty()) {
  1363. print_verbose("Loading adaptive background icon from " + path);
  1364. ImageLoader::load_image(path, background);
  1365. }
  1366. }
  1367. void EditorExportPlatformAndroid::store_image(const LauncherIcon launcher_icon, const Vector<uint8_t> &data) {
  1368. store_image(launcher_icon.export_path, data);
  1369. }
  1370. void EditorExportPlatformAndroid::store_image(const String &export_path, const Vector<uint8_t> &data) {
  1371. String img_path = export_path.insert(0, "res://android/build/");
  1372. store_file_at_path(img_path, data);
  1373. }
  1374. void EditorExportPlatformAndroid::_copy_icons_to_gradle_project(const Ref<EditorExportPreset> &p_preset,
  1375. const String &processed_splash_config_xml,
  1376. const Ref<Image> &splash_image,
  1377. const Ref<Image> &splash_bg_color_image,
  1378. const Ref<Image> &main_image,
  1379. const Ref<Image> &foreground,
  1380. const Ref<Image> &background) {
  1381. // Store the splash configuration
  1382. if (!processed_splash_config_xml.empty()) {
  1383. print_verbose("Storing processed splash configuration: " + String("\n") + processed_splash_config_xml);
  1384. store_string_at_path(SPLASH_CONFIG_PATH, processed_splash_config_xml);
  1385. }
  1386. // Store the splash image
  1387. if (splash_image.is_valid() && !splash_image->empty()) {
  1388. print_verbose("Storing splash image in " + String(SPLASH_IMAGE_EXPORT_PATH));
  1389. Vector<uint8_t> data;
  1390. _load_image_data(splash_image, data);
  1391. store_image(SPLASH_IMAGE_EXPORT_PATH, data);
  1392. }
  1393. // Store the splash bg color image
  1394. if (splash_bg_color_image.is_valid() && !splash_bg_color_image->empty()) {
  1395. print_verbose("Storing splash background image in " + String(SPLASH_BG_COLOR_PATH));
  1396. Vector<uint8_t> data;
  1397. _load_image_data(splash_bg_color_image, data);
  1398. store_image(SPLASH_BG_COLOR_PATH, data);
  1399. }
  1400. // Prepare images to be resized for the icons. If some image ends up being uninitialized,
  1401. // the default image from the export template will be used.
  1402. for (int i = 0; i < icon_densities_count; ++i) {
  1403. if (main_image.is_valid() && !main_image->empty()) {
  1404. print_verbose("Processing launcher icon for dimension " + itos(launcher_icons[i].dimensions) + " into " + launcher_icons[i].export_path);
  1405. Vector<uint8_t> data;
  1406. _process_launcher_icons(launcher_icons[i].export_path, main_image, launcher_icons[i].dimensions, data);
  1407. store_image(launcher_icons[i], data);
  1408. }
  1409. if (foreground.is_valid() && !foreground->empty()) {
  1410. print_verbose("Processing launcher adaptive icon foreground for dimension " + itos(launcher_adaptive_icon_foregrounds[i].dimensions) + " into " + launcher_adaptive_icon_foregrounds[i].export_path);
  1411. Vector<uint8_t> data;
  1412. _process_launcher_icons(launcher_adaptive_icon_foregrounds[i].export_path, foreground,
  1413. launcher_adaptive_icon_foregrounds[i].dimensions, data);
  1414. store_image(launcher_adaptive_icon_foregrounds[i], data);
  1415. }
  1416. if (background.is_valid() && !background->empty()) {
  1417. print_verbose("Processing launcher adaptive icon background for dimension " + itos(launcher_adaptive_icon_backgrounds[i].dimensions) + " into " + launcher_adaptive_icon_backgrounds[i].export_path);
  1418. Vector<uint8_t> data;
  1419. _process_launcher_icons(launcher_adaptive_icon_backgrounds[i].export_path, background,
  1420. launcher_adaptive_icon_backgrounds[i].dimensions, data);
  1421. store_image(launcher_adaptive_icon_backgrounds[i], data);
  1422. }
  1423. }
  1424. }
  1425. Vector<String> EditorExportPlatformAndroid::get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
  1426. Vector<String> abis = get_abis();
  1427. Vector<String> enabled_abis;
  1428. for (int i = 0; i < abis.size(); ++i) {
  1429. bool is_enabled = p_preset->get("architectures/" + abis[i]);
  1430. if (is_enabled) {
  1431. enabled_abis.push_back(abis[i]);
  1432. }
  1433. }
  1434. return enabled_abis;
  1435. }
  1436. void EditorExportPlatformAndroid::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  1437. String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
  1438. if (driver == "GLES2") {
  1439. r_features->push_back("etc");
  1440. } else if (driver == "GLES3") {
  1441. r_features->push_back("etc2");
  1442. if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
  1443. r_features->push_back("etc");
  1444. }
  1445. }
  1446. Vector<String> abis = get_enabled_abis(p_preset);
  1447. for (int i = 0; i < abis.size(); ++i) {
  1448. r_features->push_back(abis[i]);
  1449. }
  1450. }
  1451. void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_options) {
  1452. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1453. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1454. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_template/use_custom_build"), false));
  1455. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "custom_template/export_format", PROPERTY_HINT_ENUM, "Export APK,Export AAB"), EXPORT_FORMAT_APK));
  1456. Vector<PluginConfigAndroid> plugins_configs = get_plugins();
  1457. for (int i = 0; i < plugins_configs.size(); i++) {
  1458. print_verbose("Found Android plugin " + plugins_configs[i].name);
  1459. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "plugins/" + plugins_configs[i].name), false));
  1460. }
  1461. plugins_changed.clear();
  1462. Vector<String> abis = get_abis();
  1463. for (int i = 0; i < abis.size(); ++i) {
  1464. String abi = abis[i];
  1465. bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a");
  1466. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default));
  1467. }
  1468. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
  1469. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
  1470. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
  1471. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
  1472. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
  1473. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
  1474. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), false));
  1475. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
  1476. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
  1477. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/min_sdk", PROPERTY_HINT_RANGE, SDK_VERSION_RANGE), DEFAULT_MIN_SDK_VERSION));
  1478. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/target_sdk", PROPERTY_HINT_RANGE, SDK_VERSION_RANGE), DEFAULT_TARGET_SDK_VERSION));
  1479. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
  1480. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
  1481. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
  1482. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/classify_as_game"), true));
  1483. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/retain_data_on_uninstall"), false));
  1484. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/exclude_from_recents"), false));
  1485. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icon_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1486. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_foreground_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1487. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_background_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1488. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/opengl_debug"), false));
  1489. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,Oculus Mobile VrApi (Deprecated),OpenXR"), XR_MODE_REGULAR));
  1490. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking", PROPERTY_HINT_ENUM, "None,Optional,Required"), XR_HAND_TRACKING_NONE));
  1491. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking_frequency", PROPERTY_HINT_ENUM, "Low,High"), XR_HAND_TRACKING_FREQUENCY_LOW));
  1492. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/passthrough", PROPERTY_HINT_ENUM, "None,Optional,Required"), XR_PASSTHROUGH_NONE));
  1493. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
  1494. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
  1495. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
  1496. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
  1497. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
  1498. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data_backup/allow"), false));
  1499. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
  1500. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
  1501. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
  1502. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));
  1503. r_options->push_back(ExportOption(PropertyInfo(Variant::POOL_STRING_ARRAY, "permissions/custom_permissions"), PoolStringArray()));
  1504. const char **perms = android_perms;
  1505. while (*perms) {
  1506. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false));
  1507. perms++;
  1508. }
  1509. }
  1510. String EditorExportPlatformAndroid::get_name() const {
  1511. return "Android";
  1512. }
  1513. String EditorExportPlatformAndroid::get_os_name() const {
  1514. return "Android";
  1515. }
  1516. Ref<Texture> EditorExportPlatformAndroid::get_logo() const {
  1517. return logo;
  1518. }
  1519. bool EditorExportPlatformAndroid::should_update_export_options() {
  1520. bool export_options_changed = plugins_changed.is_set();
  1521. if (export_options_changed) {
  1522. // don't clear unless we're reporting true, to avoid race
  1523. plugins_changed.clear();
  1524. }
  1525. return export_options_changed;
  1526. }
  1527. bool EditorExportPlatformAndroid::poll_export() {
  1528. bool dc = devices_changed.is_set();
  1529. if (dc) {
  1530. // don't clear unless we're reporting true, to avoid race
  1531. devices_changed.clear();
  1532. }
  1533. return dc;
  1534. }
  1535. int EditorExportPlatformAndroid::get_options_count() const {
  1536. device_lock.lock();
  1537. int dc = devices.size();
  1538. device_lock.unlock();
  1539. return dc;
  1540. }
  1541. String EditorExportPlatformAndroid::get_options_tooltip() const {
  1542. return TTR("Select device from the list");
  1543. }
  1544. String EditorExportPlatformAndroid::get_option_label(int p_index) const {
  1545. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1546. device_lock.lock();
  1547. String s = devices[p_index].name;
  1548. device_lock.unlock();
  1549. return s;
  1550. }
  1551. String EditorExportPlatformAndroid::get_option_tooltip(int p_index) const {
  1552. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1553. device_lock.lock();
  1554. String s = devices[p_index].description;
  1555. if (devices.size() == 1) {
  1556. // Tooltip will be:
  1557. // Name
  1558. // Description
  1559. s = devices[p_index].name + "\n\n" + s;
  1560. }
  1561. device_lock.unlock();
  1562. return s;
  1563. }
  1564. Error EditorExportPlatformAndroid::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
  1565. ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
  1566. String can_export_error;
  1567. bool can_export_missing_templates;
  1568. if (!can_export(p_preset, can_export_error, can_export_missing_templates)) {
  1569. EditorNode::add_io_error(can_export_error);
  1570. return ERR_UNCONFIGURED;
  1571. }
  1572. device_lock.lock();
  1573. EditorProgress ep("run", vformat(TTR("Running on %s"), devices[p_device].name), 3);
  1574. String adb = get_adb_path();
  1575. // Export_temp APK.
  1576. if (ep.step(TTR("Exporting APK..."), 0)) {
  1577. device_lock.unlock();
  1578. return ERR_SKIP;
  1579. }
  1580. const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
  1581. const bool use_reverse = devices[p_device].api_level >= 21;
  1582. if (use_reverse) {
  1583. p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
  1584. }
  1585. String tmp_export_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");
  1586. #define CLEANUP_AND_RETURN(m_err) \
  1587. { \
  1588. DirAccess::remove_file_or_error(tmp_export_path); \
  1589. device_lock.unlock(); \
  1590. return m_err; \
  1591. }
  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. EditorNode::add_io_error(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. EditorNode::add_io_error(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. EditorNode::get_singleton()->show_warning(TTR("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).\n"
  1884. "Replace it with the first-party \"GodotGooglePlayBilling\" plugin.\n"
  1885. "Note that the singleton was also renamed from \"GodotPayments\" to \"GodotGooglePlayBilling\".");
  1886. err += "\n";
  1887. }
  1888. }
  1889. // Ensure that `Use Custom Build` is enabled if a plugin is selected.
  1890. String enabled_plugins_names = PluginConfigAndroid::get_plugins_names(get_enabled_plugins(p_preset));
  1891. if (!enabled_plugins_names.empty() && !custom_build_enabled) {
  1892. valid = false;
  1893. err += TTR("\"Use Custom Build\" must be enabled to use the plugins.");
  1894. err += "\n";
  1895. }
  1896. // Validate the Xr features are properly populated
  1897. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  1898. int hand_tracking = p_preset->get("xr_features/hand_tracking");
  1899. int passthrough_mode = p_preset->get("xr_features/passthrough");
  1900. if (xr_mode_index != XR_MODE_OVR && xr_mode_index != XR_MODE_OPENXR) {
  1901. if (hand_tracking > XR_HAND_TRACKING_NONE) {
  1902. valid = false;
  1903. err += TTR("\"Hand Tracking\" is only valid when \"Xr Mode\" is \"Oculus Mobile VrApi\" or \"OpenXR\".");
  1904. err += "\n";
  1905. }
  1906. }
  1907. if (xr_mode_index != XR_MODE_OPENXR) {
  1908. if (passthrough_mode > XR_PASSTHROUGH_NONE) {
  1909. valid = false;
  1910. err += TTR("\"Passthrough\" is only valid when \"Xr Mode\" is \"OpenXR\".");
  1911. err += "\n";
  1912. }
  1913. }
  1914. if (int(p_preset->get("custom_template/export_format")) == EXPORT_FORMAT_AAB &&
  1915. !custom_build_enabled) {
  1916. valid = false;
  1917. err += TTR("\"Export AAB\" is only valid when \"Use Custom Build\" is enabled.");
  1918. err += "\n";
  1919. }
  1920. // Check the min sdk version
  1921. int min_sdk_version = p_preset->get("version/min_sdk");
  1922. if (min_sdk_version != DEFAULT_MIN_SDK_VERSION && !custom_build_enabled) {
  1923. valid = false;
  1924. err += TTR("Changing the \"Min Sdk\" is only valid when \"Use Custom Build\" is enabled.");
  1925. err += "\n";
  1926. }
  1927. // Check the target sdk version
  1928. int target_sdk_version = p_preset->get("version/target_sdk");
  1929. if (target_sdk_version != DEFAULT_TARGET_SDK_VERSION && !custom_build_enabled) {
  1930. valid = false;
  1931. err += TTR("Changing the \"Target Sdk\" is only valid when \"Use Custom Build\" is enabled.");
  1932. err += "\n";
  1933. }
  1934. if (target_sdk_version < min_sdk_version) {
  1935. valid = false;
  1936. err += TTR("\"Target Sdk\" version must be greater or equal to \"Min Sdk\" version.");
  1937. err += "\n";
  1938. }
  1939. r_error = err;
  1940. return valid;
  1941. }
  1942. List<String> EditorExportPlatformAndroid::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  1943. List<String> list;
  1944. list.push_back("apk");
  1945. list.push_back("aab");
  1946. return list;
  1947. }
  1948. void EditorExportPlatformAndroid::_update_custom_build_project() {
  1949. print_verbose("Updating custom build project..");
  1950. DirAccessRef da = DirAccess::open("res://android");
  1951. ERR_FAIL_COND_MSG(!da, "Cannot open directory 'res://android'.");
  1952. Map<String, List<String>> directory_paths;
  1953. Map<String, List<String>> manifest_sections;
  1954. Map<String, List<String>> gradle_sections;
  1955. da->list_dir_begin();
  1956. String d = da->get_next();
  1957. while (d != String()) {
  1958. if (!d.begins_with(".") && d != "build" && da->current_is_dir()) { //a dir and not the build dir
  1959. //add directories found
  1960. DirAccessRef ds = DirAccess::open(String("res://android").plus_file(d));
  1961. if (ds) {
  1962. ds->list_dir_begin();
  1963. String sd = ds->get_next();
  1964. while (sd != String()) {
  1965. if (!sd.begins_with(".") && ds->current_is_dir()) {
  1966. String key = sd.to_upper();
  1967. if (!directory_paths.has(key)) {
  1968. directory_paths[key] = List<String>();
  1969. }
  1970. String path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android").plus_file(d).plus_file(sd);
  1971. directory_paths[key].push_back(path);
  1972. print_line("Add: " + sd + ":" + path);
  1973. }
  1974. sd = ds->get_next();
  1975. }
  1976. ds->list_dir_end();
  1977. }
  1978. //parse manifest
  1979. {
  1980. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("AndroidManifest.conf"), FileAccess::READ);
  1981. if (f) {
  1982. String section;
  1983. while (!f->eof_reached()) {
  1984. String l = f->get_line();
  1985. String k = l.strip_edges();
  1986. if (k.begins_with("[")) {
  1987. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  1988. print_line("Section: " + section);
  1989. } else if (k != String()) {
  1990. if (!manifest_sections.has(section)) {
  1991. manifest_sections[section] = List<String>();
  1992. }
  1993. manifest_sections[section].push_back(l);
  1994. }
  1995. }
  1996. f->close();
  1997. }
  1998. }
  1999. //parse gradle
  2000. {
  2001. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("gradle.conf"), FileAccess::READ);
  2002. if (f) {
  2003. String section;
  2004. while (!f->eof_reached()) {
  2005. String l = f->get_line().strip_edges();
  2006. String k = l.strip_edges();
  2007. if (k.begins_with("[")) {
  2008. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  2009. print_line("Section: " + section);
  2010. } else if (k != String()) {
  2011. if (!gradle_sections.has(section)) {
  2012. gradle_sections[section] = List<String>();
  2013. }
  2014. gradle_sections[section].push_back(l);
  2015. }
  2016. }
  2017. }
  2018. }
  2019. }
  2020. d = da->get_next();
  2021. }
  2022. da->list_dir_end();
  2023. { //fix gradle build
  2024. String new_file;
  2025. {
  2026. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::READ);
  2027. if (f) {
  2028. while (!f->eof_reached()) {
  2029. String l = f->get_line();
  2030. bool append_line = false;
  2031. if (l.begins_with("//CHUNK_")) {
  2032. String text = l.replace_first("//CHUNK_", "");
  2033. int begin_pos = text.find("_BEGIN");
  2034. if (begin_pos != -1) {
  2035. text = text.substr(0, begin_pos);
  2036. text = text.to_upper(); //just in case
  2037. String end_marker = "//CHUNK_" + text + "_END";
  2038. uint64_t pos = f->get_position();
  2039. bool found = false;
  2040. while (!f->eof_reached()) {
  2041. l = f->get_line();
  2042. if (l.begins_with(end_marker)) {
  2043. found = true;
  2044. break;
  2045. }
  2046. }
  2047. new_file += "//CHUNK_" + text + "_BEGIN\n";
  2048. if (!found) {
  2049. ERR_PRINT("No end marker found in build.gradle for chunk: " + text);
  2050. f->seek(pos);
  2051. } else {
  2052. //add chunk lines
  2053. if (gradle_sections.has(text)) {
  2054. for (List<String>::Element *E = gradle_sections[text].front(); E; E = E->next()) {
  2055. new_file += E->get() + "\n";
  2056. }
  2057. }
  2058. if (f->eof_reached()) {
  2059. new_file += end_marker;
  2060. } else {
  2061. new_file += end_marker + "\n";
  2062. }
  2063. }
  2064. } else {
  2065. append_line = true;
  2066. }
  2067. } else if (l.begins_with("//DIR_")) {
  2068. String text = l.replace_first("//DIR_", "");
  2069. int begin_pos = text.find("_BEGIN");
  2070. if (begin_pos != -1) {
  2071. text = text.substr(0, begin_pos);
  2072. text = text.to_upper(); //just in case
  2073. String end_marker = "//DIR_" + text + "_END";
  2074. uint64_t pos = f->get_position();
  2075. bool found = false;
  2076. while (!f->eof_reached()) {
  2077. l = f->get_line();
  2078. if (l.begins_with(end_marker)) {
  2079. found = true;
  2080. break;
  2081. }
  2082. }
  2083. new_file += "//DIR_" + text + "_BEGIN\n";
  2084. if (!found) {
  2085. ERR_PRINT("No end marker found in build.gradle for dir: " + text);
  2086. f->seek(pos);
  2087. } else {
  2088. //add chunk lines
  2089. if (directory_paths.has(text)) {
  2090. for (List<String>::Element *E = directory_paths[text].front(); E; E = E->next()) {
  2091. new_file += ",'" + E->get().replace("'", "\'") + "'";
  2092. new_file += "\n";
  2093. }
  2094. }
  2095. if (f->eof_reached()) {
  2096. new_file += end_marker;
  2097. } else {
  2098. new_file += end_marker + "\n";
  2099. }
  2100. }
  2101. } else {
  2102. append_line = true;
  2103. }
  2104. } else {
  2105. append_line = true;
  2106. }
  2107. if (append_line) {
  2108. if (f->eof_reached()) {
  2109. new_file += l;
  2110. } else {
  2111. new_file += l + "\n";
  2112. }
  2113. }
  2114. }
  2115. }
  2116. }
  2117. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::WRITE);
  2118. f->store_string(new_file);
  2119. f->close();
  2120. }
  2121. { //fix manifest
  2122. String new_file;
  2123. {
  2124. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::READ);
  2125. if (f) {
  2126. while (!f->eof_reached()) {
  2127. String l = f->get_line();
  2128. bool append_line = false;
  2129. if (l.begins_with("<!--CHUNK_")) {
  2130. String text = l.replace_first("<!--CHUNK_", "");
  2131. int begin_pos = text.find("_BEGIN-->");
  2132. if (begin_pos != -1) {
  2133. text = text.substr(0, begin_pos);
  2134. text = text.to_upper(); //just in case
  2135. String end_marker = "<!--CHUNK_" + text + "_END-->";
  2136. uint64_t pos = f->get_position();
  2137. bool found = false;
  2138. while (!f->eof_reached()) {
  2139. l = f->get_line();
  2140. if (l.begins_with(end_marker)) {
  2141. found = true;
  2142. break;
  2143. }
  2144. }
  2145. new_file += "<!--CHUNK_" + text + "_BEGIN-->\n";
  2146. if (!found) {
  2147. ERR_PRINT("No end marker found in AndroidManifest.xml for chunk: " + text);
  2148. f->seek(pos);
  2149. } else {
  2150. //add chunk lines
  2151. if (manifest_sections.has(text)) {
  2152. for (List<String>::Element *E = manifest_sections[text].front(); E; E = E->next()) {
  2153. new_file += E->get() + "\n";
  2154. }
  2155. }
  2156. if (f->eof_reached()) {
  2157. new_file += end_marker;
  2158. } else {
  2159. new_file += end_marker + "\n";
  2160. }
  2161. }
  2162. } else {
  2163. append_line = true;
  2164. }
  2165. } else if (l.strip_edges().begins_with("<application")) {
  2166. String last_tag = "android:icon=\"@mipmap/icon\"";
  2167. int last_tag_pos = l.find(last_tag);
  2168. if (last_tag_pos == -1) {
  2169. ERR_PRINT("Not adding application attributes as the expected tag was not found in '<application': " + last_tag);
  2170. append_line = true;
  2171. } else {
  2172. String base = l.substr(0, last_tag_pos + last_tag.length());
  2173. if (manifest_sections.has("application_attribs")) {
  2174. for (List<String>::Element *E = manifest_sections["application_attribs"].front(); E; E = E->next()) {
  2175. String to_add = E->get().strip_edges();
  2176. base += " " + to_add + " ";
  2177. }
  2178. }
  2179. base += ">\n";
  2180. new_file += base;
  2181. }
  2182. } else {
  2183. append_line = true;
  2184. }
  2185. if (append_line) {
  2186. new_file += l;
  2187. if (!f->eof_reached()) {
  2188. new_file += "\n";
  2189. }
  2190. }
  2191. }
  2192. }
  2193. }
  2194. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::WRITE);
  2195. f->store_string(new_file);
  2196. f->close();
  2197. }
  2198. }
  2199. String EditorExportPlatformAndroid::get_apk_expansion_fullpath(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
  2200. int version_code = p_preset->get("version/code");
  2201. String package_name = p_preset->get("package/unique_name");
  2202. String apk_file_name = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
  2203. String fullpath = p_path.get_base_dir().plus_file(apk_file_name);
  2204. return fullpath;
  2205. }
  2206. Error EditorExportPlatformAndroid::save_apk_expansion_file(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
  2207. String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
  2208. Error err = save_pack(p_preset, fullpath);
  2209. return err;
  2210. }
  2211. 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) {
  2212. String cmdline = p_preset->get("command_line/extra_args");
  2213. Vector<String> command_line_strings = cmdline.strip_edges().split(" ");
  2214. for (int i = 0; i < command_line_strings.size(); i++) {
  2215. if (command_line_strings[i].strip_edges().length() == 0) {
  2216. command_line_strings.remove(i);
  2217. i--;
  2218. }
  2219. }
  2220. gen_export_flags(command_line_strings, p_flags);
  2221. bool apk_expansion = p_preset->get("apk_expansion/enable");
  2222. if (apk_expansion) {
  2223. String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
  2224. String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");
  2225. command_line_strings.push_back("--use_apk_expansion");
  2226. command_line_strings.push_back("--apk_expansion_md5");
  2227. command_line_strings.push_back(FileAccess::get_md5(fullpath));
  2228. command_line_strings.push_back("--apk_expansion_key");
  2229. command_line_strings.push_back(apk_expansion_public_key.strip_edges());
  2230. }
  2231. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  2232. if (xr_mode_index == XR_MODE_OVR) {
  2233. command_line_strings.push_back("--xr_mode_ovr");
  2234. } else if (xr_mode_index == XR_MODE_OPENXR) {
  2235. command_line_strings.push_back("--xr_mode_openxr");
  2236. } else { // XRMode.REGULAR is the default.
  2237. command_line_strings.push_back("--xr_mode_regular");
  2238. }
  2239. bool immersive = p_preset->get("screen/immersive_mode");
  2240. if (immersive) {
  2241. command_line_strings.push_back("--use_immersive");
  2242. }
  2243. bool debug_opengl = p_preset->get("graphics/opengl_debug");
  2244. if (debug_opengl) {
  2245. command_line_strings.push_back("--debug_opengl");
  2246. }
  2247. bool translucent = ProjectSettings::get_singleton()->get("display/window/per_pixel_transparency/enabled");
  2248. if (translucent) {
  2249. command_line_strings.push_back("--translucent");
  2250. }
  2251. if (command_line_strings.size()) {
  2252. r_command_line_flags.resize(4);
  2253. encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);
  2254. for (int i = 0; i < command_line_strings.size(); i++) {
  2255. print_line(itos(i) + " param: " + command_line_strings[i]);
  2256. CharString command_line_argument = command_line_strings[i].utf8();
  2257. int base = r_command_line_flags.size();
  2258. int length = command_line_argument.length();
  2259. if (length == 0) {
  2260. continue;
  2261. }
  2262. r_command_line_flags.resize(base + 4 + length);
  2263. encode_uint32(length, &r_command_line_flags.write[base]);
  2264. memcpy(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);
  2265. }
  2266. }
  2267. }
  2268. Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &export_path, EditorProgress &ep) {
  2269. int export_format = int(p_preset->get("custom_template/export_format"));
  2270. String export_label = export_format == EXPORT_FORMAT_AAB ? "AAB" : "APK";
  2271. String release_keystore = p_preset->get("keystore/release");
  2272. String release_username = p_preset->get("keystore/release_user");
  2273. String release_password = p_preset->get("keystore/release_password");
  2274. String apksigner = get_apksigner_path();
  2275. print_verbose("Starting signing of the " + export_label + " binary using " + apksigner);
  2276. if (!FileAccess::exists(apksigner)) {
  2277. EditorNode::add_io_error(vformat(TTR("'apksigner' could not be found.\nPlease check the command is available in the Android SDK build-tools directory.\nThe resulting %s is unsigned."), export_label));
  2278. return OK;
  2279. }
  2280. String keystore;
  2281. String password;
  2282. String user;
  2283. if (p_debug) {
  2284. keystore = p_preset->get("keystore/debug");
  2285. password = p_preset->get("keystore/debug_password");
  2286. user = p_preset->get("keystore/debug_user");
  2287. if (keystore.empty()) {
  2288. keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  2289. password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
  2290. user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
  2291. }
  2292. if (ep.step(vformat(TTR("Signing debug %s..."), export_label), 104)) {
  2293. return ERR_SKIP;
  2294. }
  2295. } else {
  2296. keystore = release_keystore;
  2297. password = release_password;
  2298. user = release_username;
  2299. if (ep.step(vformat(TTR("Signing release %s..."), export_label), 104)) {
  2300. return ERR_SKIP;
  2301. }
  2302. }
  2303. if (!FileAccess::exists(keystore)) {
  2304. EditorNode::add_io_error(TTR("Could not find keystore, unable to export."));
  2305. return ERR_FILE_CANT_OPEN;
  2306. }
  2307. String output;
  2308. List<String> args;
  2309. args.push_back("sign");
  2310. args.push_back("--verbose");
  2311. args.push_back("--ks");
  2312. args.push_back(keystore);
  2313. args.push_back("--ks-pass");
  2314. args.push_back("pass:" + password);
  2315. args.push_back("--ks-key-alias");
  2316. args.push_back(user);
  2317. args.push_back(export_path);
  2318. if (p_debug) {
  2319. // We only print verbose logs for debug builds to avoid leaking release keystore credentials.
  2320. print_verbose("Signing debug binary using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));
  2321. }
  2322. int retval;
  2323. output.clear();
  2324. OS::get_singleton()->execute(apksigner, args, true, nullptr, &output, &retval, true);
  2325. print_verbose(output);
  2326. if (retval) {
  2327. EditorNode::add_io_error(vformat(TTR("'apksigner' returned with error #%d"), retval));
  2328. return ERR_CANT_CREATE;
  2329. }
  2330. if (ep.step(vformat(TTR("Verifying %s..."), export_label), 105)) {
  2331. return ERR_SKIP;
  2332. }
  2333. args.clear();
  2334. args.push_back("verify");
  2335. args.push_back("--verbose");
  2336. args.push_back(export_path);
  2337. if (p_debug) {
  2338. print_verbose("Verifying signed build using: " + String("\n") + apksigner + " " + join_list(args, String(" ")));
  2339. }
  2340. output.clear();
  2341. OS::get_singleton()->execute(apksigner, args, true, nullptr, &output, &retval, true);
  2342. print_verbose(output);
  2343. if (retval) {
  2344. EditorNode::add_io_error(vformat(TTR("'apksigner' verification of %s failed."), export_label));
  2345. return ERR_CANT_CREATE;
  2346. }
  2347. print_verbose("Successfully completed signing build.");
  2348. return OK;
  2349. }
  2350. void EditorExportPlatformAndroid::_clear_assets_directory() {
  2351. DirAccessRef da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  2352. // Clear the APK assets directory
  2353. if (da_res->dir_exists(APK_ASSETS_DIRECTORY)) {
  2354. print_verbose("Clearing APK assets directory..");
  2355. DirAccessRef da_assets = DirAccess::open(APK_ASSETS_DIRECTORY);
  2356. da_assets->erase_contents_recursive();
  2357. da_res->remove(APK_ASSETS_DIRECTORY);
  2358. }
  2359. // Clear the AAB assets directory
  2360. if (da_res->dir_exists(AAB_ASSETS_DIRECTORY)) {
  2361. print_verbose("Clearing AAB assets directory..");
  2362. DirAccessRef da_assets = DirAccess::open(AAB_ASSETS_DIRECTORY);
  2363. da_assets->erase_contents_recursive();
  2364. da_res->remove(AAB_ASSETS_DIRECTORY);
  2365. }
  2366. }
  2367. void EditorExportPlatformAndroid::_remove_copied_libs() {
  2368. print_verbose("Removing previously installed libraries...");
  2369. Error error;
  2370. String libs_json = FileAccess::get_file_as_string(GDNATIVE_LIBS_PATH, &error);
  2371. if (error || libs_json.empty()) {
  2372. print_verbose("No previously installed libraries found");
  2373. return;
  2374. }
  2375. Variant result;
  2376. String error_string;
  2377. int error_line;
  2378. error = JSON::parse(libs_json, result, error_string, error_line);
  2379. ERR_FAIL_COND_MSG(error, "Error parsing \"" + libs_json + "\" on line " + itos(error_line) + ": " + error_string);
  2380. Vector<String> libs = result;
  2381. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  2382. for (int i = 0; i < libs.size(); i++) {
  2383. print_verbose("Removing previously installed library " + libs[i]);
  2384. da->remove(libs[i]);
  2385. }
  2386. da->remove(GDNATIVE_LIBS_PATH);
  2387. }
  2388. String EditorExportPlatformAndroid::join_list(List<String> parts, const String &separator) const {
  2389. String ret;
  2390. for (int i = 0; i < parts.size(); ++i) {
  2391. if (i > 0) {
  2392. ret += separator;
  2393. }
  2394. ret += parts[i];
  2395. }
  2396. return ret;
  2397. }
  2398. Error EditorExportPlatformAndroid::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
  2399. int export_format = int(p_preset->get("custom_template/export_format"));
  2400. bool should_sign = p_preset->get("package/signed");
  2401. return export_project_helper(p_preset, p_debug, p_path, export_format, should_sign, p_flags);
  2402. }
  2403. 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) {
  2404. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  2405. String src_apk;
  2406. Error err;
  2407. EditorProgress ep("export", TTR("Exporting for Android"), 105, true);
  2408. bool use_custom_build = bool(p_preset->get("custom_template/use_custom_build"));
  2409. bool p_give_internet = p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG);
  2410. bool apk_expansion = p_preset->get("apk_expansion/enable");
  2411. Vector<String> enabled_abis = get_enabled_abis(p_preset);
  2412. print_verbose("Exporting for Android...");
  2413. print_verbose("- debug build: " + bool_to_string(p_debug));
  2414. print_verbose("- export path: " + p_path);
  2415. print_verbose("- export format: " + itos(export_format));
  2416. print_verbose("- sign build: " + bool_to_string(should_sign));
  2417. print_verbose("- custom build enabled: " + bool_to_string(use_custom_build));
  2418. print_verbose("- apk expansion enabled: " + bool_to_string(apk_expansion));
  2419. print_verbose("- enabled abis: " + String(",").join(enabled_abis));
  2420. print_verbose("- export filter: " + itos(p_preset->get_export_filter()));
  2421. print_verbose("- include filter: " + p_preset->get_include_filter());
  2422. print_verbose("- exclude filter: " + p_preset->get_exclude_filter());
  2423. Ref<Image> splash_image;
  2424. Ref<Image> splash_bg_color_image;
  2425. String processed_splash_config_xml = load_splash_refs(splash_image, splash_bg_color_image);
  2426. Ref<Image> main_image;
  2427. Ref<Image> foreground;
  2428. Ref<Image> background;
  2429. load_icon_refs(p_preset, main_image, foreground, background);
  2430. Vector<uint8_t> command_line_flags;
  2431. // Write command line flags into the command_line_flags variable.
  2432. get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);
  2433. if (export_format == EXPORT_FORMAT_AAB) {
  2434. if (!p_path.ends_with(".aab")) {
  2435. EditorNode::get_singleton()->show_warning(TTR("Invalid filename! Android App Bundle requires the *.aab extension."));
  2436. return ERR_UNCONFIGURED;
  2437. }
  2438. if (apk_expansion) {
  2439. EditorNode::get_singleton()->show_warning(TTR("APK Expansion not compatible with Android App Bundle."));
  2440. return ERR_UNCONFIGURED;
  2441. }
  2442. }
  2443. if (export_format == EXPORT_FORMAT_APK && !p_path.ends_with(".apk")) {
  2444. EditorNode::get_singleton()->show_warning(
  2445. TTR("Invalid filename! Android APK requires the *.apk extension."));
  2446. return ERR_UNCONFIGURED;
  2447. }
  2448. if (export_format > EXPORT_FORMAT_AAB || export_format < EXPORT_FORMAT_APK) {
  2449. EditorNode::add_io_error(TTR("Unsupported export format!\n"));
  2450. return ERR_UNCONFIGURED; //TODO: is this the right error?
  2451. }
  2452. if (use_custom_build) {
  2453. print_verbose("Starting custom build..");
  2454. //test that installed build version is alright
  2455. {
  2456. print_verbose("Checking build version..");
  2457. FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ);
  2458. if (!f) {
  2459. EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu."));
  2460. return ERR_UNCONFIGURED;
  2461. }
  2462. String version = f->get_line().strip_edges();
  2463. print_verbose("- build version: " + version);
  2464. f->close();
  2465. if (version != VERSION_FULL_CONFIG) {
  2466. EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n Template installed: %s\n Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG));
  2467. return ERR_UNCONFIGURED;
  2468. }
  2469. }
  2470. const String assets_directory = get_assets_directory(p_preset, export_format);
  2471. String sdk_path = EDITOR_GET("export/android/android_sdk_path");
  2472. 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'.");
  2473. print_verbose("Android sdk path: " + sdk_path);
  2474. // TODO: should we use "package/name" or "application/config/name"?
  2475. String project_name = get_project_name(p_preset->get("package/name"));
  2476. err = _create_project_name_strings_files(p_preset, project_name); //project name localization.
  2477. if (err != OK) {
  2478. EditorNode::add_io_error(TTR("Unable to overwrite res://android/build/res/*.xml files with project name"));
  2479. }
  2480. // Copies the project icon files into the appropriate Gradle project directory.
  2481. _copy_icons_to_gradle_project(p_preset, processed_splash_config_xml, splash_image, splash_bg_color_image, main_image, foreground, background);
  2482. // Write an AndroidManifest.xml file into the Gradle project directory.
  2483. _write_tmp_manifest(p_preset, p_give_internet, p_debug);
  2484. _update_custom_build_project();
  2485. //stores all the project files inside the Gradle project directory. Also includes all ABIs
  2486. _clear_assets_directory();
  2487. _remove_copied_libs();
  2488. if (!apk_expansion) {
  2489. print_verbose("Exporting project files..");
  2490. CustomExportData user_data;
  2491. user_data.assets_directory = assets_directory;
  2492. user_data.debug = p_debug;
  2493. err = export_project_files(p_preset, rename_and_store_file_in_gradle_project, &user_data, copy_gradle_so);
  2494. if (err != OK) {
  2495. EditorNode::add_io_error(TTR("Could not export project files to gradle project\n"));
  2496. return err;
  2497. }
  2498. if (user_data.libs.size() > 0) {
  2499. FileAccessRef fa = FileAccess::open(GDNATIVE_LIBS_PATH, FileAccess::WRITE);
  2500. fa->store_string(JSON::print(user_data.libs, "\t"));
  2501. fa->close();
  2502. }
  2503. } else {
  2504. print_verbose("Saving apk expansion file..");
  2505. err = save_apk_expansion_file(p_preset, p_path);
  2506. if (err != OK) {
  2507. EditorNode::add_io_error(TTR("Could not write expansion package file!"));
  2508. return err;
  2509. }
  2510. }
  2511. print_verbose("Storing command line flags..");
  2512. store_file_at_path(assets_directory + "/_cl_", command_line_flags);
  2513. print_verbose("Updating ANDROID_HOME environment to " + sdk_path);
  2514. OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
  2515. String build_command;
  2516. #ifdef WINDOWS_ENABLED
  2517. build_command = "gradlew.bat";
  2518. #else
  2519. build_command = "gradlew";
  2520. #endif
  2521. String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build");
  2522. build_command = build_path.plus_file(build_command);
  2523. String package_name = get_package_name(p_preset->get("package/unique_name"));
  2524. String version_code = itos(p_preset->get("version/code"));
  2525. String version_name = p_preset->get("version/name");
  2526. String min_sdk_version = itos(p_preset->get("version/min_sdk"));
  2527. String target_sdk_version = itos(p_preset->get("version/target_sdk"));
  2528. String enabled_abi_string = String("|").join(enabled_abis);
  2529. String sign_flag = should_sign ? "true" : "false";
  2530. String zipalign_flag = "true";
  2531. Vector<PluginConfigAndroid> enabled_plugins = get_enabled_plugins(p_preset);
  2532. String local_plugins_binaries = PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_LOCAL, enabled_plugins);
  2533. String remote_plugins_binaries = PluginConfigAndroid::get_plugins_binaries(PluginConfigAndroid::BINARY_TYPE_REMOTE, enabled_plugins);
  2534. String custom_maven_repos = PluginConfigAndroid::get_plugins_custom_maven_repos(enabled_plugins);
  2535. bool clean_build_required = is_clean_build_required(enabled_plugins);
  2536. List<String> cmdline;
  2537. if (clean_build_required) {
  2538. cmdline.push_back("clean");
  2539. }
  2540. String build_type = p_debug ? "Debug" : "Release";
  2541. if (export_format == EXPORT_FORMAT_AAB) {
  2542. String bundle_build_command = vformat("bundle%s", build_type);
  2543. cmdline.push_back(bundle_build_command);
  2544. } else if (export_format == EXPORT_FORMAT_APK) {
  2545. String apk_build_command = vformat("assemble%s", build_type);
  2546. cmdline.push_back(apk_build_command);
  2547. }
  2548. cmdline.push_back("-p"); // argument to specify the start directory.
  2549. cmdline.push_back(build_path); // start directory.
  2550. cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.
  2551. cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code.
  2552. cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name.
  2553. cmdline.push_back("-Pexport_version_min_sdk=" + min_sdk_version); // argument to specify the min sdk.
  2554. cmdline.push_back("-Pexport_version_target_sdk=" + target_sdk_version); // argument to specify the target sdk.
  2555. cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs.
  2556. cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies.
  2557. cmdline.push_back("-Pplugins_remote_binaries=" + remote_plugins_binaries); // argument to specify the list of plugins remote dependencies.
  2558. cmdline.push_back("-Pplugins_maven_repos=" + custom_maven_repos); // argument to specify the list of custom maven repos for the plugins dependencies.
  2559. cmdline.push_back("-Pperform_zipalign=" + zipalign_flag); // argument to specify whether the build should be zipaligned.
  2560. cmdline.push_back("-Pperform_signing=" + sign_flag); // argument to specify whether the build should be signed.
  2561. cmdline.push_back("-Pgodot_editor_version=" + String(VERSION_FULL_CONFIG));
  2562. // NOTE: The release keystore is not included in the verbose logging
  2563. // to avoid accidentally leaking sensitive information when sharing verbose logs for troubleshooting.
  2564. // Any non-sensitive additions to the command line arguments must be done above this section.
  2565. // Sensitive additions must be done below the logging statement.
  2566. print_verbose("Build Android project using gradle command: " + String("\n") + build_command + " " + join_list(cmdline, String(" ")));
  2567. if (should_sign) {
  2568. if (p_debug) {
  2569. String debug_keystore = p_preset->get("keystore/debug");
  2570. String debug_password = p_preset->get("keystore/debug_password");
  2571. String debug_user = p_preset->get("keystore/debug_user");
  2572. if (debug_keystore.empty()) {
  2573. debug_keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  2574. debug_password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
  2575. debug_user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
  2576. }
  2577. cmdline.push_back("-Pdebug_keystore_file=" + debug_keystore); // argument to specify the debug keystore file.
  2578. cmdline.push_back("-Pdebug_keystore_alias=" + debug_user); // argument to specify the debug keystore alias.
  2579. cmdline.push_back("-Pdebug_keystore_password=" + debug_password); // argument to specify the debug keystore password.
  2580. } else {
  2581. // Pass the release keystore info as well
  2582. String release_keystore = p_preset->get("keystore/release");
  2583. String release_username = p_preset->get("keystore/release_user");
  2584. String release_password = p_preset->get("keystore/release_password");
  2585. if (!FileAccess::exists(release_keystore)) {
  2586. EditorNode::add_io_error(TTR("Could not find keystore, unable to export."));
  2587. return ERR_FILE_CANT_OPEN;
  2588. }
  2589. cmdline.push_back("-Prelease_keystore_file=" + release_keystore); // argument to specify the release keystore file.
  2590. cmdline.push_back("-Prelease_keystore_alias=" + release_username); // argument to specify the release keystore alias.
  2591. cmdline.push_back("-Prelease_keystore_password=" + release_password); // argument to specify the release keystore password.
  2592. }
  2593. }
  2594. int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
  2595. if (result != 0) {
  2596. EditorNode::get_singleton()->show_warning(TTR("Building of Android project failed, check output for the error.\nAlternatively visit docs.godotengine.org for Android build documentation."));
  2597. return ERR_CANT_CREATE;
  2598. }
  2599. List<String> copy_args;
  2600. String copy_command;
  2601. if (export_format == EXPORT_FORMAT_AAB) {
  2602. copy_command = vformat("copyAndRename%sAab", build_type);
  2603. } else if (export_format == EXPORT_FORMAT_APK) {
  2604. copy_command = vformat("copyAndRename%sApk", build_type);
  2605. }
  2606. copy_args.push_back(copy_command);
  2607. copy_args.push_back("-p"); // argument to specify the start directory.
  2608. copy_args.push_back(build_path); // start directory.
  2609. String export_filename = p_path.get_file();
  2610. String export_path = p_path.get_base_dir();
  2611. if (export_path.is_rel_path()) {
  2612. export_path = OS::get_singleton()->get_resource_dir().plus_file(export_path);
  2613. }
  2614. export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path();
  2615. copy_args.push_back("-Pexport_path=file:" + export_path);
  2616. copy_args.push_back("-Pexport_filename=" + export_filename);
  2617. print_verbose("Copying Android binary using gradle command: " + String("\n") + build_command + " " + join_list(copy_args, String(" ")));
  2618. int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args);
  2619. if (copy_result != 0) {
  2620. EditorNode::get_singleton()->show_warning(TTR("Unable to copy and rename export file, check gradle project directory for outputs."));
  2621. return ERR_CANT_CREATE;
  2622. }
  2623. print_verbose("Successfully completed Android custom build.");
  2624. return OK;
  2625. }
  2626. // This is the start of the Legacy build system
  2627. print_verbose("Starting legacy build system..");
  2628. if (p_debug) {
  2629. src_apk = p_preset->get("custom_template/debug");
  2630. } else {
  2631. src_apk = p_preset->get("custom_template/release");
  2632. }
  2633. src_apk = src_apk.strip_edges();
  2634. if (src_apk == "") {
  2635. if (p_debug) {
  2636. src_apk = find_export_template("android_debug.apk");
  2637. } else {
  2638. src_apk = find_export_template("android_release.apk");
  2639. }
  2640. if (src_apk == "") {
  2641. EditorNode::add_io_error(vformat(TTR("Package not found: %s"), src_apk));
  2642. return ERR_FILE_NOT_FOUND;
  2643. }
  2644. }
  2645. if (!DirAccess::exists(p_path.get_base_dir())) {
  2646. return ERR_FILE_BAD_PATH;
  2647. }
  2648. FileAccess *src_f = nullptr;
  2649. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  2650. if (ep.step(TTR("Creating APK..."), 0)) {
  2651. return ERR_SKIP;
  2652. }
  2653. unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
  2654. if (!pkg) {
  2655. EditorNode::add_io_error(vformat(TTR("Could not find template APK to export:\n%s"), src_apk));
  2656. return ERR_FILE_NOT_FOUND;
  2657. }
  2658. int ret = unzGoToFirstFile(pkg);
  2659. zlib_filefunc_def io2 = io;
  2660. FileAccess *dst_f = nullptr;
  2661. io2.opaque = &dst_f;
  2662. String tmp_unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned." + uitos(OS::get_singleton()->get_unix_time()) + ".apk");
  2663. #define CLEANUP_AND_RETURN(m_err) \
  2664. { \
  2665. DirAccess::remove_file_or_error(tmp_unaligned_path); \
  2666. return m_err; \
  2667. }
  2668. zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);
  2669. String cmdline = p_preset->get("command_line/extra_args");
  2670. String version_name = p_preset->get("version/name");
  2671. String package_name = p_preset->get("package/unique_name");
  2672. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  2673. Vector<String> invalid_abis(enabled_abis);
  2674. while (ret == UNZ_OK) {
  2675. //get filename
  2676. unz_file_info info;
  2677. char fname[16384];
  2678. ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  2679. bool skip = false;
  2680. String file = String::utf8(fname);
  2681. Vector<uint8_t> data;
  2682. data.resize(info.uncompressed_size);
  2683. //read
  2684. unzOpenCurrentFile(pkg);
  2685. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  2686. unzCloseCurrentFile(pkg);
  2687. //write
  2688. if (file == "AndroidManifest.xml") {
  2689. _fix_manifest(p_preset, data, p_give_internet);
  2690. }
  2691. if (file == "resources.arsc") {
  2692. _fix_resources(p_preset, data);
  2693. }
  2694. // Process the splash image
  2695. if ((file == SPLASH_IMAGE_EXPORT_PATH || file == LEGACY_BUILD_SPLASH_IMAGE_EXPORT_PATH) && splash_image.is_valid() && !splash_image->empty()) {
  2696. _load_image_data(splash_image, data);
  2697. }
  2698. // Process the splash bg color image
  2699. if ((file == SPLASH_BG_COLOR_PATH || file == LEGACY_BUILD_SPLASH_BG_COLOR_PATH) && splash_bg_color_image.is_valid() && !splash_bg_color_image->empty()) {
  2700. _load_image_data(splash_bg_color_image, data);
  2701. }
  2702. for (int i = 0; i < icon_densities_count; ++i) {
  2703. if (main_image.is_valid() && !main_image->empty()) {
  2704. if (file == launcher_icons[i].export_path) {
  2705. _process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data);
  2706. }
  2707. }
  2708. if (foreground.is_valid() && !foreground->empty()) {
  2709. if (file == launcher_adaptive_icon_foregrounds[i].export_path) {
  2710. _process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data);
  2711. }
  2712. }
  2713. if (background.is_valid() && !background->empty()) {
  2714. if (file == launcher_adaptive_icon_backgrounds[i].export_path) {
  2715. _process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data);
  2716. }
  2717. }
  2718. }
  2719. if (file.ends_with(".so")) {
  2720. bool enabled = false;
  2721. for (int i = 0; i < enabled_abis.size(); ++i) {
  2722. if (file.begins_with("lib/" + enabled_abis[i] + "/")) {
  2723. invalid_abis.erase(enabled_abis[i]);
  2724. enabled = true;
  2725. break;
  2726. }
  2727. }
  2728. if (!enabled) {
  2729. skip = true;
  2730. }
  2731. }
  2732. if (file.begins_with("META-INF") && should_sign) {
  2733. skip = true;
  2734. }
  2735. if (!skip) {
  2736. print_line("ADDING: " + file);
  2737. // Respect decision on compression made by AAPT for the export template
  2738. const bool uncompressed = info.compression_method == 0;
  2739. zip_fileinfo zipfi = get_zip_fileinfo();
  2740. zipOpenNewFileInZip(unaligned_apk,
  2741. file.utf8().get_data(),
  2742. &zipfi,
  2743. nullptr,
  2744. 0,
  2745. nullptr,
  2746. 0,
  2747. nullptr,
  2748. uncompressed ? 0 : Z_DEFLATED,
  2749. Z_DEFAULT_COMPRESSION);
  2750. zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
  2751. zipCloseFileInZip(unaligned_apk);
  2752. }
  2753. ret = unzGoToNextFile(pkg);
  2754. }
  2755. if (!invalid_abis.empty()) {
  2756. String unsupported_arch = String(", ").join(invalid_abis);
  2757. EditorNode::add_io_error(vformat(TTR("Missing libraries in the export template for the selected architectures: %s.\nPlease build a template with all required libraries, or uncheck the missing architectures in the export preset."), unsupported_arch));
  2758. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2759. }
  2760. if (ep.step(TTR("Adding files..."), 1)) {
  2761. CLEANUP_AND_RETURN(ERR_SKIP);
  2762. }
  2763. err = OK;
  2764. if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
  2765. APKExportData ed;
  2766. ed.ep = &ep;
  2767. ed.apk = unaligned_apk;
  2768. err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so);
  2769. } else {
  2770. if (apk_expansion) {
  2771. err = save_apk_expansion_file(p_preset, p_path);
  2772. if (err != OK) {
  2773. EditorNode::add_io_error(TTR("Could not write expansion package file!"));
  2774. return err;
  2775. }
  2776. } else {
  2777. APKExportData ed;
  2778. ed.ep = &ep;
  2779. ed.apk = unaligned_apk;
  2780. err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so);
  2781. }
  2782. }
  2783. if (err != OK) {
  2784. unzClose(pkg);
  2785. EditorNode::add_io_error(TTR("Could not export project files"));
  2786. CLEANUP_AND_RETURN(ERR_SKIP);
  2787. }
  2788. zip_fileinfo zipfi = get_zip_fileinfo();
  2789. zipOpenNewFileInZip(unaligned_apk,
  2790. "assets/_cl_",
  2791. &zipfi,
  2792. nullptr,
  2793. 0,
  2794. nullptr,
  2795. 0,
  2796. nullptr,
  2797. 0, // No compress (little size gain and potentially slower startup)
  2798. Z_DEFAULT_COMPRESSION);
  2799. zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());
  2800. zipCloseFileInZip(unaligned_apk);
  2801. zipClose(unaligned_apk, nullptr);
  2802. unzClose(pkg);
  2803. if (err != OK) {
  2804. CLEANUP_AND_RETURN(err);
  2805. }
  2806. // Let's zip-align (must be done before signing)
  2807. static const int ZIP_ALIGNMENT = 4;
  2808. // If we're not signing the apk, then the next step should be the last.
  2809. const int next_step = should_sign ? 103 : 105;
  2810. if (ep.step(TTR("Aligning APK..."), next_step)) {
  2811. CLEANUP_AND_RETURN(ERR_SKIP);
  2812. }
  2813. unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);
  2814. if (!tmp_unaligned) {
  2815. EditorNode::add_io_error(TTR("Could not unzip temporary unaligned APK."));
  2816. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2817. }
  2818. ret = unzGoToFirstFile(tmp_unaligned);
  2819. io2 = io;
  2820. dst_f = nullptr;
  2821. io2.opaque = &dst_f;
  2822. zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);
  2823. // Take files from the unaligned APK and write them out to the aligned one
  2824. // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
  2825. // following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
  2826. int bias = 0;
  2827. while (ret == UNZ_OK) {
  2828. unz_file_info info;
  2829. memset(&info, 0, sizeof(info));
  2830. char fname[16384];
  2831. char extra[16384];
  2832. ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0);
  2833. String file = String::utf8(fname);
  2834. Vector<uint8_t> data;
  2835. data.resize(info.compressed_size);
  2836. // read
  2837. int method, level;
  2838. unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
  2839. long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
  2840. unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
  2841. unzCloseCurrentFile(tmp_unaligned);
  2842. // align
  2843. int padding = 0;
  2844. if (!info.compression_method) {
  2845. // Uncompressed file => Align
  2846. long new_offset = file_offset + bias;
  2847. padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
  2848. }
  2849. memset(extra + info.size_file_extra, 0, padding);
  2850. zip_fileinfo fileinfo = get_zip_fileinfo();
  2851. zipOpenNewFileInZip2(final_apk,
  2852. file.utf8().get_data(),
  2853. &fileinfo,
  2854. extra,
  2855. info.size_file_extra + padding,
  2856. nullptr,
  2857. 0,
  2858. nullptr,
  2859. method,
  2860. level,
  2861. 1); // raw write
  2862. zipWriteInFileInZip(final_apk, data.ptr(), data.size());
  2863. zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);
  2864. bias += padding;
  2865. ret = unzGoToNextFile(tmp_unaligned);
  2866. }
  2867. zipClose(final_apk, nullptr);
  2868. unzClose(tmp_unaligned);
  2869. if (should_sign) {
  2870. // Signing must be done last as any additional modifications to the
  2871. // file will invalidate the signature.
  2872. err = sign_apk(p_preset, p_debug, p_path, ep);
  2873. if (err != OK) {
  2874. CLEANUP_AND_RETURN(err);
  2875. }
  2876. }
  2877. CLEANUP_AND_RETURN(OK);
  2878. }
  2879. void EditorExportPlatformAndroid::get_platform_features(List<String> *r_features) {
  2880. r_features->push_back("mobile");
  2881. r_features->push_back("Android");
  2882. }
  2883. void EditorExportPlatformAndroid::resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) {
  2884. }
  2885. EditorExportPlatformAndroid::EditorExportPlatformAndroid() {
  2886. Ref<Image> img = memnew(Image(_android_logo));
  2887. logo.instance();
  2888. logo->create_from_image(img);
  2889. img = Ref<Image>(memnew(Image(_android_run_icon)));
  2890. run_icon.instance();
  2891. run_icon->create_from_image(img);
  2892. devices_changed.set();
  2893. plugins_changed.set();
  2894. check_for_changes_thread.start(_check_for_changes_poll_thread, this);
  2895. }
  2896. EditorExportPlatformAndroid::~EditorExportPlatformAndroid() {
  2897. quit_request.set();
  2898. check_for_changes_thread.wait_to_finish();
  2899. }