export_plugin.cpp 132 KB

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