export_plugin.cpp 123 KB

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