export_plugin.cpp 167 KB

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