export_plugin.cpp 142 KB

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