export.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352
  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 = "lib/" + abi + "/" + 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. Vector<String> perms;
  579. const char **aperms = android_perms;
  580. while (*aperms) {
  581. bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());
  582. if (enabled)
  583. perms.push_back("android.permission." + String(*aperms));
  584. aperms++;
  585. }
  586. PoolStringArray user_perms = p_preset->get("permissions/custom_permissions");
  587. for (int i = 0; i < user_perms.size(); i++) {
  588. String user_perm = user_perms[i].strip_edges();
  589. if (!user_perm.empty()) {
  590. perms.push_back(user_perm);
  591. }
  592. }
  593. if (p_give_internet) {
  594. if (perms.find("android.permission.INTERNET") == -1)
  595. perms.push_back("android.permission.INTERNET");
  596. }
  597. while (ofs < (uint32_t)p_manifest.size()) {
  598. uint32_t chunk = decode_uint32(&p_manifest[ofs]);
  599. uint32_t size = decode_uint32(&p_manifest[ofs + 4]);
  600. switch (chunk) {
  601. case CHUNK_STRINGS: {
  602. int iofs = ofs + 8;
  603. string_count = decode_uint32(&p_manifest[iofs]);
  604. //styles_count = decode_uint32(&p_manifest[iofs + 4]);
  605. string_flags = decode_uint32(&p_manifest[iofs + 8]);
  606. string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
  607. //styles_offset = decode_uint32(&p_manifest[iofs + 16]);
  608. /*
  609. printf("string count: %i\n",string_count);
  610. printf("flags: %i\n",string_flags);
  611. printf("sdata ofs: %i\n",string_data_offset);
  612. printf("styles ofs: %i\n",styles_offset);
  613. */
  614. uint32_t st_offset = iofs + 20;
  615. string_table.resize(string_count);
  616. uint32_t string_end = 0;
  617. string_table_begins = st_offset;
  618. for (uint32_t i = 0; i < string_count; i++) {
  619. uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
  620. string_at += st_offset + string_count * 4;
  621. ERR_EXPLAIN("Unimplemented, can't read utf8 string table.");
  622. ERR_FAIL_COND(string_flags & UTF8_FLAG);
  623. if (string_flags & UTF8_FLAG) {
  624. } else {
  625. uint32_t len = decode_uint16(&p_manifest[string_at]);
  626. Vector<CharType> ucstring;
  627. ucstring.resize(len + 1);
  628. for (uint32_t j = 0; j < len; j++) {
  629. uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
  630. ucstring.write[j] = c;
  631. }
  632. string_end = MAX(string_at + 2 + 2 * len, string_end);
  633. ucstring.write[len] = 0;
  634. string_table.write[i] = ucstring.ptr();
  635. }
  636. }
  637. for (uint32_t i = string_end; i < (ofs + size); i++) {
  638. stable_extra.push_back(p_manifest[i]);
  639. }
  640. string_table_ends = ofs + size;
  641. } break;
  642. case CHUNK_XML_START_TAG: {
  643. int iofs = ofs + 8;
  644. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  645. String tname = string_table[name];
  646. uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
  647. iofs += 28;
  648. for (uint32_t i = 0; i < attrcount; i++) {
  649. uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
  650. uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
  651. uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
  652. uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);
  653. String value;
  654. if (attr_value != 0xFFFFFFFF)
  655. value = string_table[attr_value];
  656. else
  657. value = "Res #" + itos(attr_resid);
  658. String attrname = string_table[attr_name];
  659. String nspace;
  660. if (attr_nspace != 0xFFFFFFFF)
  661. nspace = string_table[attr_nspace];
  662. else
  663. nspace = "";
  664. //replace project information
  665. if (tname == "manifest" && attrname == "package") {
  666. string_table.write[attr_value] = get_package_name(package_name);
  667. }
  668. if (tname == "manifest" && attrname == "versionCode") {
  669. encode_uint32(version_code, &p_manifest.write[iofs + 16]);
  670. }
  671. if (tname == "manifest" && attrname == "versionName") {
  672. if (attr_value == 0xFFFFFFFF) {
  673. WARN_PRINT("Version name in a resource, should be plain text");
  674. } else
  675. string_table.write[attr_value] = version_name;
  676. }
  677. if (tname == "activity" && attrname == "screenOrientation") {
  678. encode_uint32(orientation == 0 ? 0 : 1, &p_manifest.write[iofs + 16]);
  679. }
  680. if (tname == "supports-screens") {
  681. if (attrname == "smallScreens") {
  682. encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  683. } else if (attrname == "normalScreens") {
  684. encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  685. } else if (attrname == "largeScreens") {
  686. encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  687. } else if (attrname == "xlargeScreens") {
  688. encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
  689. }
  690. }
  691. if (tname == "uses-feature" && attrname == "glEsVersion") {
  692. encode_uint32(min_gles3 ? 0x00030000 : 0x00020000, &p_manifest.write[iofs + 16]);
  693. }
  694. iofs += 20;
  695. }
  696. } break;
  697. case CHUNK_XML_END_TAG: {
  698. int iofs = ofs + 8;
  699. uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
  700. String tname = string_table[name];
  701. if (tname == "manifest") {
  702. // save manifest ending so we can restore it
  703. Vector<uint8_t> manifest_end;
  704. uint32_t manifest_cur_size = p_manifest.size();
  705. manifest_end.resize(p_manifest.size() - ofs);
  706. memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
  707. int32_t attr_name_string = string_table.find("name");
  708. ERR_EXPLAIN("Template does not have 'name' attribute");
  709. ERR_FAIL_COND(attr_name_string == -1);
  710. int32_t ns_android_string = string_table.find("android");
  711. ERR_EXPLAIN("Template does not have 'android' namespace");
  712. ERR_FAIL_COND(ns_android_string == -1);
  713. int32_t attr_uses_permission_string = string_table.find("uses-permission");
  714. if (attr_uses_permission_string == -1) {
  715. string_table.push_back("uses-permission");
  716. attr_uses_permission_string = string_table.size() - 1;
  717. }
  718. for (int i = 0; i < perms.size(); ++i) {
  719. print_line("Adding permission " + perms[i]);
  720. manifest_cur_size += 56 + 24; // node + end node
  721. p_manifest.resize(manifest_cur_size);
  722. // Add permission to the string pool
  723. int32_t perm_string = string_table.find(perms[i]);
  724. if (perm_string == -1) {
  725. string_table.push_back(perms[i]);
  726. perm_string = string_table.size() - 1;
  727. }
  728. // start tag
  729. encode_uint16(0x102, &p_manifest.write[ofs]); // type
  730. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  731. encode_uint32(56, &p_manifest.write[ofs + 4]); // size
  732. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  733. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  734. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  735. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  736. encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
  737. encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
  738. encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
  739. encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
  740. encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
  741. encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
  742. // attribute
  743. encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
  744. encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
  745. encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
  746. encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
  747. p_manifest.write[ofs + 50] = 0; // typedvalue_always0
  748. p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
  749. encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference
  750. ofs += 56;
  751. // end tag
  752. encode_uint16(0x103, &p_manifest.write[ofs]); // type
  753. encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
  754. encode_uint32(24, &p_manifest.write[ofs + 4]); // size
  755. encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
  756. encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
  757. encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
  758. encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
  759. ofs += 24;
  760. }
  761. // copy footer back in
  762. memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
  763. }
  764. } break;
  765. }
  766. ofs += size;
  767. }
  768. //create new andriodmanifest binary
  769. Vector<uint8_t> ret;
  770. ret.resize(string_table_begins + string_table.size() * 4);
  771. for (uint32_t i = 0; i < string_table_begins; i++) {
  772. ret.write[i] = p_manifest[i];
  773. }
  774. ofs = 0;
  775. for (int i = 0; i < string_table.size(); i++) {
  776. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  777. ofs += string_table[i].length() * 2 + 2 + 2;
  778. }
  779. ret.resize(ret.size() + ofs);
  780. string_data_offset = ret.size() - ofs;
  781. uint8_t *chars = &ret.write[string_data_offset];
  782. for (int i = 0; i < string_table.size(); i++) {
  783. String s = string_table[i];
  784. encode_uint16(s.length(), chars);
  785. chars += 2;
  786. for (int j = 0; j < s.length(); j++) {
  787. encode_uint16(s[j], chars);
  788. chars += 2;
  789. }
  790. encode_uint16(0, chars);
  791. chars += 2;
  792. }
  793. for (int i = 0; i < stable_extra.size(); i++) {
  794. ret.push_back(stable_extra[i]);
  795. }
  796. //pad
  797. while (ret.size() % 4)
  798. ret.push_back(0);
  799. uint32_t new_stable_end = ret.size();
  800. uint32_t extra = (p_manifest.size() - string_table_ends);
  801. ret.resize(new_stable_end + extra);
  802. for (uint32_t i = 0; i < extra; i++)
  803. ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
  804. while (ret.size() % 4)
  805. ret.push_back(0);
  806. encode_uint32(ret.size(), &ret.write[4]); //update new file size
  807. encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
  808. encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
  809. encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset
  810. p_manifest = ret;
  811. }
  812. static String _parse_string(const uint8_t *p_bytes, bool p_utf8) {
  813. uint32_t offset = 0;
  814. uint32_t len = decode_uint16(&p_bytes[offset]);
  815. if (p_utf8) {
  816. //don't know how to read extended utf8, this will have to be for now
  817. len >>= 8;
  818. }
  819. offset += 2;
  820. //printf("len %i, unicode: %i\n",len,int(p_utf8));
  821. if (p_utf8) {
  822. Vector<uint8_t> str8;
  823. str8.resize(len + 1);
  824. for (uint32_t i = 0; i < len; i++) {
  825. str8.write[i] = p_bytes[offset + i];
  826. }
  827. str8.write[len] = 0;
  828. String str;
  829. str.parse_utf8((const char *)str8.ptr());
  830. return str;
  831. } else {
  832. String str;
  833. for (uint32_t i = 0; i < len; i++) {
  834. CharType c = decode_uint16(&p_bytes[offset + i * 2]);
  835. if (c == 0)
  836. break;
  837. str += String::chr(c);
  838. }
  839. return str;
  840. }
  841. }
  842. void _fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest) {
  843. const int UTF8_FLAG = 0x00000100;
  844. uint32_t string_block_len = decode_uint32(&p_manifest[16]);
  845. uint32_t string_count = decode_uint32(&p_manifest[20]);
  846. uint32_t string_flags = decode_uint32(&p_manifest[28]);
  847. const uint32_t string_table_begins = 40;
  848. Vector<String> string_table;
  849. String package_name = p_preset->get("package/name");
  850. for (uint32_t i = 0; i < string_count; i++) {
  851. uint32_t offset = decode_uint32(&p_manifest[string_table_begins + i * 4]);
  852. offset += string_table_begins + string_count * 4;
  853. String str = _parse_string(&p_manifest[offset], string_flags & UTF8_FLAG);
  854. if (str.begins_with("godot-project-name")) {
  855. if (str == "godot-project-name") {
  856. //project name
  857. str = get_project_name(package_name);
  858. } else {
  859. String lang = str.substr(str.find_last("-") + 1, str.length()).replace("-", "_");
  860. String prop = "application/config/name_" + lang;
  861. if (ProjectSettings::get_singleton()->has_setting(prop)) {
  862. str = ProjectSettings::get_singleton()->get(prop);
  863. } else {
  864. str = get_project_name(package_name);
  865. }
  866. }
  867. }
  868. string_table.push_back(str);
  869. }
  870. //write a new string table, but use 16 bits
  871. Vector<uint8_t> ret;
  872. ret.resize(string_table_begins + string_table.size() * 4);
  873. for (uint32_t i = 0; i < string_table_begins; i++) {
  874. ret.write[i] = p_manifest[i];
  875. }
  876. int ofs = 0;
  877. for (int i = 0; i < string_table.size(); i++) {
  878. encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
  879. ofs += string_table[i].length() * 2 + 2 + 2;
  880. }
  881. ret.resize(ret.size() + ofs);
  882. uint8_t *chars = &ret.write[ret.size() - ofs];
  883. for (int i = 0; i < string_table.size(); i++) {
  884. String s = string_table[i];
  885. encode_uint16(s.length(), chars);
  886. chars += 2;
  887. for (int j = 0; j < s.length(); j++) {
  888. encode_uint16(s[j], chars);
  889. chars += 2;
  890. }
  891. encode_uint16(0, chars);
  892. chars += 2;
  893. }
  894. //pad
  895. while (ret.size() % 4)
  896. ret.push_back(0);
  897. //change flags to not use utf8
  898. encode_uint32(string_flags & ~0x100, &ret.write[28]);
  899. //change length
  900. encode_uint32(ret.size() - 12, &ret.write[16]);
  901. //append the rest...
  902. int rest_from = 12 + string_block_len;
  903. int rest_to = ret.size();
  904. int rest_len = (p_manifest.size() - rest_from);
  905. ret.resize(ret.size() + (p_manifest.size() - rest_from));
  906. for (int i = 0; i < rest_len; i++) {
  907. ret.write[rest_to + i] = p_manifest[rest_from + i];
  908. }
  909. //finally update the size
  910. encode_uint32(ret.size(), &ret.write[4]);
  911. p_manifest = ret;
  912. //printf("end\n");
  913. }
  914. static Vector<String> get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
  915. Vector<String> abis = get_abis();
  916. Vector<String> enabled_abis;
  917. for (int i = 0; i < abis.size(); ++i) {
  918. bool is_enabled = p_preset->get("architectures/" + abis[i]);
  919. if (is_enabled) {
  920. enabled_abis.push_back(abis[i]);
  921. }
  922. }
  923. return enabled_abis;
  924. }
  925. public:
  926. typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
  927. public:
  928. virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
  929. String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
  930. if (driver == "GLES2") {
  931. r_features->push_back("etc");
  932. } else if (driver == "GLES3") {
  933. r_features->push_back("etc2");
  934. if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
  935. r_features->push_back("etc");
  936. }
  937. }
  938. Vector<String> abis = get_enabled_abis(p_preset);
  939. for (int i = 0; i < abis.size(); ++i) {
  940. r_features->push_back(abis[i]);
  941. }
  942. }
  943. virtual void get_export_options(List<ExportOption> *r_options) {
  944. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true));
  945. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), true));
  946. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  947. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
  948. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_package/use_custom_build"), false));
  949. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
  950. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
  951. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
  952. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
  953. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
  954. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
  955. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
  956. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "screen/orientation", PROPERTY_HINT_ENUM, "Landscape,Portrait"), 0));
  957. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
  958. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
  959. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
  960. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
  961. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/opengl_debug"), false));
  962. for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
  963. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icons[i].option_id, PROPERTY_HINT_FILE, "*.png"), ""));
  964. }
  965. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
  966. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
  967. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
  968. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
  969. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
  970. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
  971. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
  972. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
  973. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));
  974. Vector<String> abis = get_abis();
  975. for (int i = 0; i < abis.size(); ++i) {
  976. String abi = abis[i];
  977. bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a");
  978. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default));
  979. }
  980. r_options->push_back(ExportOption(PropertyInfo(Variant::POOL_STRING_ARRAY, "permissions/custom_permissions"), PoolStringArray()));
  981. const char **perms = android_perms;
  982. while (*perms) {
  983. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false));
  984. perms++;
  985. }
  986. }
  987. virtual String get_name() const {
  988. return "Android";
  989. }
  990. virtual String get_os_name() const {
  991. return "Android";
  992. }
  993. virtual Ref<Texture> get_logo() const {
  994. return logo;
  995. }
  996. virtual bool poll_devices() {
  997. bool dc = devices_changed;
  998. if (dc) {
  999. // don't clear unless we're reporting true, to avoid race
  1000. devices_changed = false;
  1001. }
  1002. return dc;
  1003. }
  1004. virtual int get_device_count() const {
  1005. device_lock->lock();
  1006. int dc = devices.size();
  1007. device_lock->unlock();
  1008. return dc;
  1009. }
  1010. virtual String get_device_name(int p_device) const {
  1011. ERR_FAIL_INDEX_V(p_device, devices.size(), "");
  1012. device_lock->lock();
  1013. String s = devices[p_device].name;
  1014. device_lock->unlock();
  1015. return s;
  1016. }
  1017. virtual String get_device_info(int p_device) const {
  1018. ERR_FAIL_INDEX_V(p_device, devices.size(), "");
  1019. device_lock->lock();
  1020. String s = devices[p_device].description;
  1021. device_lock->unlock();
  1022. return s;
  1023. }
  1024. virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
  1025. ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
  1026. device_lock->lock();
  1027. EditorProgress ep("run", "Running on " + devices[p_device].name, 3);
  1028. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  1029. if (adb == "") {
  1030. EditorNode::add_io_error("ADB executable not configured in settings, can't run.");
  1031. device_lock->unlock();
  1032. return ERR_UNCONFIGURED;
  1033. }
  1034. //export_temp
  1035. if (ep.step("Exporting APK", 0)) {
  1036. return ERR_SKIP;
  1037. }
  1038. const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
  1039. const bool use_reverse = devices[p_device].api_level >= 21;
  1040. if (use_reverse)
  1041. p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
  1042. String export_to = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport.apk");
  1043. Error err = export_project(p_preset, true, export_to, p_debug_flags);
  1044. if (err) {
  1045. device_lock->unlock();
  1046. return err;
  1047. }
  1048. List<String> args;
  1049. int rv;
  1050. bool remove_prev = p_preset->get("one_click_deploy/clear_previous_install");
  1051. String version_name = p_preset->get("version/name");
  1052. String package_name = p_preset->get("package/unique_name");
  1053. if (remove_prev) {
  1054. if (ep.step("Uninstalling...", 1)) {
  1055. return ERR_SKIP;
  1056. }
  1057. print_line("Uninstalling previous version: " + devices[p_device].name);
  1058. args.push_back("-s");
  1059. args.push_back(devices[p_device].id);
  1060. args.push_back("uninstall");
  1061. args.push_back(get_package_name(package_name));
  1062. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1063. }
  1064. print_line("Installing to device (please wait...): " + devices[p_device].name);
  1065. if (ep.step("Installing to device (please wait...)", 2)) {
  1066. return ERR_SKIP;
  1067. }
  1068. args.clear();
  1069. args.push_back("-s");
  1070. args.push_back(devices[p_device].id);
  1071. args.push_back("install");
  1072. args.push_back("-r");
  1073. args.push_back(export_to);
  1074. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1075. if (err || rv != 0) {
  1076. EditorNode::add_io_error("Could not install to device.");
  1077. device_lock->unlock();
  1078. return ERR_CANT_CREATE;
  1079. }
  1080. if (use_remote) {
  1081. if (use_reverse) {
  1082. static const char *const msg = "** Device API >= 21; debugging over USB **";
  1083. EditorNode::get_singleton()->get_log()->add_message(msg);
  1084. print_line(String(msg).to_upper());
  1085. args.clear();
  1086. args.push_back("-s");
  1087. args.push_back(devices[p_device].id);
  1088. args.push_back("reverse");
  1089. args.push_back("--remove-all");
  1090. OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1091. if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) {
  1092. int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port");
  1093. args.clear();
  1094. args.push_back("-s");
  1095. args.push_back(devices[p_device].id);
  1096. args.push_back("reverse");
  1097. args.push_back("tcp:" + itos(dbg_port));
  1098. args.push_back("tcp:" + itos(dbg_port));
  1099. OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1100. print_line("Reverse result: " + itos(rv));
  1101. }
  1102. if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) {
  1103. int fs_port = EditorSettings::get_singleton()->get("filesystem/file_server/port");
  1104. args.clear();
  1105. args.push_back("-s");
  1106. args.push_back(devices[p_device].id);
  1107. args.push_back("reverse");
  1108. args.push_back("tcp:" + itos(fs_port));
  1109. args.push_back("tcp:" + itos(fs_port));
  1110. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1111. print_line("Reverse result2: " + itos(rv));
  1112. }
  1113. } else {
  1114. static const char *const msg = "** Device API < 21; debugging over Wi-Fi **";
  1115. EditorNode::get_singleton()->get_log()->add_message(msg);
  1116. print_line(String(msg).to_upper());
  1117. }
  1118. }
  1119. if (ep.step("Running on Device...", 3)) {
  1120. return ERR_SKIP;
  1121. }
  1122. args.clear();
  1123. args.push_back("-s");
  1124. args.push_back(devices[p_device].id);
  1125. args.push_back("shell");
  1126. args.push_back("am");
  1127. args.push_back("start");
  1128. if ((bool)EditorSettings::get_singleton()->get("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17
  1129. args.push_back("--user");
  1130. args.push_back("0");
  1131. }
  1132. args.push_back("-a");
  1133. args.push_back("android.intent.action.MAIN");
  1134. args.push_back("-n");
  1135. args.push_back(get_package_name(package_name) + "/org.godotengine.godot.Godot");
  1136. err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
  1137. if (err || rv != 0) {
  1138. EditorNode::add_io_error("Could not execute on device.");
  1139. device_lock->unlock();
  1140. return ERR_CANT_CREATE;
  1141. }
  1142. device_lock->unlock();
  1143. return OK;
  1144. }
  1145. virtual Ref<Texture> get_run_icon() const {
  1146. return run_icon;
  1147. }
  1148. virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
  1149. String err;
  1150. if (!bool(p_preset->get("custom_package/use_custom_build"))) {
  1151. r_missing_templates = find_export_template("android_debug.apk") == String() || find_export_template("android_release.apk") == String();
  1152. if (p_preset->get("custom_package/debug") != "") {
  1153. if (FileAccess::exists(p_preset->get("custom_package/debug"))) {
  1154. r_missing_templates = false;
  1155. } else {
  1156. err += TTR("Custom debug template not found.") + "\n";
  1157. }
  1158. }
  1159. if (p_preset->get("custom_package/release") != "") {
  1160. if (FileAccess::exists(p_preset->get("custom_package/release"))) {
  1161. r_missing_templates = false;
  1162. } else {
  1163. err += TTR("Custom release template not found.") + "\n";
  1164. }
  1165. }
  1166. }
  1167. bool valid = !r_missing_templates;
  1168. String adb = EditorSettings::get_singleton()->get("export/android/adb");
  1169. if (!FileAccess::exists(adb)) {
  1170. valid = false;
  1171. err += TTR("ADB executable not configured in the Editor Settings.") + "\n";
  1172. }
  1173. String js = EditorSettings::get_singleton()->get("export/android/jarsigner");
  1174. if (!FileAccess::exists(js)) {
  1175. valid = false;
  1176. err += TTR("OpenJDK jarsigner not configured in the Editor Settings.") + "\n";
  1177. }
  1178. String dk = p_preset->get("keystore/debug");
  1179. if (!FileAccess::exists(dk)) {
  1180. dk = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  1181. if (!FileAccess::exists(dk)) {
  1182. valid = false;
  1183. err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";
  1184. }
  1185. }
  1186. if (bool(p_preset->get("custom_package/use_custom_build"))) {
  1187. String sdk_path = EditorSettings::get_singleton()->get("export/android/custom_build_sdk_path");
  1188. if (sdk_path == "") {
  1189. err += TTR("Custom build requires a valid Android SDK path in Editor Settings.") + "\n";
  1190. valid = false;
  1191. } else {
  1192. Error errn;
  1193. DirAccess *da = DirAccess::open(sdk_path.plus_file("tools"), &errn);
  1194. if (errn != OK) {
  1195. err += TTR("Invalid Android SDK path for custom build in Editor Settings.") + "\n";
  1196. valid = false;
  1197. }
  1198. if (da) {
  1199. memdelete(da);
  1200. }
  1201. }
  1202. if (!FileAccess::exists("res://android/build/build.gradle")) {
  1203. err += TTR("Android project is not installed for compiling. Install from Editor menu.") + "\n";
  1204. valid = false;
  1205. }
  1206. }
  1207. bool apk_expansion = p_preset->get("apk_expansion/enable");
  1208. if (apk_expansion) {
  1209. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  1210. if (apk_expansion_pkey == "") {
  1211. valid = false;
  1212. err += TTR("Invalid public key for APK expansion.") + "\n";
  1213. }
  1214. }
  1215. String pn = p_preset->get("package/unique_name");
  1216. String pn_err;
  1217. if (!is_package_name_valid(get_package_name(pn), &pn_err)) {
  1218. valid = false;
  1219. err += TTR("Invalid package name:") + " " + pn_err + "\n";
  1220. }
  1221. String etc_error = test_etc2();
  1222. if (etc_error != String()) {
  1223. valid = false;
  1224. err += etc_error;
  1225. }
  1226. r_error = err;
  1227. return valid;
  1228. }
  1229. virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  1230. List<String> list;
  1231. list.push_back("apk");
  1232. return list;
  1233. }
  1234. void _update_custom_build_project() {
  1235. DirAccessRef da = DirAccess::open("res://android");
  1236. ERR_FAIL_COND(!da);
  1237. Map<String, List<String> > directory_paths;
  1238. Map<String, List<String> > manifest_sections;
  1239. Map<String, List<String> > gradle_sections;
  1240. da->list_dir_begin();
  1241. String d = da->get_next();
  1242. while (d != String()) {
  1243. if (!d.begins_with(".") && d != "build" && da->current_is_dir()) { //a dir and not the build dir
  1244. //add directories found
  1245. DirAccessRef ds = DirAccess::open(String("res://android").plus_file(d));
  1246. if (ds) {
  1247. ds->list_dir_begin();
  1248. String sd = ds->get_next();
  1249. while (sd != String()) {
  1250. if (!sd.begins_with(".") && ds->current_is_dir()) {
  1251. String key = sd.to_upper();
  1252. if (!directory_paths.has(key)) {
  1253. directory_paths[key] = List<String>();
  1254. }
  1255. String path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android").plus_file(d).plus_file(sd);
  1256. directory_paths[key].push_back(path);
  1257. print_line("Add: " + sd + ":" + path);
  1258. }
  1259. sd = ds->get_next();
  1260. }
  1261. ds->list_dir_end();
  1262. }
  1263. //parse manifest
  1264. {
  1265. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("AndroidManifest.conf"), FileAccess::READ);
  1266. if (f) {
  1267. String section;
  1268. while (!f->eof_reached()) {
  1269. String l = f->get_line();
  1270. String k = l.strip_edges();
  1271. if (k.begins_with("[")) {
  1272. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  1273. print_line("Section: " + section);
  1274. } else if (k != String()) {
  1275. if (!manifest_sections.has(section)) {
  1276. manifest_sections[section] = List<String>();
  1277. }
  1278. manifest_sections[section].push_back(l);
  1279. }
  1280. }
  1281. f->close();
  1282. }
  1283. }
  1284. //parse gradle
  1285. {
  1286. FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("gradle.conf"), FileAccess::READ);
  1287. if (f) {
  1288. String section;
  1289. while (!f->eof_reached()) {
  1290. String l = f->get_line().strip_edges();
  1291. String k = l.strip_edges();
  1292. if (k.begins_with("[")) {
  1293. section = k.substr(1, k.length() - 2).strip_edges().to_upper();
  1294. print_line("Section: " + section);
  1295. } else if (k != String()) {
  1296. if (!gradle_sections.has(section)) {
  1297. gradle_sections[section] = List<String>();
  1298. }
  1299. gradle_sections[section].push_back(l);
  1300. }
  1301. }
  1302. }
  1303. }
  1304. }
  1305. d = da->get_next();
  1306. }
  1307. da->list_dir_end();
  1308. { //fix gradle build
  1309. String new_file;
  1310. {
  1311. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::READ);
  1312. if (f) {
  1313. while (!f->eof_reached()) {
  1314. String l = f->get_line();
  1315. if (l.begins_with("//CHUNK_")) {
  1316. String text = l.replace_first("//CHUNK_", "");
  1317. int begin_pos = text.find("_BEGIN");
  1318. if (begin_pos != -1) {
  1319. text = text.substr(0, begin_pos);
  1320. text = text.to_upper(); //just in case
  1321. String end_marker = "//CHUNK_" + text + "_END";
  1322. size_t pos = f->get_position();
  1323. bool found = false;
  1324. while (!f->eof_reached()) {
  1325. l = f->get_line();
  1326. if (l.begins_with(end_marker)) {
  1327. found = true;
  1328. break;
  1329. }
  1330. }
  1331. new_file += "//CHUNK_" + text + "_BEGIN\n";
  1332. if (!found) {
  1333. ERR_PRINTS("No end marker found in build.gradle for chunk: " + text);
  1334. f->seek(pos);
  1335. } else {
  1336. //add chunk lines
  1337. if (gradle_sections.has(text)) {
  1338. for (List<String>::Element *E = gradle_sections[text].front(); E; E = E->next()) {
  1339. new_file += E->get() + "\n";
  1340. }
  1341. }
  1342. new_file += end_marker + "\n";
  1343. }
  1344. } else {
  1345. new_file += l + "\n"; //pass line by
  1346. }
  1347. } else if (l.begins_with("//DIR_")) {
  1348. String text = l.replace_first("//DIR_", "");
  1349. int begin_pos = text.find("_BEGIN");
  1350. if (begin_pos != -1) {
  1351. text = text.substr(0, begin_pos);
  1352. text = text.to_upper(); //just in case
  1353. String end_marker = "//DIR_" + text + "_END";
  1354. size_t pos = f->get_position();
  1355. bool found = false;
  1356. while (!f->eof_reached()) {
  1357. l = f->get_line();
  1358. if (l.begins_with(end_marker)) {
  1359. found = true;
  1360. break;
  1361. }
  1362. }
  1363. new_file += "//DIR_" + text + "_BEGIN\n";
  1364. if (!found) {
  1365. ERR_PRINTS("No end marker found in build.gradle for dir: " + text);
  1366. f->seek(pos);
  1367. } else {
  1368. //add chunk lines
  1369. if (directory_paths.has(text)) {
  1370. for (List<String>::Element *E = directory_paths[text].front(); E; E = E->next()) {
  1371. new_file += ",'" + E->get().replace("'", "\'") + "'";
  1372. new_file += "\n";
  1373. }
  1374. }
  1375. new_file += end_marker + "\n";
  1376. }
  1377. } else {
  1378. new_file += l + "\n"; //pass line by
  1379. }
  1380. } else {
  1381. new_file += l + "\n";
  1382. }
  1383. }
  1384. }
  1385. }
  1386. FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::WRITE);
  1387. f->store_string(new_file);
  1388. f->close();
  1389. }
  1390. { //fix manifest
  1391. String new_file;
  1392. {
  1393. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::READ);
  1394. if (f) {
  1395. while (!f->eof_reached()) {
  1396. String l = f->get_line();
  1397. if (l.begins_with("<!--CHUNK_")) {
  1398. String text = l.replace_first("<!--CHUNK_", "");
  1399. int begin_pos = text.find("_BEGIN-->");
  1400. if (begin_pos != -1) {
  1401. text = text.substr(0, begin_pos);
  1402. text = text.to_upper(); //just in case
  1403. String end_marker = "<!--CHUNK_" + text + "_END-->";
  1404. size_t pos = f->get_position();
  1405. bool found = false;
  1406. while (!f->eof_reached()) {
  1407. l = f->get_line();
  1408. if (l.begins_with(end_marker)) {
  1409. found = true;
  1410. break;
  1411. }
  1412. }
  1413. new_file += "<!--CHUNK_" + text + "_BEGIN-->\n";
  1414. if (!found) {
  1415. ERR_PRINTS("No end marker found in AndroidManifest.conf for chunk: " + text);
  1416. f->seek(pos);
  1417. } else {
  1418. //add chunk lines
  1419. if (manifest_sections.has(text)) {
  1420. for (List<String>::Element *E = manifest_sections[text].front(); E; E = E->next()) {
  1421. new_file += E->get() + "\n";
  1422. }
  1423. }
  1424. new_file += end_marker + "\n";
  1425. }
  1426. } else {
  1427. new_file += l + "\n"; //pass line by
  1428. }
  1429. } else if (l.strip_edges().begins_with("<application")) {
  1430. String last_tag = "android:icon=\"@drawable/icon\"";
  1431. int last_tag_pos = l.find(last_tag);
  1432. if (last_tag_pos == -1) {
  1433. WARN_PRINTS("No adding of application tags because could not find last tag for <application: " + last_tag);
  1434. new_file += l + "\n";
  1435. } else {
  1436. String base = l.substr(0, last_tag_pos + last_tag.length());
  1437. if (manifest_sections.has("application_attribs")) {
  1438. for (List<String>::Element *E = manifest_sections["application_attribs"].front(); E; E = E->next()) {
  1439. String to_add = E->get().strip_edges();
  1440. base += " " + to_add + " ";
  1441. }
  1442. }
  1443. base += ">\n";
  1444. new_file += base;
  1445. }
  1446. } else {
  1447. new_file += l + "\n";
  1448. }
  1449. }
  1450. }
  1451. }
  1452. FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::WRITE);
  1453. f->store_string(new_file);
  1454. f->close();
  1455. }
  1456. }
  1457. virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) {
  1458. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1459. String src_apk;
  1460. EditorProgress ep("export", "Exporting for Android", 105, true);
  1461. if (bool(p_preset->get("custom_package/use_custom_build"))) { //custom build
  1462. //re-generate build.gradle and AndroidManifest.xml
  1463. { //test that installed build version is alright
  1464. FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ);
  1465. if (!f) {
  1466. 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."));
  1467. return ERR_UNCONFIGURED;
  1468. }
  1469. String version = f->get_line().strip_edges();
  1470. if (version != VERSION_FULL_CONFIG) {
  1471. 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));
  1472. return ERR_UNCONFIGURED;
  1473. }
  1474. }
  1475. //build project if custom build is enabled
  1476. String sdk_path = EDITOR_GET("export/android/custom_build_sdk_path");
  1477. ERR_FAIL_COND_V(sdk_path == "", ERR_UNCONFIGURED);
  1478. _update_custom_build_project();
  1479. OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
  1480. String build_command;
  1481. #ifdef WINDOWS_ENABLED
  1482. build_command = "gradlew.bat";
  1483. #else
  1484. build_command = "gradlew";
  1485. #endif
  1486. String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build");
  1487. build_command = build_path.plus_file(build_command);
  1488. List<String> cmdline;
  1489. cmdline.push_back("build");
  1490. cmdline.push_back("-p");
  1491. cmdline.push_back(build_path);
  1492. /*{ used for debug
  1493. int ec;
  1494. String pipe;
  1495. OS::get_singleton()->execute(build_command, cmdline, true, NULL, NULL, &ec);
  1496. print_line("exit code: " + itos(ec));
  1497. }
  1498. */
  1499. int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
  1500. if (result != 0) {
  1501. 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."));
  1502. return ERR_CANT_CREATE;
  1503. }
  1504. if (p_debug) {
  1505. src_apk = build_path.plus_file("build/outputs/apk/debug/build-debug-unsigned.apk");
  1506. } else {
  1507. src_apk = build_path.plus_file("build/outputs/apk/release/build-release-unsigned.apk");
  1508. }
  1509. if (!FileAccess::exists(src_apk)) {
  1510. EditorNode::get_singleton()->show_warning(TTR("No build apk generated at: ") + "\n" + src_apk);
  1511. return ERR_CANT_CREATE;
  1512. }
  1513. } else {
  1514. if (p_debug)
  1515. src_apk = p_preset->get("custom_package/debug");
  1516. else
  1517. src_apk = p_preset->get("custom_package/release");
  1518. src_apk = src_apk.strip_edges();
  1519. if (src_apk == "") {
  1520. if (p_debug) {
  1521. src_apk = find_export_template("android_debug.apk");
  1522. } else {
  1523. src_apk = find_export_template("android_release.apk");
  1524. }
  1525. if (src_apk == "") {
  1526. EditorNode::add_io_error("Package not found: " + src_apk);
  1527. return ERR_FILE_NOT_FOUND;
  1528. }
  1529. }
  1530. }
  1531. if (!DirAccess::exists(p_path.get_base_dir())) {
  1532. return ERR_FILE_BAD_PATH;
  1533. }
  1534. FileAccess *src_f = NULL;
  1535. zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
  1536. if (ep.step("Creating APK", 0)) {
  1537. return ERR_SKIP;
  1538. }
  1539. unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
  1540. if (!pkg) {
  1541. EditorNode::add_io_error("Could not find template APK to export:\n" + src_apk);
  1542. return ERR_FILE_NOT_FOUND;
  1543. }
  1544. int ret = unzGoToFirstFile(pkg);
  1545. zlib_filefunc_def io2 = io;
  1546. FileAccess *dst_f = NULL;
  1547. io2.opaque = &dst_f;
  1548. String unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk");
  1549. zipFile unaligned_apk = zipOpen2(unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
  1550. bool use_32_fb = p_preset->get("graphics/32_bits_framebuffer");
  1551. bool immersive = p_preset->get("screen/immersive_mode");
  1552. bool debug_opengl = p_preset->get("screen/opengl_debug");
  1553. bool _signed = p_preset->get("package/signed");
  1554. bool apk_expansion = p_preset->get("apk_expansion/enable");
  1555. String cmdline = p_preset->get("command_line/extra_args");
  1556. int version_code = p_preset->get("version/code");
  1557. String version_name = p_preset->get("version/name");
  1558. String package_name = p_preset->get("package/unique_name");
  1559. String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
  1560. String release_keystore = p_preset->get("keystore/release");
  1561. String release_username = p_preset->get("keystore/release_user");
  1562. String release_password = p_preset->get("keystore/release_password");
  1563. Vector<String> enabled_abis = get_enabled_abis(p_preset);
  1564. while (ret == UNZ_OK) {
  1565. //get filename
  1566. unz_file_info info;
  1567. char fname[16384];
  1568. ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
  1569. bool skip = false;
  1570. String file = fname;
  1571. Vector<uint8_t> data;
  1572. data.resize(info.uncompressed_size);
  1573. //read
  1574. unzOpenCurrentFile(pkg);
  1575. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  1576. unzCloseCurrentFile(pkg);
  1577. //write
  1578. if (file == "AndroidManifest.xml") {
  1579. _fix_manifest(p_preset, data, p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG));
  1580. }
  1581. if (file == "resources.arsc") {
  1582. _fix_resources(p_preset, data);
  1583. }
  1584. if (file == "res/drawable-nodpi-v4/icon.png") {
  1585. bool found = false;
  1586. for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
  1587. String icon_path = String(p_preset->get(launcher_icons[i].option_id)).strip_edges();
  1588. if (icon_path != "" && icon_path.ends_with(".png")) {
  1589. FileAccess *f = FileAccess::open(icon_path, FileAccess::READ);
  1590. if (f) {
  1591. data.resize(f->get_len());
  1592. f->get_buffer(data.ptrw(), data.size());
  1593. memdelete(f);
  1594. found = true;
  1595. break;
  1596. }
  1597. }
  1598. }
  1599. if (!found) {
  1600. String appicon = ProjectSettings::get_singleton()->get("application/config/icon");
  1601. if (appicon != "" && appicon.ends_with(".png")) {
  1602. FileAccess *f = FileAccess::open(appicon, FileAccess::READ);
  1603. if (f) {
  1604. data.resize(f->get_len());
  1605. f->get_buffer(data.ptrw(), data.size());
  1606. memdelete(f);
  1607. }
  1608. }
  1609. }
  1610. }
  1611. if (file.ends_with(".so")) {
  1612. bool enabled = false;
  1613. for (int i = 0; i < enabled_abis.size(); ++i) {
  1614. if (file.begins_with("lib/" + enabled_abis[i] + "/")) {
  1615. enabled = true;
  1616. break;
  1617. }
  1618. }
  1619. if (!enabled) {
  1620. skip = true;
  1621. }
  1622. }
  1623. if (file.begins_with("META-INF") && _signed) {
  1624. skip = true;
  1625. }
  1626. if (!skip) {
  1627. print_line("ADDING: " + file);
  1628. // Respect decision on compression made by AAPT for the export template
  1629. const bool uncompressed = info.compression_method == 0;
  1630. zip_fileinfo zipfi = get_zip_fileinfo();
  1631. zipOpenNewFileInZip(unaligned_apk,
  1632. file.utf8().get_data(),
  1633. &zipfi,
  1634. NULL,
  1635. 0,
  1636. NULL,
  1637. 0,
  1638. NULL,
  1639. uncompressed ? 0 : Z_DEFLATED,
  1640. Z_DEFAULT_COMPRESSION);
  1641. zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
  1642. zipCloseFileInZip(unaligned_apk);
  1643. }
  1644. ret = unzGoToNextFile(pkg);
  1645. }
  1646. if (ep.step("Adding Files...", 1)) {
  1647. return ERR_SKIP;
  1648. }
  1649. Error err = OK;
  1650. Vector<String> cl = cmdline.strip_edges().split(" ");
  1651. for (int i = 0; i < cl.size(); i++) {
  1652. if (cl[i].strip_edges().length() == 0) {
  1653. cl.remove(i);
  1654. i--;
  1655. }
  1656. }
  1657. gen_export_flags(cl, p_flags);
  1658. if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
  1659. APKExportData ed;
  1660. ed.ep = &ep;
  1661. ed.apk = unaligned_apk;
  1662. err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so);
  1663. } else {
  1664. //all files
  1665. if (apk_expansion) {
  1666. String apkfname = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
  1667. String fullpath = p_path.get_base_dir().plus_file(apkfname);
  1668. err = save_pack(p_preset, fullpath);
  1669. if (err != OK) {
  1670. unzClose(pkg);
  1671. EditorNode::add_io_error("Could not write expansion package file: " + apkfname);
  1672. return OK;
  1673. }
  1674. cl.push_back("--use_apk_expansion");
  1675. cl.push_back("--apk_expansion_md5");
  1676. cl.push_back(FileAccess::get_md5(fullpath));
  1677. cl.push_back("--apk_expansion_key");
  1678. cl.push_back(apk_expansion_pkey.strip_edges());
  1679. } else {
  1680. APKExportData ed;
  1681. ed.ep = &ep;
  1682. ed.apk = unaligned_apk;
  1683. err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so);
  1684. }
  1685. }
  1686. if (!err) {
  1687. APKExportData ed;
  1688. ed.ep = &ep;
  1689. ed.apk = unaligned_apk;
  1690. for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
  1691. String icon_path = String(p_preset->get(launcher_icons[i].option_id)).strip_edges();
  1692. if (icon_path != "" && icon_path.ends_with(".png") && FileAccess::exists(icon_path)) {
  1693. Vector<uint8_t> data = FileAccess::get_file_as_array(icon_path);
  1694. store_in_apk(&ed, launcher_icons[i].export_path, data);
  1695. }
  1696. }
  1697. }
  1698. if (use_32_fb)
  1699. cl.push_back("--use_depth_32");
  1700. if (immersive)
  1701. cl.push_back("--use_immersive");
  1702. if (debug_opengl)
  1703. cl.push_back("--debug_opengl");
  1704. if (cl.size()) {
  1705. //add comandline
  1706. Vector<uint8_t> clf;
  1707. clf.resize(4);
  1708. encode_uint32(cl.size(), &clf.write[0]);
  1709. for (int i = 0; i < cl.size(); i++) {
  1710. print_line(itos(i) + " param: " + cl[i]);
  1711. CharString txt = cl[i].utf8();
  1712. int base = clf.size();
  1713. int length = txt.length();
  1714. if (!length)
  1715. continue;
  1716. clf.resize(base + 4 + length);
  1717. encode_uint32(length, &clf.write[base]);
  1718. copymem(&clf.write[base + 4], txt.ptr(), length);
  1719. }
  1720. zip_fileinfo zipfi = get_zip_fileinfo();
  1721. zipOpenNewFileInZip(unaligned_apk,
  1722. "assets/_cl_",
  1723. &zipfi,
  1724. NULL,
  1725. 0,
  1726. NULL,
  1727. 0,
  1728. NULL,
  1729. 0, // No compress (little size gain and potentially slower startup)
  1730. Z_DEFAULT_COMPRESSION);
  1731. zipWriteInFileInZip(unaligned_apk, clf.ptr(), clf.size());
  1732. zipCloseFileInZip(unaligned_apk);
  1733. }
  1734. zipClose(unaligned_apk, NULL);
  1735. unzClose(pkg);
  1736. if (err) {
  1737. return err;
  1738. }
  1739. if (_signed) {
  1740. String jarsigner = EditorSettings::get_singleton()->get("export/android/jarsigner");
  1741. if (!FileAccess::exists(jarsigner)) {
  1742. EditorNode::add_io_error("'jarsigner' could not be found.\nPlease supply a path in the Editor Settings.\nThe resulting APK is unsigned.");
  1743. return OK;
  1744. }
  1745. String keystore;
  1746. String password;
  1747. String user;
  1748. if (p_debug) {
  1749. keystore = p_preset->get("keystore/debug");
  1750. password = p_preset->get("keystore/debug_password");
  1751. user = p_preset->get("keystore/debug_user");
  1752. if (keystore.empty()) {
  1753. keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
  1754. password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
  1755. user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
  1756. }
  1757. if (ep.step("Signing debug APK...", 103)) {
  1758. return ERR_SKIP;
  1759. }
  1760. } else {
  1761. keystore = release_keystore;
  1762. password = release_password;
  1763. user = release_username;
  1764. if (ep.step("Signing release APK...", 103)) {
  1765. return ERR_SKIP;
  1766. }
  1767. }
  1768. if (!FileAccess::exists(keystore)) {
  1769. EditorNode::add_io_error("Could not find keystore, unable to export.");
  1770. return ERR_FILE_CANT_OPEN;
  1771. }
  1772. List<String> args;
  1773. args.push_back("-digestalg");
  1774. args.push_back("SHA-256");
  1775. args.push_back("-sigalg");
  1776. args.push_back("SHA256withRSA");
  1777. String tsa_url = EditorSettings::get_singleton()->get("export/android/timestamping_authority_url");
  1778. if (tsa_url != "") {
  1779. args.push_back("-tsa");
  1780. args.push_back(tsa_url);
  1781. }
  1782. args.push_back("-verbose");
  1783. args.push_back("-keystore");
  1784. args.push_back(keystore);
  1785. args.push_back("-storepass");
  1786. args.push_back(password);
  1787. args.push_back(unaligned_path);
  1788. args.push_back(user);
  1789. int retval;
  1790. OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
  1791. if (retval) {
  1792. EditorNode::add_io_error("'jarsigner' returned with error #" + itos(retval));
  1793. return ERR_CANT_CREATE;
  1794. }
  1795. if (ep.step("Verifying APK...", 104)) {
  1796. return ERR_SKIP;
  1797. }
  1798. args.clear();
  1799. args.push_back("-verify");
  1800. args.push_back("-keystore");
  1801. args.push_back(keystore);
  1802. args.push_back(unaligned_path);
  1803. args.push_back("-verbose");
  1804. OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
  1805. if (retval) {
  1806. EditorNode::add_io_error("'jarsigner' verification of APK failed. Make sure to use a jarsigner from OpenJDK 8.");
  1807. return ERR_CANT_CREATE;
  1808. }
  1809. }
  1810. // Let's zip-align (must be done after signing)
  1811. static const int ZIP_ALIGNMENT = 4;
  1812. if (ep.step("Aligning APK...", 105)) {
  1813. return ERR_SKIP;
  1814. }
  1815. unzFile tmp_unaligned = unzOpen2(unaligned_path.utf8().get_data(), &io);
  1816. if (!tmp_unaligned) {
  1817. EditorNode::add_io_error("Could not find temp unaligned APK.");
  1818. return ERR_FILE_NOT_FOUND;
  1819. }
  1820. ret = unzGoToFirstFile(tmp_unaligned);
  1821. io2 = io;
  1822. dst_f = NULL;
  1823. io2.opaque = &dst_f;
  1824. zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
  1825. // Take files from the unaligned APK and write them out to the aligned one
  1826. // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
  1827. // following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
  1828. int bias = 0;
  1829. while (ret == UNZ_OK) {
  1830. unz_file_info info;
  1831. memset(&info, 0, sizeof(info));
  1832. char fname[16384];
  1833. char extra[16384];
  1834. ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, NULL, 0);
  1835. String file = fname;
  1836. Vector<uint8_t> data;
  1837. data.resize(info.compressed_size);
  1838. // read
  1839. int method, level;
  1840. unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
  1841. long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
  1842. unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
  1843. unzCloseCurrentFile(tmp_unaligned);
  1844. // align
  1845. int padding = 0;
  1846. if (!info.compression_method) {
  1847. // Uncompressed file => Align
  1848. long new_offset = file_offset + bias;
  1849. padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
  1850. }
  1851. memset(extra + info.size_file_extra, 0, padding);
  1852. // write
  1853. zip_fileinfo zipfi = get_zip_fileinfo();
  1854. zipOpenNewFileInZip2(final_apk,
  1855. file.utf8().get_data(),
  1856. &zipfi,
  1857. extra,
  1858. info.size_file_extra + padding,
  1859. NULL,
  1860. 0,
  1861. NULL,
  1862. method,
  1863. level,
  1864. 1); // raw write
  1865. zipWriteInFileInZip(final_apk, data.ptr(), data.size());
  1866. zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);
  1867. bias += padding;
  1868. ret = unzGoToNextFile(tmp_unaligned);
  1869. }
  1870. zipClose(final_apk, NULL);
  1871. unzClose(tmp_unaligned);
  1872. return OK;
  1873. }
  1874. virtual void get_platform_features(List<String> *r_features) {
  1875. r_features->push_back("mobile");
  1876. r_features->push_back("Android");
  1877. }
  1878. virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) {
  1879. }
  1880. EditorExportPlatformAndroid() {
  1881. Ref<Image> img = memnew(Image(_android_logo));
  1882. logo.instance();
  1883. logo->create_from_image(img);
  1884. img = Ref<Image>(memnew(Image(_android_run_icon)));
  1885. run_icon.instance();
  1886. run_icon->create_from_image(img);
  1887. device_lock = Mutex::create();
  1888. devices_changed = true;
  1889. quit_request = false;
  1890. device_thread = Thread::create(_device_poll_thread, this);
  1891. }
  1892. ~EditorExportPlatformAndroid() {
  1893. quit_request = true;
  1894. Thread::wait_to_finish(device_thread);
  1895. memdelete(device_lock);
  1896. memdelete(device_thread);
  1897. }
  1898. };
  1899. void register_android_exporter() {
  1900. String exe_ext;
  1901. if (OS::get_singleton()->get_name() == "Windows") {
  1902. exe_ext = "*.exe";
  1903. }
  1904. EDITOR_DEF("export/android/adb", "");
  1905. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/adb", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
  1906. EDITOR_DEF("export/android/jarsigner", "");
  1907. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/jarsigner", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
  1908. EDITOR_DEF("export/android/debug_keystore", "");
  1909. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"));
  1910. EDITOR_DEF("export/android/debug_keystore_user", "androiddebugkey");
  1911. EDITOR_DEF("export/android/debug_keystore_pass", "android");
  1912. EDITOR_DEF("export/android/force_system_user", false);
  1913. EDITOR_DEF("export/android/custom_build_sdk_path", "");
  1914. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/custom_build_sdk_path", PROPERTY_HINT_GLOBAL_DIR, "*.keystore"));
  1915. EDITOR_DEF("export/android/timestamping_authority_url", "");
  1916. EDITOR_DEF("export/android/shutdown_adb_on_exit", true);
  1917. Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>(memnew(EditorExportPlatformAndroid));
  1918. EditorExport::get_singleton()->add_export_platform(exporter);
  1919. }