export_plugin.cpp 154 KB

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