export_plugin.cpp 159 KB

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