export_plugin.cpp 155 KB

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