gradle_export_util.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /**************************************************************************/
  2. /* gradle_export_util.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gradle_export_util.h"
  31. #include "core/string/translation_server.h"
  32. #include "modules/regex/regex.h"
  33. int _get_android_orientation_value(DisplayServer::ScreenOrientation screen_orientation) {
  34. switch (screen_orientation) {
  35. case DisplayServer::SCREEN_PORTRAIT:
  36. return 1;
  37. case DisplayServer::SCREEN_REVERSE_LANDSCAPE:
  38. return 8;
  39. case DisplayServer::SCREEN_REVERSE_PORTRAIT:
  40. return 9;
  41. case DisplayServer::SCREEN_SENSOR_LANDSCAPE:
  42. return 11;
  43. case DisplayServer::SCREEN_SENSOR_PORTRAIT:
  44. return 12;
  45. case DisplayServer::SCREEN_SENSOR:
  46. return 13;
  47. case DisplayServer::SCREEN_LANDSCAPE:
  48. default:
  49. return 0;
  50. }
  51. }
  52. String _get_android_orientation_label(DisplayServer::ScreenOrientation screen_orientation) {
  53. switch (screen_orientation) {
  54. case DisplayServer::SCREEN_PORTRAIT:
  55. return "portrait";
  56. case DisplayServer::SCREEN_REVERSE_LANDSCAPE:
  57. return "reverseLandscape";
  58. case DisplayServer::SCREEN_REVERSE_PORTRAIT:
  59. return "reversePortrait";
  60. case DisplayServer::SCREEN_SENSOR_LANDSCAPE:
  61. return "userLandscape";
  62. case DisplayServer::SCREEN_SENSOR_PORTRAIT:
  63. return "userPortrait";
  64. case DisplayServer::SCREEN_SENSOR:
  65. return "fullUser";
  66. case DisplayServer::SCREEN_LANDSCAPE:
  67. default:
  68. return "landscape";
  69. }
  70. }
  71. int _get_app_category_value(int category_index) {
  72. switch (category_index) {
  73. case APP_CATEGORY_ACCESSIBILITY:
  74. return 8;
  75. case APP_CATEGORY_AUDIO:
  76. return 1;
  77. case APP_CATEGORY_IMAGE:
  78. return 3;
  79. case APP_CATEGORY_MAPS:
  80. return 6;
  81. case APP_CATEGORY_NEWS:
  82. return 5;
  83. case APP_CATEGORY_PRODUCTIVITY:
  84. return 7;
  85. case APP_CATEGORY_SOCIAL:
  86. return 4;
  87. case APP_CATEGORY_UNDEFINED:
  88. return -1;
  89. case APP_CATEGORY_VIDEO:
  90. return 2;
  91. case APP_CATEGORY_GAME:
  92. default:
  93. return 0;
  94. }
  95. }
  96. String _get_app_category_label(int category_index) {
  97. switch (category_index) {
  98. case APP_CATEGORY_ACCESSIBILITY:
  99. return "accessibility";
  100. case APP_CATEGORY_AUDIO:
  101. return "audio";
  102. case APP_CATEGORY_IMAGE:
  103. return "image";
  104. case APP_CATEGORY_MAPS:
  105. return "maps";
  106. case APP_CATEGORY_NEWS:
  107. return "news";
  108. case APP_CATEGORY_PRODUCTIVITY:
  109. return "productivity";
  110. case APP_CATEGORY_SOCIAL:
  111. return "social";
  112. case APP_CATEGORY_VIDEO:
  113. return "video";
  114. case APP_CATEGORY_GAME:
  115. default:
  116. return "game";
  117. }
  118. }
  119. // Utility method used to create a directory.
  120. Error create_directory(const String &p_dir) {
  121. if (!DirAccess::exists(p_dir)) {
  122. Ref<DirAccess> filesystem_da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  123. ERR_FAIL_COND_V_MSG(filesystem_da.is_null(), ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'.");
  124. Error err = filesystem_da->make_dir_recursive(p_dir);
  125. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'.");
  126. }
  127. return OK;
  128. }
  129. // Writes p_data into a file at p_path, creating directories if necessary.
  130. // Note: this will overwrite the file at p_path if it already exists.
  131. Error store_file_at_path(const String &p_path, const Vector<uint8_t> &p_data) {
  132. String dir = p_path.get_base_dir();
  133. Error err = create_directory(dir);
  134. if (err != OK) {
  135. return err;
  136. }
  137. Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE);
  138. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'.");
  139. fa->store_buffer(p_data.ptr(), p_data.size());
  140. return OK;
  141. }
  142. // Writes string p_data into a file at p_path, creating directories if necessary.
  143. // Note: this will overwrite the file at p_path if it already exists.
  144. Error store_string_at_path(const String &p_path, const String &p_data) {
  145. String dir = p_path.get_base_dir();
  146. Error err = create_directory(dir);
  147. if (err != OK) {
  148. if (OS::get_singleton()->is_stdout_verbose()) {
  149. print_error("Unable to write data into " + p_path);
  150. }
  151. return err;
  152. }
  153. Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE);
  154. ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'.");
  155. fa->store_string(p_data);
  156. return OK;
  157. }
  158. // Implementation of EditorExportSaveFunction.
  159. // This method will only be called as an input to export_project_files.
  160. // It is used by the export_project_files method to save all the asset files into the gradle project.
  161. // It's functionality mirrors that of the method save_apk_file.
  162. // This method will be called ONLY when gradle build is enabled.
  163. Error rename_and_store_file_in_gradle_project(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed, bool p_delta) {
  164. CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata);
  165. const String simplified_path = EditorExportPlatform::simplify_path(p_path);
  166. Vector<uint8_t> enc_data;
  167. EditorExportPlatform::SavedData sd;
  168. Error err = _store_temp_file(simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, p_delta, enc_data, sd);
  169. if (err != OK) {
  170. return err;
  171. }
  172. const String dst_path = export_data->assets_directory + String("/") + simplified_path.trim_prefix("res://");
  173. print_verbose("Saving project files from " + simplified_path + " into " + dst_path);
  174. err = store_file_at_path(dst_path, enc_data);
  175. export_data->pd.file_ofs.push_back(sd);
  176. return err;
  177. }
  178. String _android_xml_escape(const String &p_string) {
  179. // Android XML requires strings to be both valid XML (`xml_escape()`) but also
  180. // to escape characters which are valid XML but have special meaning in Android XML.
  181. // https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
  182. // Note: Didn't handle U+XXXX unicode chars, could be done if needed.
  183. return p_string
  184. .replace("@", "\\@")
  185. .replace("?", "\\?")
  186. .replace("'", "\\'")
  187. .replace("\"", "\\\"")
  188. .replace("\n", "\\n")
  189. .replace("\t", "\\t")
  190. .xml_escape(false);
  191. }
  192. // Creates strings.xml files inside the gradle project for different locales.
  193. Error _create_project_name_strings_files(const Ref<EditorExportPreset> &p_preset, const String &p_project_name, const String &p_gradle_build_dir, const Dictionary &p_appnames) {
  194. print_verbose("Creating strings resources for supported locales for project " + p_project_name);
  195. // Stores the string into the default values directory.
  196. String processed_default_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(p_project_name));
  197. store_string_at_path(p_gradle_build_dir.path_join("res/values/godot_project_name_string.xml"), processed_default_xml_string);
  198. // Searches the Gradle project res/ directory to find all supported locales
  199. Ref<DirAccess> da = DirAccess::open(p_gradle_build_dir.path_join("res"));
  200. if (da.is_null()) {
  201. if (OS::get_singleton()->is_stdout_verbose()) {
  202. print_error("Unable to open Android resources directory.");
  203. }
  204. return ERR_CANT_OPEN;
  205. }
  206. // Setup a temporary translation domain to translate the project name.
  207. const StringName domain_name = "godot.project_name_localization";
  208. Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(domain_name);
  209. TranslationServer::get_singleton()->load_project_translations(domain);
  210. da->list_dir_begin();
  211. while (true) {
  212. String file = da->get_next();
  213. if (file.is_empty()) {
  214. break;
  215. }
  216. if (!file.begins_with("values-")) {
  217. // NOTE: This assumes all directories that start with "values-" are for localization.
  218. continue;
  219. }
  220. String locale = file.replace("values-", "").replace("-r", "_");
  221. String locale_directory = p_gradle_build_dir.path_join("res/" + file + "/godot_project_name_string.xml");
  222. String locale_project_name;
  223. if (p_appnames.is_empty()) {
  224. domain->set_locale_override(locale);
  225. locale_project_name = domain->translate(p_project_name, String());
  226. } else {
  227. locale_project_name = p_appnames.get(locale, p_project_name);
  228. }
  229. if (locale_project_name != p_project_name) {
  230. String processed_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(locale_project_name));
  231. print_verbose("Storing project name for locale " + locale + " under " + locale_directory);
  232. store_string_at_path(locale_directory, processed_xml_string);
  233. } else {
  234. // TODO: Once the legacy build system is deprecated we don't need to have xml files for this else branch
  235. store_string_at_path(locale_directory, processed_default_xml_string);
  236. }
  237. }
  238. da->list_dir_end();
  239. TranslationServer::get_singleton()->remove_domain(domain_name);
  240. return OK;
  241. }
  242. String bool_to_string(bool v) {
  243. return v ? "true" : "false";
  244. }
  245. String _get_gles_tag() {
  246. return " <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" />\n";
  247. }
  248. String _get_screen_sizes_tag(const Ref<EditorExportPreset> &p_preset) {
  249. String manifest_screen_sizes = " <supports-screens \n tools:node=\"replace\"";
  250. String sizes[] = { "small", "normal", "large", "xlarge" };
  251. constexpr size_t num_sizes = std_size(sizes);
  252. for (size_t i = 0; i < num_sizes; i++) {
  253. String feature_name = vformat("screen/support_%s", sizes[i]);
  254. String feature_support = bool_to_string(p_preset->get(feature_name));
  255. String xml_entry = vformat("\n android:%sScreens=\"%s\"", sizes[i], feature_support);
  256. manifest_screen_sizes += xml_entry;
  257. }
  258. manifest_screen_sizes += " />\n";
  259. return manifest_screen_sizes;
  260. }
  261. String _get_activity_tag(const Ref<EditorExportPlatform> &p_export_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug) {
  262. String export_plugins_activity_element_contents;
  263. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  264. for (int i = 0; i < export_plugins.size(); i++) {
  265. if (export_plugins[i]->supports_platform(p_export_platform)) {
  266. const String contents = export_plugins[i]->get_android_manifest_activity_element_contents(p_export_platform, p_debug);
  267. if (!contents.is_empty()) {
  268. const String export_plugin_name = export_plugins[i]->get_name();
  269. export_plugins_activity_element_contents += "<!-- Start of manifest activity element contents from " + export_plugin_name + " -->\n";
  270. export_plugins_activity_element_contents += contents;
  271. export_plugins_activity_element_contents += "\n";
  272. export_plugins_activity_element_contents += "<!-- End of manifest activity element contents from " + export_plugin_name + " -->\n";
  273. }
  274. }
  275. }
  276. // Update the GodotApp activity tag.
  277. String orientation = _get_android_orientation_label(DisplayServer::ScreenOrientation(int(p_export_platform->get_project_setting(p_preset, "display/window/handheld/orientation"))));
  278. String manifest_activity_text = vformat(
  279. " <activity android:name=\".GodotApp\" "
  280. "tools:replace=\"android:screenOrientation,android:excludeFromRecents,android:resizeableActivity\" "
  281. "tools:node=\"mergeOnlyAttributes\" "
  282. "android:excludeFromRecents=\"%s\" "
  283. "android:screenOrientation=\"%s\" "
  284. "android:resizeableActivity=\"%s\">\n",
  285. bool_to_string(p_preset->get("package/exclude_from_recents")),
  286. orientation,
  287. bool_to_string(bool(p_export_platform->get_project_setting(p_preset, "display/window/size/resizable"))));
  288. // *LAUNCHER and *HOME categories should only go to the activity-alias.
  289. Ref<RegEx> activity_content_to_remove_regex = RegEx::create_from_string(R"delim(<category\s+android:name\s*=\s*"\S+(LAUNCHER|HOME)"\s*\/>)delim");
  290. String updated_export_plugins_activity_element_contents = activity_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);
  291. manifest_activity_text += updated_export_plugins_activity_element_contents;
  292. manifest_activity_text += " </activity>\n";
  293. // Update the GodotAppLauncher activity tag.
  294. manifest_activity_text += " <activity-alias\n"
  295. " tools:node=\"mergeOnlyAttributes\"\n"
  296. " android:name=\".GodotAppLauncher\"\n"
  297. " android:targetActivity=\".GodotApp\"\n"
  298. " android:exported=\"true\">\n";
  299. manifest_activity_text += " <intent-filter>\n"
  300. " <action android:name=\"android.intent.action.MAIN\" />\n"
  301. " <category android:name=\"android.intent.category.DEFAULT\" />\n";
  302. bool show_in_app_library = p_preset->get("package/show_in_app_library");
  303. if (show_in_app_library) {
  304. manifest_activity_text += " <category android:name=\"android.intent.category.LAUNCHER\" />\n";
  305. }
  306. bool uses_leanback_category = p_preset->get("package/show_in_android_tv");
  307. if (uses_leanback_category) {
  308. manifest_activity_text += " <category android:name=\"android.intent.category.LEANBACK_LAUNCHER\" />\n";
  309. }
  310. bool uses_home_category = p_preset->get("package/show_as_launcher_app");
  311. if (uses_home_category) {
  312. manifest_activity_text += " <category android:name=\"android.intent.category.HOME\" />\n";
  313. }
  314. manifest_activity_text += " </intent-filter>\n";
  315. // Hybrid categories should only go to the actual 'GodotApp' activity.
  316. Ref<RegEx> activity_alias_content_to_remove_regex = RegEx::create_from_string(R"delim(<category\s+android:name\s*=\s*"org.godotengine.xr.hybrid.(IMMERSIVE|PANEL)"\s*\/>)delim");
  317. String updated_export_plugins_activity_alias_element_contents = activity_alias_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);
  318. manifest_activity_text += updated_export_plugins_activity_alias_element_contents;
  319. manifest_activity_text += " </activity-alias>\n";
  320. return manifest_activity_text;
  321. }
  322. String _get_application_tag(const Ref<EditorExportPlatform> &p_export_platform, const Ref<EditorExportPreset> &p_preset, bool p_has_read_write_storage_permission, bool p_debug, const Vector<MetadataInfo> &p_metadata) {
  323. int app_category_index = (int)(p_preset->get("package/app_category"));
  324. bool is_game = app_category_index == APP_CATEGORY_GAME;
  325. String manifest_application_text = vformat(
  326. " <application android:label=\"@string/godot_project_name_string\"\n"
  327. " android:allowBackup=\"%s\"\n"
  328. " android:icon=\"@mipmap/icon\"\n"
  329. " android:isGame=\"%s\"\n"
  330. " android:hasFragileUserData=\"%s\"\n"
  331. " android:requestLegacyExternalStorage=\"%s\"\n",
  332. bool_to_string(p_preset->get("user_data_backup/allow")),
  333. bool_to_string(is_game),
  334. bool_to_string(p_preset->get("package/retain_data_on_uninstall")),
  335. bool_to_string(p_has_read_write_storage_permission));
  336. if (app_category_index != APP_CATEGORY_UNDEFINED) {
  337. manifest_application_text += vformat(" android:appCategory=\"%s\"\n", _get_app_category_label(app_category_index));
  338. manifest_application_text += " tools:replace=\"android:allowBackup,android:appCategory,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";
  339. } else {
  340. manifest_application_text += " tools:remove=\"android:appCategory\"\n";
  341. manifest_application_text += " tools:replace=\"android:allowBackup,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";
  342. }
  343. manifest_application_text += " tools:ignore=\"GoogleAppIndexingWarning\">\n\n";
  344. for (int i = 0; i < p_metadata.size(); i++) {
  345. manifest_application_text += vformat(" <meta-data tools:node=\"replace\" android:name=\"%s\" android:value=\"%s\" />\n", p_metadata[i].name, p_metadata[i].value);
  346. }
  347. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  348. for (int i = 0; i < export_plugins.size(); i++) {
  349. if (export_plugins[i]->supports_platform(p_export_platform)) {
  350. const String contents = export_plugins[i]->get_android_manifest_application_element_contents(p_export_platform, p_debug);
  351. if (!contents.is_empty()) {
  352. const String export_plugin_name = export_plugins[i]->get_name();
  353. manifest_application_text += "<!-- Start of manifest application element contents from " + export_plugin_name + " -->\n";
  354. manifest_application_text += contents;
  355. manifest_application_text += "\n";
  356. manifest_application_text += "<!-- End of manifest application element contents from " + export_plugin_name + " -->\n";
  357. }
  358. }
  359. }
  360. manifest_application_text += _get_activity_tag(p_export_platform, p_preset, p_debug);
  361. manifest_application_text += " </application>\n";
  362. return manifest_application_text;
  363. }
  364. Error _store_temp_file(const String &p_simplified_path, const Vector<uint8_t> &p_data, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed, bool p_delta, Vector<uint8_t> &r_enc_data, EditorExportPlatform::SavedData &r_sd) {
  365. Error err = OK;
  366. Ref<FileAccess> ftmp = FileAccess::create_temp(FileAccess::WRITE_READ, "export", "tmp", false, &err);
  367. if (err != OK) {
  368. return err;
  369. }
  370. r_sd.path_utf8 = p_simplified_path.trim_prefix("res://").utf8();
  371. r_sd.ofs = 0;
  372. r_sd.size = p_data.size();
  373. r_sd.delta = p_delta;
  374. err = EditorExportPlatform::_encrypt_and_store_data(ftmp, p_simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, r_sd.encrypted);
  375. if (err != OK) {
  376. return err;
  377. }
  378. r_enc_data.resize(ftmp->get_length());
  379. ftmp->seek(0);
  380. ftmp->get_buffer(r_enc_data.ptrw(), r_enc_data.size());
  381. ftmp.unref();
  382. // Store MD5 of original file.
  383. {
  384. unsigned char hash[16];
  385. CryptoCore::md5(p_data.ptr(), p_data.size(), hash);
  386. r_sd.md5.resize(16);
  387. for (int i = 0; i < 16; i++) {
  388. r_sd.md5.write[i] = hash[i];
  389. }
  390. }
  391. return OK;
  392. }