export.cpp 78 KB

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