export_plugin.cpp 154 KB

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