export_plugin.cpp 116 KB

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