export_plugin.cpp 161 KB

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