export_plugin.cpp 119 KB

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