export.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924
  1. /*************************************************************************/
  2. /* export.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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.h"
  31. #include "core/io/image_loader.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/io/zip_io.h"
  34. #include "core/os/dir_access.h"
  35. #include "core/os/file_access.h"
  36. #include "core/os/os.h"
  37. #include "core/project_settings.h"
  38. #include "core/version.h"
  39. #include "drivers/png/png_driver_common.h"
  40. #include "editor/editor_export.h"
  41. #include "editor/editor_log.h"
  42. #include "editor/editor_node.h"
  43. #include "editor/editor_settings.h"
  44. #include "platform/android/export/gradle_export_util.h"
  45. #include "platform/android/logo.gen.h"
  46. #include "platform/android/plugin/godot_plugin_config.h"
  47. #include "platform/android/run_icon.gen.h"
  48. #include <string.h>
  49. static const char *android_perms[] = {
  50. "ACCESS_CHECKIN_PROPERTIES",
  51. "ACCESS_COARSE_LOCATION",
  52. "ACCESS_FINE_LOCATION",
  53. "ACCESS_LOCATION_EXTRA_COMMANDS",
  54. "ACCESS_MOCK_LOCATION",
  55. "ACCESS_NETWORK_STATE",
  56. "ACCESS_SURFACE_FLINGER",
  57. "ACCESS_WIFI_STATE",
  58. "ACCOUNT_MANAGER",
  59. "ADD_VOICEMAIL",
  60. "AUTHENTICATE_ACCOUNTS",
  61. "BATTERY_STATS",
  62. "BIND_ACCESSIBILITY_SERVICE",
  63. "BIND_APPWIDGET",
  64. "BIND_DEVICE_ADMIN",
  65. "BIND_INPUT_METHOD",
  66. "BIND_NFC_SERVICE",
  67. "BIND_NOTIFICATION_LISTENER_SERVICE",
  68. "BIND_PRINT_SERVICE",
  69. "BIND_REMOTEVIEWS",
  70. "BIND_TEXT_SERVICE",
  71. "BIND_VPN_SERVICE",
  72. "BIND_WALLPAPER",
  73. "BLUETOOTH",
  74. "BLUETOOTH_ADMIN",
  75. "BLUETOOTH_PRIVILEGED",
  76. "BRICK",
  77. "BROADCAST_PACKAGE_REMOVED",
  78. "BROADCAST_SMS",
  79. "BROADCAST_STICKY",
  80. "BROADCAST_WAP_PUSH",
  81. "CALL_PHONE",
  82. "CALL_PRIVILEGED",
  83. "CAMERA",
  84. "CAPTURE_AUDIO_OUTPUT",
  85. "CAPTURE_SECURE_VIDEO_OUTPUT",
  86. "CAPTURE_VIDEO_OUTPUT",
  87. "CHANGE_COMPONENT_ENABLED_STATE",
  88. "CHANGE_CONFIGURATION",
  89. "CHANGE_NETWORK_STATE",
  90. "CHANGE_WIFI_MULTICAST_STATE",
  91. "CHANGE_WIFI_STATE",
  92. "CLEAR_APP_CACHE",
  93. "CLEAR_APP_USER_DATA",
  94. "CONTROL_LOCATION_UPDATES",
  95. "DELETE_CACHE_FILES",
  96. "DELETE_PACKAGES",
  97. "DEVICE_POWER",
  98. "DIAGNOSTIC",
  99. "DISABLE_KEYGUARD",
  100. "DUMP",
  101. "EXPAND_STATUS_BAR",
  102. "FACTORY_TEST",
  103. "FLASHLIGHT",
  104. "FORCE_BACK",
  105. "GET_ACCOUNTS",
  106. "GET_PACKAGE_SIZE",
  107. "GET_TASKS",
  108. "GET_TOP_ACTIVITY_INFO",
  109. "GLOBAL_SEARCH",
  110. "HARDWARE_TEST",
  111. "INJECT_EVENTS",
  112. "INSTALL_LOCATION_PROVIDER",
  113. "INSTALL_PACKAGES",
  114. "INSTALL_SHORTCUT",
  115. "INTERNAL_SYSTEM_WINDOW",
  116. "INTERNET",
  117. "KILL_BACKGROUND_PROCESSES",
  118. "LOCATION_HARDWARE",
  119. "MANAGE_ACCOUNTS",
  120. "MANAGE_APP_TOKENS",
  121. "MANAGE_DOCUMENTS",
  122. "MASTER_CLEAR",
  123. "MEDIA_CONTENT_CONTROL",
  124. "MODIFY_AUDIO_SETTINGS",
  125. "MODIFY_PHONE_STATE",
  126. "MOUNT_FORMAT_FILESYSTEMS",
  127. "MOUNT_UNMOUNT_FILESYSTEMS",
  128. "NFC",
  129. "PERSISTENT_ACTIVITY",
  130. "PROCESS_OUTGOING_CALLS",
  131. "READ_CALENDAR",
  132. "READ_CALL_LOG",
  133. "READ_CONTACTS",
  134. "READ_EXTERNAL_STORAGE",
  135. "READ_FRAME_BUFFER",
  136. "READ_HISTORY_BOOKMARKS",
  137. "READ_INPUT_STATE",
  138. "READ_LOGS",
  139. "READ_PHONE_STATE",
  140. "READ_PROFILE",
  141. "READ_SMS",
  142. "READ_SOCIAL_STREAM",
  143. "READ_SYNC_SETTINGS",
  144. "READ_SYNC_STATS",
  145. "READ_USER_DICTIONARY",
  146. "REBOOT",
  147. "RECEIVE_BOOT_COMPLETED",
  148. "RECEIVE_MMS",
  149. "RECEIVE_SMS",
  150. "RECEIVE_WAP_PUSH",
  151. "RECORD_AUDIO",
  152. "REORDER_TASKS",
  153. "RESTART_PACKAGES",
  154. "SEND_RESPOND_VIA_MESSAGE",
  155. "SEND_SMS",
  156. "SET_ACTIVITY_WATCHER",
  157. "SET_ALARM",
  158. "SET_ALWAYS_FINISH",
  159. "SET_ANIMATION_SCALE",
  160. "SET_DEBUG_APP",
  161. "SET_ORIENTATION",
  162. "SET_POINTER_SPEED",
  163. "SET_PREFERRED_APPLICATIONS",
  164. "SET_PROCESS_LIMIT",
  165. "SET_TIME",
  166. "SET_TIME_ZONE",
  167. "SET_WALLPAPER",
  168. "SET_WALLPAPER_HINTS",
  169. "SIGNAL_PERSISTENT_PROCESSES",
  170. "STATUS_BAR",
  171. "SUBSCRIBED_FEEDS_READ",
  172. "SUBSCRIBED_FEEDS_WRITE",
  173. "SYSTEM_ALERT_WINDOW",
  174. "TRANSMIT_IR",
  175. "UNINSTALL_SHORTCUT",
  176. "UPDATE_DEVICE_STATS",
  177. "USE_CREDENTIALS",
  178. "USE_SIP",
  179. "VIBRATE",
  180. "WAKE_LOCK",
  181. "WRITE_APN_SETTINGS",
  182. "WRITE_CALENDAR",
  183. "WRITE_CALL_LOG",
  184. "WRITE_CONTACTS",
  185. "WRITE_EXTERNAL_STORAGE",
  186. "WRITE_GSERVICES",
  187. "WRITE_HISTORY_BOOKMARKS",
  188. "WRITE_PROFILE",
  189. "WRITE_SECURE_SETTINGS",
  190. "WRITE_SETTINGS",
  191. "WRITE_SMS",
  192. "WRITE_SOCIAL_STREAM",
  193. "WRITE_SYNC_SETTINGS",
  194. "WRITE_USER_DICTIONARY",
  195. NULL
  196. };
  197. struct LauncherIcon {
  198. const char *export_path;
  199. int dimensions;
  200. };
  201. static const int icon_densities_count = 6;
  202. static const char *launcher_icon_option = "launcher_icons/main_192x192";
  203. static const char *launcher_adaptive_icon_foreground_option = "launcher_icons/adaptive_foreground_432x432";
  204. static const char *launcher_adaptive_icon_background_option = "launcher_icons/adaptive_background_432x432";
  205. static const LauncherIcon launcher_icons[icon_densities_count] = {
  206. { "res/mipmap-xxxhdpi-v4/icon.png", 192 },
  207. { "res/mipmap-xxhdpi-v4/icon.png", 144 },
  208. { "res/mipmap-xhdpi-v4/icon.png", 96 },
  209. { "res/mipmap-hdpi-v4/icon.png", 72 },
  210. { "res/mipmap-mdpi-v4/icon.png", 48 },
  211. { "res/mipmap/icon.png", 192 }
  212. };
  213. static const LauncherIcon launcher_adaptive_icon_foregrounds[icon_densities_count] = {
  214. { "res/mipmap-xxxhdpi-v4/icon_foreground.png", 432 },
  215. { "res/mipmap-xxhdpi-v4/icon_foreground.png", 324 },
  216. { "res/mipmap-xhdpi-v4/icon_foreground.png", 216 },
  217. { "res/mipmap-hdpi-v4/icon_foreground.png", 162 },
  218. { "res/mipmap-mdpi-v4/icon_foreground.png", 108 },
  219. { "res/mipmap/icon_foreground.png", 432 }
  220. };
  221. static const LauncherIcon launcher_adaptive_icon_backgrounds[icon_densities_count] = {
  222. { "res/mipmap-xxxhdpi-v4/icon_background.png", 432 },
  223. { "res/mipmap-xxhdpi-v4/icon_background.png", 324 },
  224. { "res/mipmap-xhdpi-v4/icon_background.png", 216 },
  225. { "res/mipmap-hdpi-v4/icon_background.png", 162 },
  226. { "res/mipmap-mdpi-v4/icon_background.png", 108 },
  227. { "res/mipmap/icon_background.png", 432 }
  228. };
  229. class EditorExportPlatformAndroid : public EditorExportPlatform {
  230. GDCLASS(EditorExportPlatformAndroid, EditorExportPlatform);
  231. Ref<ImageTexture> logo;
  232. Ref<ImageTexture> run_icon;
  233. struct Device {
  234. String id;
  235. String name;
  236. String description;
  237. int api_level;
  238. };
  239. struct APKExportData {
  240. zipFile apk;
  241. EditorProgress *ep;
  242. };
  243. Vector<PluginConfig> plugins;
  244. String last_plugin_names;
  245. uint64_t last_custom_build_time = 0;
  246. volatile bool plugins_changed;
  247. Mutex *plugins_lock;
  248. Vector<Device> devices;
  249. volatile bool devices_changed;
  250. Mutex *device_lock;
  251. Thread *check_for_changes_thread;
  252. volatile bool quit_request;
  253. static void _check_for_changes_poll_thread(void *ud) {
  254. EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud;
  255. while (!ea->quit_request) {
  256. // Check for plugins updates
  257. {
  258. // Nothing to do if we already know the plugins have changed.
  259. if (!ea->plugins_changed) {
  260. Vector<PluginConfig> loaded_plugins = get_plugins();
  261. ea->plugins_lock->lock();
  262. if (ea->plugins.size() != loaded_plugins.size()) {
  263. ea->plugins_changed = true;
  264. } else {
  265. for (int i = 0; i < ea->plugins.size(); i++) {
  266. if (ea->plugins[i].name != loaded_plugins[i].name) {
  267. ea->plugins_changed = true;
  268. break;
  269. }
  270. }
  271. }
  272. if (ea->plugins_changed) {
  273. ea->plugins = loaded_plugins;
  274. }
  275. ea->plugins_lock->unlock();
  276. }
  277. }
  278. // Check for devices updates
  279. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  280. if (FileAccess::exists(adb)) {
  281. String devices;
  282. List<String> args;
  283. args.push_back("devices");
  284. int ec;
  285. OS::get_singleton()->execute(adb, args, true, NULL, &devices, &ec);
  286. Vector<String> ds = devices.split("\n");
  287. Vector<String> ldevices;
  288. for (int i = 1; i < ds.size(); i++) {
  289. String d = ds[i];
  290. int dpos = d.find("device");
  291. if (dpos == -1) {
  292. continue;
  293. }
  294. d = d.substr(0, dpos).strip_edges();
  295. ldevices.push_back(d);
  296. }
  297. ea->device_lock->lock();
  298. bool different = false;
  299. if (ea->devices.size() != ldevices.size()) {
  300. different = true;
  301. } else {
  302. for (int i = 0; i < ea->devices.size(); i++) {
  303. if (ea->devices[i].id != ldevices[i]) {
  304. different = true;
  305. break;
  306. }
  307. }
  308. }
  309. if (different) {
  310. Vector<Device> ndevices;
  311. for (int i = 0; i < ldevices.size(); i++) {
  312. Device d;
  313. d.id = ldevices[i];
  314. for (int j = 0; j < ea->devices.size(); j++) {
  315. if (ea->devices[j].id == ldevices[i]) {
  316. d.description = ea->devices[j].description;
  317. d.name = ea->devices[j].name;
  318. d.api_level = ea->devices[j].api_level;
  319. }
  320. }
  321. if (d.description == "") {
  322. //in the oven, request!
  323. args.clear();
  324. args.push_back("-s");
  325. args.push_back(d.id);
  326. args.push_back("shell");
  327. args.push_back("getprop");
  328. int ec2;
  329. String dp;
  330. OS::get_singleton()->execute(adb, args, true, NULL, &dp, &ec2);
  331. Vector<String> props = dp.split("\n");
  332. String vendor;
  333. String device;
  334. d.description = "Device ID: " + d.id + "\n";
  335. d.api_level = 0;
  336. for (int j = 0; j < props.size(); j++) {
  337. // got information by `shell cat /system/build.prop` before and its format is "property=value"
  338. // it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above
  339. // its format is "[property]: [value]" so changed it as like build.prop
  340. String p = props[j];
  341. p = p.replace("]: ", "=");
  342. p = p.replace("[", "");
  343. p = p.replace("]", "");
  344. if (p.begins_with("ro.product.model=")) {
  345. device = p.get_slice("=", 1).strip_edges();
  346. } else if (p.begins_with("ro.product.brand=")) {
  347. vendor = p.get_slice("=", 1).strip_edges().capitalize();
  348. } else if (p.begins_with("ro.build.display.id=")) {
  349. d.description += "Build: " + p.get_slice("=", 1).strip_edges() + "\n";
  350. } else if (p.begins_with("ro.build.version.release=")) {
  351. d.description += "Release: " + p.get_slice("=", 1).strip_edges() + "\n";
  352. } else if (p.begins_with("ro.build.version.sdk=")) {
  353. d.api_level = p.get_slice("=", 1).to_int();
  354. } else if (p.begins_with("ro.product.cpu.abi=")) {
  355. d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n";
  356. } else if (p.begins_with("ro.product.manufacturer=")) {
  357. d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n";
  358. } else if (p.begins_with("ro.board.platform=")) {
  359. d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n";
  360. } else if (p.begins_with("ro.opengles.version=")) {
  361. uint32_t opengl = p.get_slice("=", 1).to_int();
  362. d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n";
  363. }
  364. }
  365. d.name = vendor + " " + device;
  366. if (device == String()) continue;
  367. }
  368. ndevices.push_back(d);
  369. }
  370. ea->devices = ndevices;
  371. ea->devices_changed = true;
  372. }
  373. ea->device_lock->unlock();
  374. }
  375. uint64_t sleep = OS::get_singleton()->get_power_state() == OS::POWERSTATE_ON_BATTERY ? 1000 : 100;
  376. uint64_t wait = 3000000;
  377. uint64_t time = OS::get_singleton()->get_ticks_usec();
  378. while (OS::get_singleton()->get_ticks_usec() - time < wait) {
  379. OS::get_singleton()->delay_usec(1000 * sleep);
  380. if (ea->quit_request)
  381. break;
  382. }
  383. }
  384. if (EditorSettings::get_singleton()->get("export/android/shutdown_adb_on_exit")) {
  385. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  386. if (!FileAccess::exists(adb)) {
  387. return; //adb not configured
  388. }
  389. List<String> args;
  390. args.push_back("kill-server");
  391. OS::get_singleton()->execute(adb, args, true);
  392. };
  393. }
  394. String get_project_name(const String &p_name) const {
  395. String aname;
  396. if (p_name != "") {
  397. aname = p_name;
  398. } else {
  399. aname = ProjectSettings::get_singleton()->get("application/config/name");
  400. }
  401. if (aname == "") {
  402. aname = VERSION_NAME;
  403. }
  404. return aname;
  405. }
  406. String get_package_name(const String &p_package) const {
  407. String pname = p_package;
  408. String basename = ProjectSettings::get_singleton()->get("application/config/name");
  409. basename = basename.to_lower();
  410. String name;
  411. bool first = true;
  412. for (int i = 0; i < basename.length(); i++) {
  413. CharType c = basename[i];
  414. if (c >= '0' && c <= '9' && first) {
  415. continue;
  416. }
  417. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
  418. name += String::chr(c);
  419. first = false;
  420. }
  421. }
  422. if (name == "")
  423. name = "noname";
  424. pname = pname.replace("$genname", name);
  425. return pname;
  426. }
  427. bool is_package_name_valid(const String &p_package, String *r_error = NULL) const {
  428. String pname = p_package;
  429. if (pname.length() == 0) {
  430. if (r_error) {
  431. *r_error = TTR("Package name is missing.");
  432. }
  433. return false;
  434. }
  435. int segments = 0;
  436. bool first = true;
  437. for (int i = 0; i < pname.length(); i++) {
  438. CharType c = pname[i];
  439. if (first && c == '.') {
  440. if (r_error) {
  441. *r_error = TTR("Package segments must be of non-zero length.");
  442. }
  443. return false;
  444. }
  445. if (c == '.') {
  446. segments++;
  447. first = true;
  448. continue;
  449. }
  450. if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) {
  451. if (r_error) {
  452. *r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c));
  453. }
  454. return false;
  455. }
  456. if (first && (c >= '0' && c <= '9')) {
  457. if (r_error) {
  458. *r_error = TTR("A digit cannot be the first character in a package segment.");
  459. }
  460. return false;
  461. }
  462. if (first && c == '_') {
  463. if (r_error) {
  464. *r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c));
  465. }
  466. return false;
  467. }
  468. first = false;
  469. }
  470. if (segments == 0) {
  471. if (r_error) {
  472. *r_error = TTR("The package must have at least one '.' separator.");
  473. }
  474. return false;
  475. }
  476. if (first) {
  477. if (r_error) {
  478. *r_error = TTR("Package segments must be of non-zero length.");
  479. }
  480. return false;
  481. }
  482. return true;
  483. }
  484. static bool _should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) {
  485. /*
  486. * By not compressing files with little or not benefit in doing so,
  487. * a performance gain is expected attime. Moreover, if the APK is
  488. * zip-aligned, assets stored as they are can be efficiently read by
  489. * Android by memory-mapping them.
  490. */
  491. // -- Unconditional uncompress to mimic AAPT plus some other
  492. static const char *unconditional_compress_ext[] = {
  493. // From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp
  494. // These formats are already compressed, or don't compress well:
  495. ".jpg", ".jpeg", ".png", ".gif",
  496. ".wav", ".mp2", ".mp3", ".ogg", ".aac",
  497. ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
  498. ".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
  499. ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
  500. ".amr", ".awb", ".wma", ".wmv",
  501. // Godot-specific:
  502. ".webp", // Same reasoning as .png
  503. ".cfb", // Don't let small config files slow-down startup
  504. ".scn", // Binary scenes are usually already compressed
  505. ".stex", // Streamable textures are usually already compressed
  506. // Trailer for easier processing
  507. NULL
  508. };
  509. for (const char **ext = unconditional_compress_ext; *ext; ++ext) {
  510. if (p_path.to_lower().ends_with(String(*ext))) {
  511. return false;
  512. }
  513. }
  514. // -- Compressed resource?
  515. if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') {
  516. // Already compressed
  517. return false;
  518. }
  519. // --- TODO: Decide on texture resources according to their image compression setting
  520. return true;
  521. }
  522. static zip_fileinfo get_zip_fileinfo() {
  523. OS::Time time = OS::get_singleton()->get_time();
  524. OS::Date date = OS::get_singleton()->get_date();
  525. zip_fileinfo zipfi;
  526. zipfi.tmz_date.tm_hour = time.hour;
  527. zipfi.tmz_date.tm_mday = date.day;
  528. zipfi.tmz_date.tm_min = time.min;
  529. zipfi.tmz_date.tm_mon = date.month;
  530. zipfi.tmz_date.tm_sec = time.sec;
  531. zipfi.tmz_date.tm_year = date.year;
  532. zipfi.dosDate = 0;
  533. zipfi.external_fa = 0;
  534. zipfi.internal_fa = 0;
  535. return zipfi;
  536. }
  537. static Vector<String> get_abis() {
  538. Vector<String> abis;
  539. abis.push_back("armeabi-v7a");
  540. abis.push_back("arm64-v8a");
  541. abis.push_back("x86");
  542. abis.push_back("x86_64");
  543. return abis;
  544. }
  545. /// List the gdap files in the directory specified by the p_path parameter.
  546. static Vector<String> list_gdap_files(const String &p_path) {
  547. Vector<String> dir_files;
  548. DirAccessRef da = DirAccess::open(p_path);
  549. if (da) {
  550. da->list_dir_begin();
  551. while (true) {
  552. String file = da->get_next();
  553. if (file == "") {
  554. break;
  555. }
  556. if (da->current_is_dir() || da->current_is_hidden()) {
  557. continue;
  558. }
  559. if (file.ends_with(PLUGIN_CONFIG_EXT)) {
  560. dir_files.push_back(file);
  561. }
  562. }
  563. da->list_dir_end();
  564. }
  565. return dir_files;
  566. }
  567. static Vector<PluginConfig> get_plugins() {
  568. Vector<PluginConfig> loaded_plugins;
  569. String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/plugins");
  570. // Add the prebuilt plugins
  571. loaded_plugins.append_array(get_prebuilt_plugins(plugins_dir));
  572. if (DirAccess::exists(plugins_dir)) {
  573. Vector<String> plugins_filenames = list_gdap_files(plugins_dir);
  574. if (!plugins_filenames.empty()) {
  575. Ref<ConfigFile> config_file = memnew(ConfigFile);
  576. for (int i = 0; i < plugins_filenames.size(); i++) {
  577. PluginConfig config = load_plugin_config(config_file, plugins_dir.plus_file(plugins_filenames[i]));
  578. if (config.valid_config) {
  579. loaded_plugins.push_back(config);
  580. } else {
  581. print_error("Invalid plugin config file " + plugins_filenames[i]);
  582. }
  583. }
  584. }
  585. }
  586. return loaded_plugins;
  587. }
  588. static Vector<PluginConfig> get_enabled_plugins(const Ref<EditorExportPreset> &p_presets) {
  589. Vector<PluginConfig> enabled_plugins;
  590. Vector<PluginConfig> all_plugins = get_plugins();
  591. for (int i = 0; i < all_plugins.size(); i++) {
  592. PluginConfig plugin = all_plugins[i];
  593. bool enabled = p_presets->get("plugins/" + plugin.name);
  594. if (enabled) {
  595. enabled_plugins.push_back(plugin);
  596. }
  597. }
  598. return enabled_plugins;
  599. }
  600. static Error store_in_apk(APKExportData *ed, const String &p_path, const Vector<uint8_t> &p_data, int compression_method = Z_DEFLATED) {
  601. zip_fileinfo zipfi = get_zip_fileinfo();
  602. zipOpenNewFileInZip(ed->apk,
  603. p_path.utf8().get_data(),
  604. &zipfi,
  605. NULL,
  606. 0,
  607. NULL,
  608. 0,
  609. NULL,
  610. compression_method,
  611. Z_DEFAULT_COMPRESSION);
  612. zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size());
  613. zipCloseFileInZip(ed->apk);
  614. return OK;
  615. }
  616. static Error save_apk_so(void *p_userdata, const SharedObject &p_so) {
  617. if (!p_so.path.get_file().begins_with("lib")) {
  618. String err = "Android .so file names must start with \"lib\", but got: " + p_so.path;
  619. ERR_PRINTS(err);
  620. return FAILED;
  621. }
  622. APKExportData *ed = (APKExportData *)p_userdata;
  623. Vector<String> abis = get_abis();
  624. bool exported = false;
  625. for (int i = 0; i < p_so.tags.size(); ++i) {
  626. // shared objects can be fat (compatible with multiple ABIs)
  627. int abi_index = abis.find(p_so.tags[i]);
  628. if (abi_index != -1) {
  629. exported = true;
  630. String abi = abis[abi_index];
  631. String dst_path = String("lib").plus_file(abi).plus_file(p_so.path.get_file());
  632. Vector<uint8_t> array = FileAccess::get_file_as_array(p_so.path);
  633. Error store_err = store_in_apk(ed, dst_path, array);
  634. ERR_FAIL_COND_V_MSG(store_err, store_err, "Cannot store in apk file '" + dst_path + "'.");
  635. }
  636. }
  637. if (!exported) {
  638. String abis_string = String(" ").join(abis);
  639. String err = "Cannot determine ABI for library \"" + p_so.path + "\". One of the supported ABIs must be used as a tag: " + abis_string;
  640. ERR_PRINTS(err);
  641. return FAILED;
  642. }
  643. return OK;
  644. }
  645. static Error save_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
  646. APKExportData *ed = (APKExportData *)p_userdata;
  647. String dst_path = p_path.replace_first("res://", "assets/");
  648. store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0);
  649. return OK;
  650. }
  651. static Error ignore_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
  652. return OK;
  653. }
  654. void _get_permissions(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, Vector<String> &r_permissions) {
  655. const char **aperms = android_perms;
  656. while (*aperms) {
  657. bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());
  658. if (enabled) {
  659. r_permissions.push_back("android.permission." + String(*aperms));
  660. }
  661. aperms++;
  662. }
  663. PoolStringArray user_perms = p_preset->get("permissions/custom_permissions");
  664. for (int i = 0; i < user_perms.size(); i++) {
  665. String user_perm = user_perms[i].strip_edges();
  666. if (!user_perm.empty()) {
  667. r_permissions.push_back(user_perm);
  668. }
  669. }
  670. if (p_give_internet) {
  671. if (r_permissions.find("android.permission.INTERNET") == -1) {
  672. r_permissions.push_back("android.permission.INTERNET");
  673. }
  674. }
  675. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  676. if (xr_mode_index == 1 /* XRMode.OVR */) {
  677. int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required
  678. if (hand_tracking_index > 0) {
  679. if (r_permissions.find("com.oculus.permission.HAND_TRACKING") == -1) {
  680. r_permissions.push_back("com.oculus.permission.HAND_TRACKING");
  681. }
  682. }
  683. }
  684. }
  685. void _fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {
  686. // Leaving the unused types commented because looking these constants up
  687. // again later would be annoying
  688. // const int CHUNK_AXML_FILE = 0x00080003;
  689. // const int CHUNK_RESOURCEIDS = 0x00080180;
  690. const int CHUNK_STRINGS = 0x001C0001;
  691. // const int CHUNK_XML_END_NAMESPACE = 0x00100101;
  692. const int CHUNK_XML_END_TAG = 0x00100103;
  693. // const int CHUNK_XML_START_NAMESPACE = 0x00100100;
  694. const int CHUNK_XML_START_TAG = 0x00100102;
  695. // const int CHUNK_XML_TEXT = 0x00100104;
  696. const int UTF8_FLAG = 0x00000100;
  697. Vector<String> string_table;
  698. uint32_t ofs = 8;
  699. uint32_t string_count = 0;
  700. //uint32_t styles_count = 0;
  701. uint32_t string_flags = 0;
  702. uint32_t string_data_offset = 0;
  703. //uint32_t styles_offset = 0;
  704. uint32_t string_table_begins = 0;
  705. uint32_t string_table_ends = 0;
  706. Vector<uint8_t> stable_extra;
  707. String version_name = p_preset->get("version/name");
  708. int version_code = p_preset->get("version/code");
  709. String package_name = p_preset->get("package/unique_name");
  710. int orientation = p_preset->get("screen/orientation");
  711. bool min_gles3 = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name") == "GLES3" &&
  712. !ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2");
  713. bool screen_support_small = p_preset->get("screen/support_small");
  714. bool screen_support_normal = p_preset->get("screen/support_normal");
  715. bool screen_support_large = p_preset->get("screen/support_large");
  716. bool screen_support_xlarge = p_preset->get("screen/support_xlarge");
  717. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  718. bool focus_awareness = p_preset->get("xr_features/focus_awareness");
  719. String plugins_names = get_plugins_names(get_enabled_plugins(p_preset));
  720. Vector<String> perms;
  721. // Write permissions into the perms variable.
  722. _get_permissions(p_preset, p_give_internet, perms);
  723. while (ofs < (uint32_t)p_manifest.size()) {
  724. uint32_t chunk = decode_uint32(&p_manifest[ofs]);
  725. uint32_t size = decode_uint32(&p_manifest[ofs + 4]);
  726. switch (chunk) {
  727. case CHUNK_STRINGS: {
  728. int iofs = ofs + 8;
  729. string_count = decode_uint32(&p_manifest[iofs]);
  730. //styles_count = decode_uint32(&p_manifest[iofs + 4]);
  731. string_flags = decode_uint32(&p_manifest[iofs + 8]);
  732. string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
  733. //styles_offset = decode_uint32(&p_manifest[iofs + 16]);
  734. /*
  735. printf("string count: %i\n",string_count);
  736. printf("flags: %i\n",string_flags);
  737. printf("sdata ofs: %i\n",string_data_offset);
  738. printf("styles ofs: %i\n",styles_offset);
  739. */
  740. uint32_t st_offset = iofs + 20;
  741. string_table.resize(string_count);
  742. uint32_t string_end = 0;
  743. string_table_begins = st_offset;
  744. for (uint32_t i = 0; i < string_count; i++) {
  745. uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
  746. string_at += st_offset + string_count * 4;
  747. ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table.");
  748. if (string_flags & UTF8_FLAG) {
  749. } else {
  750. uint32_t len = decode_uint16(&p_manifest[string_at]);
  751. Vector<CharType> ucstring;
  752. ucstring.resize(len + 1);
  753. for (uint32_t j = 0; j < len; j++) {
  754. uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
  755. ucstring.write[j] = c;
  756. }
  757. string_end = MAX(string_at + 2 + 2 * len, string_end);
  758. ucstring.write[len] = 0;
  759. string_table.write[i] = ucstring.ptr();
  760. }
  761. }
  762. for (uint32_t i = string_end; i < (ofs + size); i++) {
  763. stable_extra.push_back(p_manifest[i]);
  764. }
  765. string_table_ends = ofs + size;
  766. } break;
  767. case CHUNK_XML_START_TAG: {
  768. int iofs = ofs + 8;
  769. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  770. String tname = string_table[name];
  771. uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
  772. iofs += 28;
  773. bool is_focus_aware_metadata = false;
  774. for (uint32_t i = 0; i < attrcount; i++) {
  775. uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
  776. uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
  777. uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
  778. uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);
  779. const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid);
  780. String attrname = string_table[attr_name];
  781. const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : "";
  782. //replace project information
  783. if (tname == "manifest" && attrname == "package") {
  784. string_table.write[attr_value] = get_package_name(package_name);
  785. }
  786. if (tname == "manifest" && attrname == "versionCode") {
  787. encode_uint32(version_code, &p_manifest.write[iofs + 16]);
  788. }
  789. if (tname == "manifest" && attrname == "versionName") {
  790. if (attr_value == 0xFFFFFFFF) {
  791. WARN_PRINT("Version name in a resource, should be plain text");
  792. } else
  793. string_table.write[attr_value] = version_name;
  794. }
  795. if (tname == "instrumentation" && attrname == "targetPackage") {
  796. string_table.write[attr_value] = get_package_name(package_name);
  797. }
  798. if (tname == "activity" && attrname == "screenOrientation") {
  799. encode_uint32(orientation == 0 ? 0 : 1, &p_manifest.write[iofs + 16]);
  800. }
  801. if (tname == "supports-screens") {
  802. if (attrname == "smallScreens") {
  803. encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  804. } else if (attrname == "normalScreens") {
  805. encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  806. } else if (attrname == "largeScreens") {
  807. encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  808. } else if (attrname == "xlargeScreens") {
  809. encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  810. }
  811. }
  812. if (tname == "uses-feature" && attrname == "glEsVersion") {
  813. encode_uint32(min_gles3 ? 0x00030000 : 0x00020000, &p_manifest.write[iofs + 16]);
  814. }
  815. // FIXME: `attr_value != 0xFFFFFFFF` below added as a stopgap measure for GH-32553,
  816. // but the issue should be debugged further and properly addressed.
  817. if (tname == "meta-data" && attrname == "name" && value == "xr_mode_metadata_name") {
  818. // Update the meta-data 'android:name' attribute based on the selected XR mode.
  819. if (xr_mode_index == 1 /* XRMode.OVR */) {
  820. string_table.write[attr_value] = "com.samsung.android.vr.application.mode";
  821. }
  822. }
  823. if (tname == "meta-data" && attrname == "value" && value == "xr_mode_metadata_value") {
  824. // Update the meta-data 'android:value' attribute based on the selected XR mode.
  825. if (xr_mode_index == 1 /* XRMode.OVR */) {
  826. string_table.write[attr_value] = "vr_only";
  827. }
  828. }
  829. if (tname == "meta-data" && attrname == "value" && is_focus_aware_metadata) {
  830. // Update the focus awareness meta-data value
  831. encode_uint32(xr_mode_index == /* XRMode.OVR */ 1 && focus_awareness ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  832. }
  833. if (tname == "meta-data" && attrname == "value" && value == "plugins_value" && !plugins_names.empty()) {
  834. // Update the meta-data 'android:value' attribute with the list of enabled plugins.
  835. string_table.write[attr_value] = plugins_names;
  836. }
  837. is_focus_aware_metadata = tname == "meta-data" && attrname == "name" && value == "com.oculus.vr.focusaware";
  838. iofs += 20;
  839. }
  840. } break;
  841. case CHUNK_XML_END_TAG: {
  842. int iofs = ofs + 8;
  843. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  844. String tname = string_table[name];
  845. if (tname == "uses-feature") {
  846. Vector<String> feature_names;
  847. Vector<bool> feature_required_list;
  848. Vector<int> feature_versions;
  849. if (xr_mode_index == 1 /* XRMode.OVR */) {
  850. // Check for degrees of freedom
  851. int dof_index = p_preset->get("xr_features/degrees_of_freedom"); // 0: none, 1: 3dof and 6dof, 2: 6dof
  852. if (dof_index > 0) {
  853. feature_names.push_back("android.hardware.vr.headtracking");
  854. feature_required_list.push_back(dof_index == 2);
  855. feature_versions.push_back(1);
  856. }
  857. // Check for hand tracking
  858. int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required
  859. if (hand_tracking_index > 0) {
  860. feature_names.push_back("oculus.software.handtracking");
  861. feature_required_list.push_back(hand_tracking_index == 2);
  862. feature_versions.push_back(-1); // no version attribute should be added.
  863. }
  864. }
  865. if (feature_names.size() > 0) {
  866. ofs += 24; // skip over end tag
  867. // save manifest ending so we can restore it
  868. Vector<uint8_t> manifest_end;
  869. uint32_t manifest_cur_size = p_manifest.size();
  870. manifest_end.resize(p_manifest.size() - ofs);
  871. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  872. int32_t attr_name_string = string_table.find("name");
  873. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  874. int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android");
  875. if (ns_android_string == -1) {
  876. string_table.push_back("http://schemas.android.com/apk/res/android");
  877. ns_android_string = string_table.size() - 1;
  878. }
  879. int32_t attr_uses_feature_string = string_table.find("uses-feature");
  880. if (attr_uses_feature_string == -1) {
  881. string_table.push_back("uses-feature");
  882. attr_uses_feature_string = string_table.size() - 1;
  883. }
  884. int32_t attr_required_string = string_table.find("required");
  885. if (attr_required_string == -1) {
  886. string_table.push_back("required");
  887. attr_required_string = string_table.size() - 1;
  888. }
  889. for (int i = 0; i < feature_names.size(); i++) {
  890. String feature_name = feature_names[i];
  891. bool feature_required = feature_required_list[i];
  892. int feature_version = feature_versions[i];
  893. bool has_version_attribute = feature_version != -1;
  894. print_line("Adding feature " + feature_name);
  895. int32_t feature_string = string_table.find(feature_name);
  896. if (feature_string == -1) {
  897. string_table.push_back(feature_name);
  898. feature_string = string_table.size() - 1;
  899. }
  900. String required_value_string = feature_required ? "true" : "false";
  901. int32_t required_value = string_table.find(required_value_string);
  902. if (required_value == -1) {
  903. string_table.push_back(required_value_string);
  904. required_value = string_table.size() - 1;
  905. }
  906. int32_t attr_version_string = -1;
  907. int32_t version_value = -1;
  908. int tag_size;
  909. int attr_count;
  910. if (has_version_attribute) {
  911. attr_version_string = string_table.find("version");
  912. if (attr_version_string == -1) {
  913. string_table.push_back("version");
  914. attr_version_string = string_table.size() - 1;
  915. }
  916. version_value = string_table.find(itos(feature_version));
  917. if (version_value == -1) {
  918. string_table.push_back(itos(feature_version));
  919. version_value = string_table.size() - 1;
  920. }
  921. tag_size = 96; // node and three attrs + end node
  922. attr_count = 3;
  923. } else {
  924. tag_size = 76; // node and two attrs + end node
  925. attr_count = 2;
  926. }
  927. manifest_cur_size += tag_size + 24;
  928. p_manifest.resize(manifest_cur_size);
  929. // start tag
  930. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  931. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  932. encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size
  933. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  934. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  935. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  936. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  937. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  938. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  939. encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs
  940. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  941. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  942. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  943. // android:name attribute
  944. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  945. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  946. encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value
  947. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  948. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  949. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  950. encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  951. // android:required attribute
  952. encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns
  953. encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name'
  954. encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value
  955. encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size
  956. p_manifest.write[ofs + 70] = 0; // typedvalue_always0
  957. p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)
  958. encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference
  959. ofs += 76;
  960. if (has_version_attribute) {
  961. // android:version attribute
  962. encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns
  963. encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name'
  964. encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value
  965. encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size
  966. p_manifest.write[ofs + 14] = 0; // typedvalue_always0
  967. p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string)
  968. encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference
  969. ofs += 20;
  970. }
  971. // end tag
  972. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  973. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  974. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  975. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  976. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  977. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  978. encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
  979. ofs += 24;
  980. }
  981. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  982. ofs -= 24; // go back over back end
  983. }
  984. }
  985. if (tname == "manifest") {
  986. // save manifest ending so we can restore it
  987. Vector<uint8_t> manifest_end;
  988. uint32_t manifest_cur_size = p_manifest.size();
  989. manifest_end.resize(p_manifest.size() - ofs);
  990. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  991. int32_t attr_name_string = string_table.find("name");
  992. ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");
  993. int32_t ns_android_string = string_table.find("android");
  994. ERR_FAIL_COND_MSG(ns_android_string == -1, "Template does not have 'android' namespace.");
  995. int32_t attr_uses_permission_string = string_table.find("uses-permission");
  996. if (attr_uses_permission_string == -1) {
  997. string_table.push_back("uses-permission");
  998. attr_uses_permission_string = string_table.size() - 1;
  999. }
  1000. for (int i = 0; i < perms.size(); ++i) {
  1001. print_line("Adding permission " + perms[i]);
  1002. manifest_cur_size += 56 + 24; // node + end node
  1003. p_manifest.resize(manifest_cur_size);
  1004. // Add permission to the string pool
  1005. int32_t perm_string = string_table.find(perms[i]);
  1006. if (perm_string == -1) {
  1007. string_table.push_back(perms[i]);
  1008. perm_string = string_table.size() - 1;
  1009. }
  1010. // start tag
  1011. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  1012. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1013. encode_uint32(56, &p_manifest.write[ofs + 4]); // size
  1014. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1015. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1016. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1017. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1018. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  1019. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  1020. encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
  1021. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  1022. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  1023. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  1024. // attribute
  1025. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  1026. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  1027. encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
  1028. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  1029. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  1030. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  1031. encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  1032. ofs += 56;
  1033. // end tag
  1034. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  1035. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  1036. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  1037. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  1038. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  1039. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  1040. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  1041. ofs += 24;
  1042. }
  1043. // copy footer back in
  1044. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  1045. }
  1046. } break;
  1047. }
  1048. ofs += size;
  1049. }
  1050. //create new andriodmanifest binary
  1051. Vector<uint8_t> ret;
  1052. ret.resize(string_table_begins + string_table.size() * 4);
  1053. for (uint32_t i = 0; i < string_table_begins; i++) {
  1054. ret.write[i] = p_manifest[i];
  1055. }
  1056. ofs = 0;
  1057. for (int i = 0; i < string_table.size(); i++) {
  1058. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1059. ofs += string_table[i].length() * 2 + 2 + 2;
  1060. }
  1061. ret.resize(ret.size() + ofs);
  1062. string_data_offset = ret.size() - ofs;
  1063. uint8_t *chars = &ret.write[string_data_offset];
  1064. for (int i = 0; i < string_table.size(); i++) {
  1065. String s = string_table[i];
  1066. encode_uint16(s.length(), chars);
  1067. chars += 2;
  1068. for (int j = 0; j < s.length(); j++) {
  1069. encode_uint16(s[j], chars);
  1070. chars += 2;
  1071. }
  1072. encode_uint16(0, chars);
  1073. chars += 2;
  1074. }
  1075. for (int i = 0; i < stable_extra.size(); i++) {
  1076. ret.push_back(stable_extra[i]);
  1077. }
  1078. //pad
  1079. while (ret.size() % 4)
  1080. ret.push_back(0);
  1081. uint32_t new_stable_end = ret.size();
  1082. uint32_t extra = (p_manifest.size() - string_table_ends);
  1083. ret.resize(new_stable_end + extra);
  1084. for (uint32_t i = 0; i < extra; i++)
  1085. ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
  1086. while (ret.size() % 4)
  1087. ret.push_back(0);
  1088. encode_uint32(ret.size(), &ret.write[4]); //update new file size
  1089. encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
  1090. encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
  1091. encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset
  1092. p_manifest = ret;
  1093. }
  1094. static String _parse_string(const uint8_t *p_bytes, bool p_utf8) {
  1095. uint32_t offset = 0;
  1096. uint32_t len = 0;
  1097. if (p_utf8) {
  1098. uint8_t byte = p_bytes[offset];
  1099. if (byte & 0x80)
  1100. offset += 2;
  1101. else
  1102. offset += 1;
  1103. byte = p_bytes[offset];
  1104. offset++;
  1105. if (byte & 0x80) {
  1106. len = byte & 0x7F;
  1107. len = (len << 8) + p_bytes[offset];
  1108. offset++;
  1109. } else {
  1110. len = byte;
  1111. }
  1112. } else {
  1113. len = decode_uint16(&p_bytes[offset]);
  1114. offset += 2;
  1115. if (len & 0x8000) {
  1116. len &= 0x7FFF;
  1117. len = (len << 16) + decode_uint16(&p_bytes[offset]);
  1118. offset += 2;
  1119. }
  1120. }
  1121. if (p_utf8) {
  1122. Vector<uint8_t> str8;
  1123. str8.resize(len + 1);
  1124. for (uint32_t i = 0; i < len; i++) {
  1125. str8.write[i] = p_bytes[offset + i];
  1126. }
  1127. str8.write[len] = 0;
  1128. String str;
  1129. str.parse_utf8((const char *)str8.ptr());
  1130. return str;
  1131. } else {
  1132. String str;
  1133. for (uint32_t i = 0; i < len; i++) {
  1134. CharType c = decode_uint16(&p_bytes[offset + i * 2]);
  1135. if (c == 0)
  1136. break;
  1137. str += String::chr(c);
  1138. }
  1139. return str;
  1140. }
  1141. }
  1142. void _fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &r_manifest) {
  1143. const int UTF8_FLAG = 0x00000100;
  1144. uint32_t string_block_len = decode_uint32(&r_manifest[16]);
  1145. uint32_t string_count = decode_uint32(&r_manifest[20]);
  1146. uint32_t string_flags = decode_uint32(&r_manifest[28]);
  1147. const uint32_t string_table_begins = 40;
  1148. Vector<String> string_table;
  1149. String package_name = p_preset->get("package/name");
  1150. for (uint32_t i = 0; i < string_count; i++) {
  1151. uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]);
  1152. offset += string_table_begins + string_count * 4;
  1153. String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG);
  1154. if (str.begins_with("godot-project-name")) {
  1155. if (str == "godot-project-name") {
  1156. //project name
  1157. str = get_project_name(package_name);
  1158. } else {
  1159. String lang = str.substr(str.find_last("-") + 1, str.length()).replace("-", "_");
  1160. String prop = "application/config/name_" + lang;
  1161. if (ProjectSettings::get_singleton()->has_setting(prop)) {
  1162. str = ProjectSettings::get_singleton()->get(prop);
  1163. } else {
  1164. str = get_project_name(package_name);
  1165. }
  1166. }
  1167. }
  1168. string_table.push_back(str);
  1169. }
  1170. //write a new string table, but use 16 bits
  1171. Vector<uint8_t> ret;
  1172. ret.resize(string_table_begins + string_table.size() * 4);
  1173. for (uint32_t i = 0; i < string_table_begins; i++) {
  1174. ret.write[i] = r_manifest[i];
  1175. }
  1176. int ofs = 0;
  1177. for (int i = 0; i < string_table.size(); i++) {
  1178. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  1179. ofs += string_table[i].length() * 2 + 2 + 2;
  1180. }
  1181. ret.resize(ret.size() + ofs);
  1182. uint8_t *chars = &ret.write[ret.size() - ofs];
  1183. for (int i = 0; i < string_table.size(); i++) {
  1184. String s = string_table[i];
  1185. encode_uint16(s.length(), chars);
  1186. chars += 2;
  1187. for (int j = 0; j < s.length(); j++) {
  1188. encode_uint16(s[j], chars);
  1189. chars += 2;
  1190. }
  1191. encode_uint16(0, chars);
  1192. chars += 2;
  1193. }
  1194. //pad
  1195. while (ret.size() % 4)
  1196. ret.push_back(0);
  1197. //change flags to not use utf8
  1198. encode_uint32(string_flags & ~0x100, &ret.write[28]);
  1199. //change length
  1200. encode_uint32(ret.size() - 12, &ret.write[16]);
  1201. //append the rest...
  1202. int rest_from = 12 + string_block_len;
  1203. int rest_to = ret.size();
  1204. int rest_len = (r_manifest.size() - rest_from);
  1205. ret.resize(ret.size() + (r_manifest.size() - rest_from));
  1206. for (int i = 0; i < rest_len; i++) {
  1207. ret.write[rest_to + i] = r_manifest[rest_from + i];
  1208. }
  1209. //finally update the size
  1210. encode_uint32(ret.size(), &ret.write[4]);
  1211. r_manifest = ret;
  1212. //printf("end\n");
  1213. }
  1214. void _process_launcher_icons(const String &p_processing_file_name, const Ref<Image> &p_source_image, const LauncherIcon p_icon, Vector<uint8_t> &p_data) {
  1215. if (p_processing_file_name == p_icon.export_path) {
  1216. Ref<Image> working_image = p_source_image;
  1217. if (p_source_image->get_width() != p_icon.dimensions || p_source_image->get_height() != p_icon.dimensions) {
  1218. working_image = p_source_image->duplicate();
  1219. working_image->resize(p_icon.dimensions, p_icon.dimensions, Image::Interpolation::INTERPOLATE_LANCZOS);
  1220. }
  1221. PoolVector<uint8_t> png_buffer;
  1222. Error err = PNGDriverCommon::image_to_png(working_image, png_buffer);
  1223. if (err == OK) {
  1224. p_data.resize(png_buffer.size());
  1225. memcpy(p_data.ptrw(), png_buffer.read().ptr(), p_data.size());
  1226. } else {
  1227. String err_str = String("Failed to convert resized icon (") + p_processing_file_name + ") to png.";
  1228. WARN_PRINT(err_str.utf8().get_data());
  1229. }
  1230. }
  1231. }
  1232. static Vector<String> get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
  1233. Vector<String> abis = get_abis();
  1234. Vector<String> enabled_abis;
  1235. for (int i = 0; i < abis.size(); ++i) {
  1236. bool is_enabled = p_preset->get("architectures/" + abis[i]);
  1237. if (is_enabled) {
  1238. enabled_abis.push_back(abis[i]);
  1239. }
  1240. }
  1241. return enabled_abis;
  1242. }
  1243. public:
  1244. typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
  1245. public:
  1246. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  1247. String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
  1248. if (driver == "GLES2") {
  1249. r_features->push_back("etc");
  1250. } else if (driver == "GLES3") {
  1251. r_features->push_back("etc2");
  1252. if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
  1253. r_features->push_back("etc");
  1254. }
  1255. }
  1256. Vector<String> abis = get_enabled_abis(p_preset);
  1257. for (int i = 0; i < abis.size(); ++i) {
  1258. r_features->push_back(abis[i]);
  1259. }
  1260. }
  1261. virtual void get_export_options(List<ExportOption> *r_options) {
  1262. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true));
  1263. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,Oculus Mobile VR"), 0));
  1264. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/degrees_of_freedom", PROPERTY_HINT_ENUM, "None,3DOF and 6DOF,6DOF"), 0));
  1265. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking", PROPERTY_HINT_ENUM, "None,Optional,Required"), 0));
  1266. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "xr_features/focus_awareness"), false));
  1267. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), false));
  1268. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1269. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  1270. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_template/use_custom_build"), false));
  1271. Vector<PluginConfig> plugins_configs = get_plugins();
  1272. for (int i = 0; i < plugins_configs.size(); i++) {
  1273. print_verbose("Found Android plugin " + plugins_configs[i].name);
  1274. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "plugins/" + plugins_configs[i].name), false));
  1275. }
  1276. plugins_changed = false;
  1277. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
  1278. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
  1279. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
  1280. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
  1281. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
  1282. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
  1283. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
  1284. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "screen/orientation", PROPERTY_HINT_ENUM, "Landscape,Portrait"), 0));
  1285. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
  1286. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
  1287. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
  1288. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
  1289. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/opengl_debug"), false));
  1290. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icon_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1291. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_foreground_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1292. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_background_option, PROPERTY_HINT_FILE, "*.png"), ""));
  1293. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
  1294. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
  1295. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
  1296. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
  1297. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
  1298. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
  1299. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
  1300. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
  1301. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));
  1302. Vector<String> abis = get_abis();
  1303. for (int i = 0; i < abis.size(); ++i) {
  1304. String abi = abis[i];
  1305. bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a");
  1306. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default));
  1307. }
  1308. r_options->push_back(ExportOption(PropertyInfo(Variant::POOL_STRING_ARRAY, "permissions/custom_permissions"), PoolStringArray()));
  1309. const char **perms = android_perms;
  1310. while (*perms) {
  1311. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false));
  1312. perms++;
  1313. }
  1314. }
  1315. virtual String get_name() const {
  1316. return "Android";
  1317. }
  1318. virtual String get_os_name() const {
  1319. return "Android";
  1320. }
  1321. virtual Ref<Texture> get_logo() const {
  1322. return logo;
  1323. }
  1324. virtual bool should_update_export_options() {
  1325. bool export_options_changed = plugins_changed;
  1326. if (export_options_changed) {
  1327. // don't clear unless we're reporting true, to avoid race
  1328. plugins_changed = false;
  1329. }
  1330. return export_options_changed;
  1331. }
  1332. virtual bool poll_export() {
  1333. bool dc = devices_changed;
  1334. if (dc) {
  1335. // don't clear unless we're reporting true, to avoid race
  1336. devices_changed = false;
  1337. }
  1338. return dc;
  1339. }
  1340. virtual int get_options_count() const {
  1341. device_lock->lock();
  1342. int dc = devices.size();
  1343. device_lock->unlock();
  1344. return dc;
  1345. }
  1346. virtual String get_options_tooltip() const {
  1347. return TTR("Select device from the list");
  1348. }
  1349. virtual String get_option_label(int p_index) const {
  1350. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1351. device_lock->lock();
  1352. String s = devices[p_index].name;
  1353. device_lock->unlock();
  1354. return s;
  1355. }
  1356. virtual String get_option_tooltip(int p_index) const {
  1357. ERR_FAIL_INDEX_V(p_index, devices.size(), "");
  1358. device_lock->lock();
  1359. String s = devices[p_index].description;
  1360. if (devices.size() == 1) {
  1361. // Tooltip will be:
  1362. // Name
  1363. // Description
  1364. s = devices[p_index].name + "\n\n" + s;
  1365. }
  1366. device_lock->unlock();
  1367. return s;
  1368. }
  1369. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
  1370. ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
  1371. String can_export_error;
  1372. bool can_export_missing_templates;
  1373. if (!can_export(p_preset, can_export_error, can_export_missing_templates)) {
  1374. EditorNode::add_io_error(can_export_error);
  1375. return ERR_UNCONFIGURED;
  1376. }
  1377. device_lock->lock();
  1378. EditorProgress ep("run", "Running on " + devices[p_device].name, 3);
  1379. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  1380. // Export_temp APK.
  1381. if (ep.step("Exporting APK...", 0)) {
  1382. device_lock->unlock();
  1383. return ERR_SKIP;
  1384. }
  1385. const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
  1386. const bool use_reverse = devices[p_device].api_level >= 21;
  1387. if (use_reverse)
  1388. p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
  1389. String tmp_export_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport.apk");
  1390. #define CLEANUP_AND_RETURN(m_err) \
  1391. { \
  1392. DirAccess::remove_file_or_error(tmp_export_path); \
  1393. device_lock->unlock(); \
  1394. return m_err; \
  1395. }
  1396. // Export to temporary APK before sending to device.
  1397. Error err = export_project(p_preset, true, tmp_export_path, p_debug_flags);
  1398. if (err != OK) {
  1399. CLEANUP_AND_RETURN(err);
  1400. }
  1401. List<String> args;
  1402. int rv;
  1403. bool remove_prev = p_preset->get("one_click_deploy/clear_previous_install");
  1404. String version_name = p_preset->get("version/name");
  1405. String package_name = p_preset->get("package/unique_name");
  1406. if (remove_prev) {
  1407. if (ep.step("Uninstalling...", 1)) {
  1408. CLEANUP_AND_RETURN(ERR_SKIP);
  1409. }
  1410. print_line("Uninstalling previous version: " + devices[p_device].name);
  1411. args.push_back("-s");
  1412. args.push_back(devices[p_device].id);
  1413. args.push_back("uninstall");
  1414. args.push_back(get_package_name(package_name));
  1415. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1416. }
  1417. print_line("Installing to device (please wait...): " + devices[p_device].name);
  1418. if (ep.step("Installing to device, please wait...", 2)) {
  1419. CLEANUP_AND_RETURN(ERR_SKIP);
  1420. }
  1421. args.clear();
  1422. args.push_back("-s");
  1423. args.push_back(devices[p_device].id);
  1424. args.push_back("install");
  1425. args.push_back("-r");
  1426. args.push_back(tmp_export_path);
  1427. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1428. if (err || rv != 0) {
  1429. EditorNode::add_io_error("Could not install to device.");
  1430. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  1431. }
  1432. if (use_remote) {
  1433. if (use_reverse) {
  1434. static const char *const msg = "--- Device API >= 21; debugging over USB ---";
  1435. EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
  1436. print_line(String(msg).to_upper());
  1437. args.clear();
  1438. args.push_back("-s");
  1439. args.push_back(devices[p_device].id);
  1440. args.push_back("reverse");
  1441. args.push_back("--remove-all");
  1442. OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1443. if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) {
  1444. int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port");
  1445. args.clear();
  1446. args.push_back("-s");
  1447. args.push_back(devices[p_device].id);
  1448. args.push_back("reverse");
  1449. args.push_back("tcp:" + itos(dbg_port));
  1450. args.push_back("tcp:" + itos(dbg_port));
  1451. OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1452. print_line("Reverse result: " + itos(rv));
  1453. }
  1454. if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) {
  1455. int fs_port = EditorSettings::get_singleton()->get("filesystem/file_server/port");
  1456. args.clear();
  1457. args.push_back("-s");
  1458. args.push_back(devices[p_device].id);
  1459. args.push_back("reverse");
  1460. args.push_back("tcp:" + itos(fs_port));
  1461. args.push_back("tcp:" + itos(fs_port));
  1462. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1463. print_line("Reverse result2: " + itos(rv));
  1464. }
  1465. } else {
  1466. static const char *const msg = "--- Device API < 21; debugging over Wi-Fi ---";
  1467. EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
  1468. print_line(String(msg).to_upper());
  1469. }
  1470. }
  1471. if (ep.step("Running on device...", 3)) {
  1472. CLEANUP_AND_RETURN(ERR_SKIP);
  1473. }
  1474. args.clear();
  1475. args.push_back("-s");
  1476. args.push_back(devices[p_device].id);
  1477. args.push_back("shell");
  1478. args.push_back("am");
  1479. args.push_back("start");
  1480. if ((bool)EditorSettings::get_singleton()->get("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17
  1481. args.push_back("--user");
  1482. args.push_back("0");
  1483. }
  1484. args.push_back("-a");
  1485. args.push_back("android.intent.action.MAIN");
  1486. args.push_back("-n");
  1487. args.push_back(get_package_name(package_name) + "/com.godot.game.GodotApp");
  1488. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1489. if (err || rv != 0) {
  1490. EditorNode::add_io_error("Could not execute on device.");
  1491. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  1492. }
  1493. CLEANUP_AND_RETURN(OK);
  1494. #undef CLEANUP_AND_RETURN
  1495. }
  1496. virtual Ref<Texture> get_run_icon() const {
  1497. return run_icon;
  1498. }
  1499. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  1500. String err;
  1501. bool valid = false;
  1502. // Look for export templates (first official, and if defined custom templates).
  1503. if (!bool(p_preset->get("custom_template/use_custom_build"))) {
  1504. String template_err;
  1505. bool dvalid = false;
  1506. bool rvalid = false;
  1507. if (p_preset->get("custom_template/debug") != "") {
  1508. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  1509. if (!dvalid) {
  1510. template_err += TTR("Custom debug template not found.") + "\n";
  1511. }
  1512. } else {
  1513. dvalid = exists_export_template("android_debug.apk", &template_err);
  1514. }
  1515. if (p_preset->get("custom_template/release") != "") {
  1516. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  1517. if (!rvalid) {
  1518. template_err += TTR("Custom release template not found.") + "\n";
  1519. }
  1520. } else {
  1521. rvalid = exists_export_template("android_release.apk", &template_err);
  1522. }
  1523. valid = dvalid || rvalid;
  1524. if (!valid) {
  1525. err += template_err;
  1526. }
  1527. } else {
  1528. valid = exists_export_template("android_source.zip", &err);
  1529. }
  1530. r_missing_templates = !valid;
  1531. // Validate the rest of the configuration.
  1532. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  1533. if (!FileAccess::exists(adb)) {
  1534. valid = false;
  1535. err += TTR("ADB executable not configured in the Editor Settings.") + "\n";
  1536. }
  1537. String js = EditorSettings::get_singleton()->get("export/android/jarsigner");
  1538. if (!FileAccess::exists(js)) {
  1539. valid = false;
  1540. err += TTR("OpenJDK jarsigner not configured in the Editor Settings.") + "\n";
  1541. }
  1542. String dk = p_preset->get("keystore/debug");
  1543. if (!FileAccess::exists(dk)) {
  1544. dk = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  1545. if (!FileAccess::exists(dk)) {
  1546. valid = false;
  1547. err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";
  1548. }
  1549. }
  1550. String rk = p_preset->get("keystore/release");
  1551. if (!rk.empty() && !FileAccess::exists(rk)) {
  1552. valid = false;
  1553. err += TTR("Release keystore incorrectly configured in the export preset.") + "\n";
  1554. }
  1555. if (bool(p_preset->get("custom_template/use_custom_build"))) {
  1556. String sdk_path = EditorSettings::get_singleton()->get("export/android/custom_build_sdk_path");
  1557. if (sdk_path == "") {
  1558. err += TTR("Custom build requires a valid Android SDK path in Editor Settings.") + "\n";
  1559. valid = false;
  1560. } else {
  1561. Error errn;
  1562. DirAccessRef da = DirAccess::open(sdk_path.plus_file("platform-tools"), &errn);
  1563. if (errn != OK) {
  1564. err += TTR("Invalid Android SDK path for custom build in Editor Settings.") + "\n";
  1565. valid = false;
  1566. }
  1567. }
  1568. if (!FileAccess::exists("res://android/build/build.gradle")) {
  1569. err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n";
  1570. valid = false;
  1571. }
  1572. }
  1573. bool apk_expansion = p_preset->get("apk_expansion/enable");
  1574. if (apk_expansion) {
  1575. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  1576. if (apk_expansion_pkey == "") {
  1577. valid = false;
  1578. err += TTR("Invalid public key for APK expansion.") + "\n";
  1579. }
  1580. }
  1581. String pn = p_preset->get("package/unique_name");
  1582. String pn_err;
  1583. if (!is_package_name_valid(get_package_name(pn), &pn_err)) {
  1584. valid = false;
  1585. err += TTR("Invalid package name:") + " " + pn_err + "\n";
  1586. }
  1587. String etc_error = test_etc2();
  1588. if (etc_error != String()) {
  1589. valid = false;
  1590. err += etc_error;
  1591. }
  1592. // The GodotPaymentV3 module was converted to the external GodotGooglePlayBilling plugin in Godot 3.2.2,
  1593. // this check helps users to notice the change to ensure that they change their settings.
  1594. String modules = ProjectSettings::get_singleton()->get("android/modules");
  1595. if (modules.find("org/godotengine/godot/GodotPaymentV3") != -1) {
  1596. bool godot_google_play_billing_enabled = p_preset->get("plugins/GodotGooglePlayBilling");
  1597. if (!godot_google_play_billing_enabled) {
  1598. valid = false;
  1599. err += TTR("Invalid \"GodotPaymentV3\" module included in the \"android/modules\" project setting (changed in Godot 3.2.2).\n"
  1600. "Replace it with the first-party \"GodotGooglePlayBilling\" plugin.\n"
  1601. "Note that the singleton was also renamed from \"GodotPayments\" to \"GodotGooglePlayBilling\".");
  1602. err += "\n";
  1603. }
  1604. }
  1605. // Ensure that `Use Custom Build` is enabled if a plugin is selected.
  1606. String enabled_plugins_names = get_plugins_names(get_enabled_plugins(p_preset));
  1607. bool custom_build_enabled = p_preset->get("custom_template/use_custom_build");
  1608. if (!enabled_plugins_names.empty() && !custom_build_enabled) {
  1609. valid = false;
  1610. err += TTR("\"Use Custom Build\" must be enabled to use the plugins.");
  1611. err += "\n";
  1612. }
  1613. // Validate the Xr features are properly populated
  1614. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  1615. int degrees_of_freedom = p_preset->get("xr_features/degrees_of_freedom");
  1616. int hand_tracking = p_preset->get("xr_features/hand_tracking");
  1617. bool focus_awareness = p_preset->get("xr_features/focus_awareness");
  1618. if (xr_mode_index != /* XRMode.OVR*/ 1) {
  1619. if (degrees_of_freedom > 0) {
  1620. valid = false;
  1621. err += TTR("\"Degrees Of Freedom\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
  1622. err += "\n";
  1623. }
  1624. if (hand_tracking > 0) {
  1625. valid = false;
  1626. err += TTR("\"Hand Tracking\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
  1627. err += "\n";
  1628. }
  1629. if (focus_awareness) {
  1630. valid = false;
  1631. err += TTR("\"Focus Awareness\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
  1632. err += "\n";
  1633. }
  1634. }
  1635. r_error = err;
  1636. return valid;
  1637. }
  1638. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  1639. List<String> list;
  1640. list.push_back("apk");
  1641. return list;
  1642. }
  1643. void _update_custom_build_project() {
  1644. DirAccessRef da = DirAccess::open("res://android");
  1645. ERR_FAIL_COND_MSG(!da, "Cannot open directory 'res://android'.");
  1646. Map<String, List<String> > directory_paths;
  1647. Map<String, List<String> > manifest_sections;
  1648. Map<String, List<String> > gradle_sections;
  1649. da->list_dir_begin();
  1650. String d = da->get_next();
  1651. while (d != String()) {
  1652. if (!d.begins_with(".") && d != "build" && da->current_is_dir()) { //a dir and not the build dir
  1653. //add directories found
  1654. DirAccessRef ds = DirAccess::open(String("res://android").plus_file(d));
  1655. if (ds) {
  1656. ds->list_dir_begin();
  1657. String sd = ds->get_next();
  1658. while (sd != String()) {
  1659. if (!sd.begins_with(".") && ds->current_is_dir()) {
  1660. String key = sd.to_upper();
  1661. if (!directory_paths.has(key)) {
  1662. directory_paths[key] = List<String>();
  1663. }
  1664. String path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android").plus_file(d).plus_file(sd);
  1665. directory_paths[key].push_back(path);
  1666. print_line("Add: " + sd + ":" + path);
  1667. }
  1668. sd = ds->get_next();
  1669. }
  1670. ds->list_dir_end();
  1671. }
  1672. //parse manifest
  1673. {
  1674. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("AndroidManifest.conf"), FileAccess::READ);
  1675. if (f) {
  1676. String section;
  1677. while (!f->eof_reached()) {
  1678. String l = f->get_line();
  1679. String k = l.strip_edges();
  1680. if (k.begins_with("[")) {
  1681. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  1682. print_line("Section: " + section);
  1683. } else if (k != String()) {
  1684. if (!manifest_sections.has(section)) {
  1685. manifest_sections[section] = List<String>();
  1686. }
  1687. manifest_sections[section].push_back(l);
  1688. }
  1689. }
  1690. f->close();
  1691. }
  1692. }
  1693. //parse gradle
  1694. {
  1695. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("gradle.conf"), FileAccess::READ);
  1696. if (f) {
  1697. String section;
  1698. while (!f->eof_reached()) {
  1699. String l = f->get_line().strip_edges();
  1700. String k = l.strip_edges();
  1701. if (k.begins_with("[")) {
  1702. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  1703. print_line("Section: " + section);
  1704. } else if (k != String()) {
  1705. if (!gradle_sections.has(section)) {
  1706. gradle_sections[section] = List<String>();
  1707. }
  1708. gradle_sections[section].push_back(l);
  1709. }
  1710. }
  1711. }
  1712. }
  1713. }
  1714. d = da->get_next();
  1715. }
  1716. da->list_dir_end();
  1717. { //fix gradle build
  1718. String new_file;
  1719. {
  1720. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::READ);
  1721. if (f) {
  1722. while (!f->eof_reached()) {
  1723. String l = f->get_line();
  1724. bool append_line = false;
  1725. if (l.begins_with("//CHUNK_")) {
  1726. String text = l.replace_first("//CHUNK_", "");
  1727. int begin_pos = text.find("_BEGIN");
  1728. if (begin_pos != -1) {
  1729. text = text.substr(0, begin_pos);
  1730. text = text.to_upper(); //just in case
  1731. String end_marker = "//CHUNK_" + text + "_END";
  1732. size_t pos = f->get_position();
  1733. bool found = false;
  1734. while (!f->eof_reached()) {
  1735. l = f->get_line();
  1736. if (l.begins_with(end_marker)) {
  1737. found = true;
  1738. break;
  1739. }
  1740. }
  1741. new_file += "//CHUNK_" + text + "_BEGIN\n";
  1742. if (!found) {
  1743. ERR_PRINTS("No end marker found in build.gradle for chunk: " + text);
  1744. f->seek(pos);
  1745. } else {
  1746. //add chunk lines
  1747. if (gradle_sections.has(text)) {
  1748. for (List<String>::Element *E = gradle_sections[text].front(); E; E = E->next()) {
  1749. new_file += E->get() + "\n";
  1750. }
  1751. }
  1752. if (f->eof_reached()) {
  1753. new_file += end_marker;
  1754. } else {
  1755. new_file += end_marker + "\n";
  1756. }
  1757. }
  1758. } else {
  1759. append_line = true;
  1760. }
  1761. } else if (l.begins_with("//DIR_")) {
  1762. String text = l.replace_first("//DIR_", "");
  1763. int begin_pos = text.find("_BEGIN");
  1764. if (begin_pos != -1) {
  1765. text = text.substr(0, begin_pos);
  1766. text = text.to_upper(); //just in case
  1767. String end_marker = "//DIR_" + text + "_END";
  1768. size_t pos = f->get_position();
  1769. bool found = false;
  1770. while (!f->eof_reached()) {
  1771. l = f->get_line();
  1772. if (l.begins_with(end_marker)) {
  1773. found = true;
  1774. break;
  1775. }
  1776. }
  1777. new_file += "//DIR_" + text + "_BEGIN\n";
  1778. if (!found) {
  1779. ERR_PRINTS("No end marker found in build.gradle for dir: " + text);
  1780. f->seek(pos);
  1781. } else {
  1782. //add chunk lines
  1783. if (directory_paths.has(text)) {
  1784. for (List<String>::Element *E = directory_paths[text].front(); E; E = E->next()) {
  1785. new_file += ",'" + E->get().replace("'", "\'") + "'";
  1786. new_file += "\n";
  1787. }
  1788. }
  1789. if (f->eof_reached()) {
  1790. new_file += end_marker;
  1791. } else {
  1792. new_file += end_marker + "\n";
  1793. }
  1794. }
  1795. } else {
  1796. append_line = true;
  1797. }
  1798. } else {
  1799. append_line = true;
  1800. }
  1801. if (append_line) {
  1802. if (f->eof_reached()) {
  1803. new_file += l;
  1804. } else {
  1805. new_file += l + "\n";
  1806. }
  1807. }
  1808. }
  1809. }
  1810. }
  1811. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::WRITE);
  1812. f->store_string(new_file);
  1813. f->close();
  1814. }
  1815. { //fix manifest
  1816. String new_file;
  1817. {
  1818. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::READ);
  1819. if (f) {
  1820. while (!f->eof_reached()) {
  1821. String l = f->get_line();
  1822. bool append_line = false;
  1823. if (l.begins_with("<!--CHUNK_")) {
  1824. String text = l.replace_first("<!--CHUNK_", "");
  1825. int begin_pos = text.find("_BEGIN-->");
  1826. if (begin_pos != -1) {
  1827. text = text.substr(0, begin_pos);
  1828. text = text.to_upper(); //just in case
  1829. String end_marker = "<!--CHUNK_" + text + "_END-->";
  1830. size_t pos = f->get_position();
  1831. bool found = false;
  1832. while (!f->eof_reached()) {
  1833. l = f->get_line();
  1834. if (l.begins_with(end_marker)) {
  1835. found = true;
  1836. break;
  1837. }
  1838. }
  1839. new_file += "<!--CHUNK_" + text + "_BEGIN-->\n";
  1840. if (!found) {
  1841. ERR_PRINTS("No end marker found in AndroidManifest.xml for chunk: " + text);
  1842. f->seek(pos);
  1843. } else {
  1844. //add chunk lines
  1845. if (manifest_sections.has(text)) {
  1846. for (List<String>::Element *E = manifest_sections[text].front(); E; E = E->next()) {
  1847. new_file += E->get() + "\n";
  1848. }
  1849. }
  1850. if (f->eof_reached()) {
  1851. new_file += end_marker;
  1852. } else {
  1853. new_file += end_marker + "\n";
  1854. }
  1855. }
  1856. } else {
  1857. append_line = true;
  1858. }
  1859. } else if (l.strip_edges().begins_with("<application")) {
  1860. String last_tag = "android:icon=\"@mipmap/icon\"";
  1861. int last_tag_pos = l.find(last_tag);
  1862. if (last_tag_pos == -1) {
  1863. ERR_PRINTS("Not adding application attributes as the expected tag was not found in '<application': " + last_tag);
  1864. append_line = true;
  1865. } else {
  1866. String base = l.substr(0, last_tag_pos + last_tag.length());
  1867. if (manifest_sections.has("application_attribs")) {
  1868. for (List<String>::Element *E = manifest_sections["application_attribs"].front(); E; E = E->next()) {
  1869. String to_add = E->get().strip_edges();
  1870. base += " " + to_add + " ";
  1871. }
  1872. }
  1873. base += ">\n";
  1874. new_file += base;
  1875. }
  1876. } else {
  1877. append_line = true;
  1878. }
  1879. if (append_line) {
  1880. new_file += l;
  1881. if (!f->eof_reached()) {
  1882. new_file += "\n";
  1883. }
  1884. }
  1885. }
  1886. }
  1887. }
  1888. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::WRITE);
  1889. f->store_string(new_file);
  1890. f->close();
  1891. }
  1892. }
  1893. inline bool is_clean_build_required(Vector<PluginConfig> enabled_plugins) {
  1894. String plugin_names = get_plugins_names(enabled_plugins);
  1895. bool first_build = last_custom_build_time == 0;
  1896. bool have_plugins_changed = false;
  1897. if (!first_build) {
  1898. have_plugins_changed = plugin_names != last_plugin_names;
  1899. if (!have_plugins_changed) {
  1900. for (int i = 0; i < enabled_plugins.size(); i++) {
  1901. if (enabled_plugins.get(i).last_updated > last_custom_build_time) {
  1902. have_plugins_changed = true;
  1903. break;
  1904. }
  1905. }
  1906. }
  1907. }
  1908. last_custom_build_time = OS::get_singleton()->get_unix_time();
  1909. last_plugin_names = plugin_names;
  1910. return have_plugins_changed || first_build;
  1911. }
  1912. Error get_command_line_flags(const Ref<EditorExportPreset> &p_preset, const String &p_path, int p_flags, Vector<uint8_t> &r_command_line_flags) {
  1913. String cmdline = p_preset->get("command_line/extra_args");
  1914. Vector<String> command_line_strings = cmdline.strip_edges().split(" ");
  1915. for (int i = 0; i < command_line_strings.size(); i++) {
  1916. if (command_line_strings[i].strip_edges().length() == 0) {
  1917. command_line_strings.remove(i);
  1918. i--;
  1919. }
  1920. }
  1921. gen_export_flags(command_line_strings, p_flags);
  1922. bool apk_expansion = p_preset->get("apk_expansion/enable");
  1923. if (apk_expansion) {
  1924. int version_code = p_preset->get("version/code");
  1925. String package_name = p_preset->get("package/unique_name");
  1926. String apk_file_name = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
  1927. String fullpath = p_path.get_base_dir().plus_file(apk_file_name);
  1928. String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");
  1929. Error err = save_pack(p_preset, fullpath);
  1930. if (err != OK) {
  1931. EditorNode::add_io_error("Could not write expansion package file: " + apk_file_name);
  1932. return err;
  1933. }
  1934. command_line_strings.push_back("--use_apk_expansion");
  1935. command_line_strings.push_back("--apk_expansion_md5");
  1936. command_line_strings.push_back(FileAccess::get_md5(fullpath));
  1937. command_line_strings.push_back("--apk_expansion_key");
  1938. command_line_strings.push_back(apk_expansion_public_key.strip_edges());
  1939. }
  1940. int xr_mode_index = p_preset->get("xr_features/xr_mode");
  1941. if (xr_mode_index == 1) {
  1942. command_line_strings.push_back("--xr_mode_ovr");
  1943. } else { // XRMode.REGULAR is the default.
  1944. command_line_strings.push_back("--xr_mode_regular");
  1945. }
  1946. bool use_32_bit_framebuffer = p_preset->get("graphics/32_bits_framebuffer");
  1947. if (use_32_bit_framebuffer) {
  1948. command_line_strings.push_back("--use_depth_32");
  1949. }
  1950. bool immersive = p_preset->get("screen/immersive_mode");
  1951. if (immersive) {
  1952. command_line_strings.push_back("--use_immersive");
  1953. }
  1954. bool debug_opengl = p_preset->get("screen/opengl_debug");
  1955. if (debug_opengl) {
  1956. command_line_strings.push_back("--debug_opengl");
  1957. }
  1958. if (command_line_strings.size()) {
  1959. r_command_line_flags.resize(4);
  1960. encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);
  1961. for (int i = 0; i < command_line_strings.size(); i++) {
  1962. print_line(itos(i) + " param: " + command_line_strings[i]);
  1963. CharString command_line_argument = command_line_strings[i].utf8();
  1964. int base = r_command_line_flags.size();
  1965. int length = command_line_argument.length();
  1966. if (length == 0)
  1967. continue;
  1968. r_command_line_flags.resize(base + 4 + length);
  1969. encode_uint32(length, &r_command_line_flags.write[base]);
  1970. copymem(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);
  1971. }
  1972. }
  1973. return OK;
  1974. }
  1975. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) {
  1976. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1977. String src_apk;
  1978. EditorProgress ep("export", "Exporting for Android", 105, true);
  1979. bool use_custom_build = bool(p_preset->get("custom_template/use_custom_build"));
  1980. if (use_custom_build) {
  1981. //re-generate build.gradle and AndroidManifest.xml
  1982. { //test that installed build version is alright
  1983. FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ);
  1984. if (!f) {
  1985. EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu."));
  1986. return ERR_UNCONFIGURED;
  1987. }
  1988. String version = f->get_line().strip_edges();
  1989. if (version != VERSION_FULL_CONFIG) {
  1990. EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n Template installed: %s\n Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG));
  1991. return ERR_UNCONFIGURED;
  1992. }
  1993. }
  1994. // TODO: should we use "package/name" or "application/config/name"?
  1995. String project_name = get_project_name(p_preset->get("package/name"));
  1996. // instead of calling _fix_resources
  1997. Error err = _create_project_name_strings_files(p_preset, project_name);
  1998. if (err != OK) {
  1999. EditorNode::add_io_error("Unable to overwrite res://android/build/res/*.xml files with project name");
  2000. }
  2001. //build project if custom build is enabled
  2002. String sdk_path = EDITOR_GET("export/android/custom_build_sdk_path");
  2003. ERR_FAIL_COND_V_MSG(sdk_path == "", ERR_UNCONFIGURED, "Android SDK path must be configured in Editor Settings at 'export/android/custom_build_sdk_path'.");
  2004. _update_custom_build_project();
  2005. OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
  2006. String build_command;
  2007. #ifdef WINDOWS_ENABLED
  2008. build_command = "gradlew.bat";
  2009. #else
  2010. build_command = "gradlew";
  2011. #endif
  2012. String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build");
  2013. build_command = build_path.plus_file(build_command);
  2014. String package_name = get_package_name(p_preset->get("package/unique_name"));
  2015. Vector<PluginConfig> enabled_plugins = get_enabled_plugins(p_preset);
  2016. String local_plugins_binaries = get_plugins_binaries(BINARY_TYPE_LOCAL, enabled_plugins);
  2017. String remote_plugins_binaries = get_plugins_binaries(BINARY_TYPE_REMOTE, enabled_plugins);
  2018. String custom_maven_repos = get_plugins_custom_maven_repos(enabled_plugins);
  2019. bool clean_build_required = is_clean_build_required(enabled_plugins);
  2020. List<String> cmdline;
  2021. if (clean_build_required) {
  2022. cmdline.push_back("clean");
  2023. }
  2024. cmdline.push_back("build");
  2025. cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.
  2026. cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies.
  2027. cmdline.push_back("-Pplugins_remote_binaries=" + remote_plugins_binaries); // argument to specify the list of plugins remote dependencies.
  2028. cmdline.push_back("-Pplugins_maven_repos=" + custom_maven_repos); // argument to specify the list of custom maven repos for the plugins dependencies.
  2029. cmdline.push_back("-p"); // argument to specify the start directory.
  2030. cmdline.push_back(build_path); // start directory.
  2031. /*{ used for debug
  2032. int ec;
  2033. String pipe;
  2034. OS::get_singleton()->execute(build_command, cmdline, true, NULL, NULL, &ec);
  2035. print_line("exit code: " + itos(ec));
  2036. }
  2037. */
  2038. int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
  2039. if (result != 0) {
  2040. EditorNode::get_singleton()->show_warning(TTR("Building of Android project failed, check output for the error.\nAlternatively visit docs.godotengine.org for Android build documentation."));
  2041. return ERR_CANT_CREATE;
  2042. }
  2043. if (p_debug) {
  2044. src_apk = build_path.plus_file("build/outputs/apk/debug/android_debug.apk");
  2045. } else {
  2046. src_apk = build_path.plus_file("build/outputs/apk/release/android_release.apk");
  2047. }
  2048. if (!FileAccess::exists(src_apk)) {
  2049. EditorNode::get_singleton()->show_warning(TTR("No build apk generated at: ") + "\n" + src_apk);
  2050. return ERR_CANT_CREATE;
  2051. }
  2052. } else {
  2053. if (p_debug)
  2054. src_apk = p_preset->get("custom_template/debug");
  2055. else
  2056. src_apk = p_preset->get("custom_template/release");
  2057. src_apk = src_apk.strip_edges();
  2058. if (src_apk == "") {
  2059. if (p_debug) {
  2060. src_apk = find_export_template("android_debug.apk");
  2061. } else {
  2062. src_apk = find_export_template("android_release.apk");
  2063. }
  2064. if (src_apk == "") {
  2065. EditorNode::add_io_error("Package not found: " + src_apk);
  2066. return ERR_FILE_NOT_FOUND;
  2067. }
  2068. }
  2069. }
  2070. if (!DirAccess::exists(p_path.get_base_dir())) {
  2071. return ERR_FILE_BAD_PATH;
  2072. }
  2073. FileAccess *src_f = NULL;
  2074. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  2075. if (ep.step("Creating APK...", 0)) {
  2076. return ERR_SKIP;
  2077. }
  2078. unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
  2079. if (!pkg) {
  2080. EditorNode::add_io_error("Could not find template APK to export:\n" + src_apk);
  2081. return ERR_FILE_NOT_FOUND;
  2082. }
  2083. int ret = unzGoToFirstFile(pkg);
  2084. zlib_filefunc_def io2 = io;
  2085. FileAccess *dst_f = NULL;
  2086. io2.opaque = &dst_f;
  2087. String tmp_unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk");
  2088. #define CLEANUP_AND_RETURN(m_err) \
  2089. { \
  2090. DirAccess::remove_file_or_error(tmp_unaligned_path); \
  2091. return m_err; \
  2092. }
  2093. zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
  2094. bool _signed = p_preset->get("package/signed");
  2095. String cmdline = p_preset->get("command_line/extra_args");
  2096. String version_name = p_preset->get("version/name");
  2097. String package_name = p_preset->get("package/unique_name");
  2098. bool apk_expansion = p_preset->get("apk_expansion/enable");
  2099. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  2100. String release_keystore = p_preset->get("keystore/release");
  2101. String release_username = p_preset->get("keystore/release_user");
  2102. String release_password = p_preset->get("keystore/release_password");
  2103. Vector<String> enabled_abis = get_enabled_abis(p_preset);
  2104. String project_icon_path = ProjectSettings::get_singleton()->get("application/config/icon");
  2105. // Prepare images to be resized for the icons. If some image ends up being uninitialized, the default image from the export template will be used.
  2106. Ref<Image> launcher_icon_image;
  2107. Ref<Image> launcher_adaptive_icon_foreground_image;
  2108. Ref<Image> launcher_adaptive_icon_background_image;
  2109. launcher_icon_image.instance();
  2110. launcher_adaptive_icon_foreground_image.instance();
  2111. launcher_adaptive_icon_background_image.instance();
  2112. // Regular icon: user selection -> project icon -> default.
  2113. String path = static_cast<String>(p_preset->get(launcher_icon_option)).strip_edges();
  2114. if (path.empty() || ImageLoader::load_image(path, launcher_icon_image) != OK) {
  2115. ImageLoader::load_image(project_icon_path, launcher_icon_image);
  2116. }
  2117. // Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default).
  2118. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_foreground_option)).strip_edges();
  2119. if (path.empty() || ImageLoader::load_image(path, launcher_adaptive_icon_foreground_image) != OK) {
  2120. launcher_adaptive_icon_foreground_image = launcher_icon_image;
  2121. }
  2122. // Adaptive background: user selection -> default.
  2123. path = static_cast<String>(p_preset->get(launcher_adaptive_icon_background_option)).strip_edges();
  2124. if (!path.empty()) {
  2125. ImageLoader::load_image(path, launcher_adaptive_icon_background_image);
  2126. }
  2127. Vector<String> invalid_abis(enabled_abis);
  2128. while (ret == UNZ_OK) {
  2129. //get filename
  2130. unz_file_info info;
  2131. char fname[16384];
  2132. ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
  2133. bool skip = false;
  2134. String file = fname;
  2135. Vector<uint8_t> data;
  2136. data.resize(info.uncompressed_size);
  2137. //read
  2138. unzOpenCurrentFile(pkg);
  2139. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  2140. unzCloseCurrentFile(pkg);
  2141. //write
  2142. if (file == "AndroidManifest.xml") {
  2143. _fix_manifest(p_preset, data, p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG));
  2144. }
  2145. if (file == "resources.arsc") {
  2146. if (!use_custom_build) {
  2147. _fix_resources(p_preset, data);
  2148. }
  2149. }
  2150. for (int i = 0; i < icon_densities_count; ++i) {
  2151. if (launcher_icon_image.is_valid() && !launcher_icon_image->empty()) {
  2152. _process_launcher_icons(file, launcher_icon_image, launcher_icons[i], data);
  2153. }
  2154. if (launcher_adaptive_icon_foreground_image.is_valid() && !launcher_adaptive_icon_foreground_image->empty()) {
  2155. _process_launcher_icons(file, launcher_adaptive_icon_foreground_image, launcher_adaptive_icon_foregrounds[i], data);
  2156. }
  2157. if (launcher_adaptive_icon_background_image.is_valid() && !launcher_adaptive_icon_background_image->empty()) {
  2158. _process_launcher_icons(file, launcher_adaptive_icon_background_image, launcher_adaptive_icon_backgrounds[i], data);
  2159. }
  2160. }
  2161. if (file.ends_with(".so")) {
  2162. bool enabled = false;
  2163. for (int i = 0; i < enabled_abis.size(); ++i) {
  2164. if (file.begins_with("lib/" + enabled_abis[i] + "/")) {
  2165. invalid_abis.erase(enabled_abis[i]);
  2166. enabled = true;
  2167. break;
  2168. }
  2169. }
  2170. if (!enabled) {
  2171. skip = true;
  2172. }
  2173. }
  2174. if (file.begins_with("META-INF") && _signed) {
  2175. skip = true;
  2176. }
  2177. if (!skip) {
  2178. print_line("ADDING: " + file);
  2179. // Respect decision on compression made by AAPT for the export template
  2180. const bool uncompressed = info.compression_method == 0;
  2181. zip_fileinfo zipfi = get_zip_fileinfo();
  2182. zipOpenNewFileInZip(unaligned_apk,
  2183. file.utf8().get_data(),
  2184. &zipfi,
  2185. NULL,
  2186. 0,
  2187. NULL,
  2188. 0,
  2189. NULL,
  2190. uncompressed ? 0 : Z_DEFLATED,
  2191. Z_DEFAULT_COMPRESSION);
  2192. zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
  2193. zipCloseFileInZip(unaligned_apk);
  2194. }
  2195. ret = unzGoToNextFile(pkg);
  2196. }
  2197. if (!invalid_abis.empty()) {
  2198. String unsupported_arch = String(", ").join(invalid_abis);
  2199. EditorNode::add_io_error("Missing libraries in the export template for the selected architectures: " + unsupported_arch + ".\n" +
  2200. "Please build a template with all required libraries, or uncheck the missing architectures in the export preset.");
  2201. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2202. }
  2203. if (ep.step("Adding files...", 1)) {
  2204. CLEANUP_AND_RETURN(ERR_SKIP);
  2205. }
  2206. Error err = OK;
  2207. if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
  2208. APKExportData ed;
  2209. ed.ep = &ep;
  2210. ed.apk = unaligned_apk;
  2211. err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so);
  2212. } else if (!apk_expansion) {
  2213. APKExportData ed;
  2214. ed.ep = &ep;
  2215. ed.apk = unaligned_apk;
  2216. err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so);
  2217. }
  2218. if (err != OK) {
  2219. unzClose(pkg);
  2220. EditorNode::add_io_error("Could not export project files");
  2221. CLEANUP_AND_RETURN(ERR_SKIP);
  2222. }
  2223. Vector<uint8_t> command_line_flags;
  2224. // Write command line flags into the command_line_flags variable.
  2225. err = get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);
  2226. zip_fileinfo zipfi = get_zip_fileinfo();
  2227. zipOpenNewFileInZip(unaligned_apk,
  2228. "assets/_cl_",
  2229. &zipfi,
  2230. NULL,
  2231. 0,
  2232. NULL,
  2233. 0,
  2234. NULL,
  2235. 0, // No compress (little size gain and potentially slower startup)
  2236. Z_DEFAULT_COMPRESSION);
  2237. zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());
  2238. zipCloseFileInZip(unaligned_apk);
  2239. zipClose(unaligned_apk, NULL);
  2240. unzClose(pkg);
  2241. if (err != OK) {
  2242. CLEANUP_AND_RETURN(err);
  2243. }
  2244. if (_signed) {
  2245. String jarsigner = EditorSettings::get_singleton()->get("export/android/jarsigner");
  2246. if (!FileAccess::exists(jarsigner)) {
  2247. EditorNode::add_io_error("'jarsigner' could not be found.\nPlease supply a path in the Editor Settings.\nThe resulting APK is unsigned.");
  2248. CLEANUP_AND_RETURN(OK);
  2249. }
  2250. String keystore;
  2251. String password;
  2252. String user;
  2253. if (p_debug) {
  2254. keystore = p_preset->get("keystore/debug");
  2255. password = p_preset->get("keystore/debug_password");
  2256. user = p_preset->get("keystore/debug_user");
  2257. if (keystore.empty()) {
  2258. keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  2259. password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
  2260. user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
  2261. }
  2262. if (ep.step("Signing debug APK...", 103)) {
  2263. CLEANUP_AND_RETURN(ERR_SKIP);
  2264. }
  2265. } else {
  2266. keystore = release_keystore;
  2267. password = release_password;
  2268. user = release_username;
  2269. if (ep.step("Signing release APK...", 103)) {
  2270. CLEANUP_AND_RETURN(ERR_SKIP);
  2271. }
  2272. }
  2273. if (!FileAccess::exists(keystore)) {
  2274. EditorNode::add_io_error("Could not find keystore, unable to export.");
  2275. CLEANUP_AND_RETURN(ERR_FILE_CANT_OPEN);
  2276. }
  2277. List<String> args;
  2278. args.push_back("-digestalg");
  2279. args.push_back("SHA-256");
  2280. args.push_back("-sigalg");
  2281. args.push_back("SHA256withRSA");
  2282. String tsa_url = EditorSettings::get_singleton()->get("export/android/timestamping_authority_url");
  2283. if (tsa_url != "") {
  2284. args.push_back("-tsa");
  2285. args.push_back(tsa_url);
  2286. }
  2287. args.push_back("-verbose");
  2288. args.push_back("-keystore");
  2289. args.push_back(keystore);
  2290. args.push_back("-storepass");
  2291. args.push_back(password);
  2292. args.push_back(tmp_unaligned_path);
  2293. args.push_back(user);
  2294. int retval;
  2295. OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
  2296. if (retval) {
  2297. EditorNode::add_io_error("'jarsigner' returned with error #" + itos(retval));
  2298. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  2299. }
  2300. if (ep.step("Verifying APK...", 104)) {
  2301. CLEANUP_AND_RETURN(ERR_SKIP);
  2302. }
  2303. args.clear();
  2304. args.push_back("-verify");
  2305. args.push_back("-keystore");
  2306. args.push_back(keystore);
  2307. args.push_back(tmp_unaligned_path);
  2308. args.push_back("-verbose");
  2309. OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
  2310. if (retval) {
  2311. EditorNode::add_io_error("'jarsigner' verification of APK failed. Make sure to use a jarsigner from OpenJDK 8.");
  2312. CLEANUP_AND_RETURN(ERR_CANT_CREATE);
  2313. }
  2314. }
  2315. // Let's zip-align (must be done after signing)
  2316. static const int ZIP_ALIGNMENT = 4;
  2317. if (ep.step("Aligning APK...", 105)) {
  2318. CLEANUP_AND_RETURN(ERR_SKIP);
  2319. }
  2320. unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);
  2321. if (!tmp_unaligned) {
  2322. EditorNode::add_io_error("Could not unzip temporary unaligned APK.");
  2323. CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
  2324. }
  2325. ret = unzGoToFirstFile(tmp_unaligned);
  2326. io2 = io;
  2327. dst_f = NULL;
  2328. io2.opaque = &dst_f;
  2329. zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
  2330. // Take files from the unaligned APK and write them out to the aligned one
  2331. // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
  2332. // following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
  2333. int bias = 0;
  2334. while (ret == UNZ_OK) {
  2335. unz_file_info info;
  2336. memset(&info, 0, sizeof(info));
  2337. char fname[16384];
  2338. char extra[16384];
  2339. ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, NULL, 0);
  2340. String file = fname;
  2341. Vector<uint8_t> data;
  2342. data.resize(info.compressed_size);
  2343. // read
  2344. int method, level;
  2345. unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
  2346. long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
  2347. unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
  2348. unzCloseCurrentFile(tmp_unaligned);
  2349. // align
  2350. int padding = 0;
  2351. if (!info.compression_method) {
  2352. // Uncompressed file => Align
  2353. long new_offset = file_offset + bias;
  2354. padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
  2355. }
  2356. memset(extra + info.size_file_extra, 0, padding);
  2357. zip_fileinfo fileinfo = get_zip_fileinfo();
  2358. zipOpenNewFileInZip2(final_apk,
  2359. file.utf8().get_data(),
  2360. &fileinfo,
  2361. extra,
  2362. info.size_file_extra + padding,
  2363. NULL,
  2364. 0,
  2365. NULL,
  2366. method,
  2367. level,
  2368. 1); // raw write
  2369. zipWriteInFileInZip(final_apk, data.ptr(), data.size());
  2370. zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);
  2371. bias += padding;
  2372. ret = unzGoToNextFile(tmp_unaligned);
  2373. }
  2374. zipClose(final_apk, NULL);
  2375. unzClose(tmp_unaligned);
  2376. CLEANUP_AND_RETURN(OK);
  2377. }
  2378. virtual void get_platform_features(List<String> *r_features) {
  2379. r_features->push_back("mobile");
  2380. r_features->push_back("Android");
  2381. }
  2382. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) {
  2383. }
  2384. EditorExportPlatformAndroid() {
  2385. Ref<Image> img = memnew(Image(_android_logo));
  2386. logo.instance();
  2387. logo->create_from_image(img);
  2388. img = Ref<Image>(memnew(Image(_android_run_icon)));
  2389. run_icon.instance();
  2390. run_icon->create_from_image(img);
  2391. device_lock = Mutex::create();
  2392. devices_changed = true;
  2393. plugins_lock = Mutex::create();
  2394. plugins_changed = true;
  2395. quit_request = false;
  2396. check_for_changes_thread = Thread::create(_check_for_changes_poll_thread, this);
  2397. }
  2398. ~EditorExportPlatformAndroid() {
  2399. quit_request = true;
  2400. Thread::wait_to_finish(check_for_changes_thread);
  2401. memdelete(plugins_lock);
  2402. memdelete(device_lock);
  2403. memdelete(check_for_changes_thread);
  2404. }
  2405. };
  2406. void register_android_exporter() {
  2407. String exe_ext;
  2408. if (OS::get_singleton()->get_name() == "Windows") {
  2409. exe_ext = "*.exe";
  2410. }
  2411. EDITOR_DEF("export/android/adb", "");
  2412. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/adb", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
  2413. EDITOR_DEF("export/android/jarsigner", "");
  2414. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/jarsigner", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
  2415. EDITOR_DEF("export/android/debug_keystore", "");
  2416. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"));
  2417. EDITOR_DEF("export/android/debug_keystore_user", "androiddebugkey");
  2418. EDITOR_DEF("export/android/debug_keystore_pass", "android");
  2419. EDITOR_DEF("export/android/force_system_user", false);
  2420. EDITOR_DEF("export/android/custom_build_sdk_path", "");
  2421. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/custom_build_sdk_path", PROPERTY_HINT_GLOBAL_DIR));
  2422. EDITOR_DEF("export/android/timestamping_authority_url", "");
  2423. EDITOR_DEF("export/android/shutdown_adb_on_exit", true);
  2424. Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>(memnew(EditorExportPlatformAndroid));
  2425. EditorExport::get_singleton()->add_export_platform(exporter);
  2426. }