export_plugin.cpp 140 KB

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