export_plugin.cpp 136 KB

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