export_plugin.cpp 129 KB

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