Debian Codegraph @

platform/android/export/gradle_export_util.cpp

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