export_plugin.cpp 138 KB

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