export_plugin.cpp 149 KB

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