export_plugin.cpp 166 KB

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