export_plugin.cpp 137 KB

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