export_plugin.cpp 140 KB

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