export_plugin.cpp 154 KB

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