export_plugin.cpp 119 KB

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