export_plugin.cpp 133 KB

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