export.cpp 79 KB

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