export_plugin.cpp 140 KB

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