export_plugin.cpp 150 KB

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