Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/platform/android/export/gradle_export_util.cpp
21135 views
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
String dst_path;
186
if (export_data->pd.salt.length() == 32) {
187
dst_path = export_data->assets_directory + String("/") + (simplified_path + export_data->pd.salt).sha256_text();
188
} else {
189
dst_path = export_data->assets_directory + String("/") + simplified_path.trim_prefix("res://");
190
}
191
print_verbose("Saving project files from " + simplified_path + " into " + dst_path);
192
err = store_file_at_path(dst_path, enc_data);
193
194
export_data->pd.file_ofs.push_back(sd);
195
return err;
196
}
197
198
String _android_xml_escape(const String &p_string) {
199
// Android XML requires strings to be both valid XML (`xml_escape()`) but also
200
// to escape characters which are valid XML but have special meaning in Android XML.
201
// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
202
// Note: Didn't handle U+XXXX unicode chars, could be done if needed.
203
return p_string
204
.replace("@", "\\@")
205
.replace("?", "\\?")
206
.replace("'", "\\'")
207
.replace("\"", "\\\"")
208
.replace("\n", "\\n")
209
.replace("\t", "\\t")
210
.xml_escape(false);
211
}
212
213
// Creates strings.xml files inside the gradle project for different locales.
214
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) {
215
print_verbose("Creating strings resources for supported locales for project " + p_project_name);
216
// Stores the string into the default values directory.
217
String processed_default_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(p_project_name));
218
store_string_at_path(p_gradle_build_dir.path_join("res/values/godot_project_name_string.xml"), processed_default_xml_string);
219
220
// Searches the Gradle project res/ directory to find all supported locales
221
Ref<DirAccess> da = DirAccess::open(p_gradle_build_dir.path_join("res"));
222
if (da.is_null()) {
223
if (OS::get_singleton()->is_stdout_verbose()) {
224
print_error("Unable to open Android resources directory.");
225
}
226
return ERR_CANT_OPEN;
227
}
228
229
// Setup a temporary translation domain to translate the project name.
230
const StringName domain_name = "godot.project_name_localization";
231
Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(domain_name);
232
TranslationServer::get_singleton()->load_project_translations(domain);
233
234
da->list_dir_begin();
235
while (true) {
236
String file = da->get_next();
237
if (file.is_empty()) {
238
break;
239
}
240
if (!file.begins_with("values-")) {
241
// NOTE: This assumes all directories that start with "values-" are for localization.
242
continue;
243
}
244
String locale = file.replace("values-", "").replace("-r", "_");
245
String locale_directory = p_gradle_build_dir.path_join("res/" + file + "/godot_project_name_string.xml");
246
247
String locale_project_name;
248
if (p_appnames.is_empty()) {
249
domain->set_locale_override(locale);
250
locale_project_name = domain->translate(p_project_name, String());
251
} else {
252
locale_project_name = p_appnames.get(locale, p_project_name);
253
}
254
if (locale_project_name != p_project_name) {
255
String processed_xml_string = vformat(GODOT_PROJECT_NAME_XML_STRING, _android_xml_escape(locale_project_name));
256
print_verbose("Storing project name for locale " + locale + " under " + locale_directory);
257
store_string_at_path(locale_directory, processed_xml_string);
258
} else {
259
// TODO: Once the legacy build system is deprecated we don't need to have xml files for this else branch
260
store_string_at_path(locale_directory, processed_default_xml_string);
261
}
262
}
263
da->list_dir_end();
264
265
TranslationServer::get_singleton()->remove_domain(domain_name);
266
267
return OK;
268
}
269
270
String bool_to_string(bool v) {
271
return v ? "true" : "false";
272
}
273
274
String _get_gles_tag() {
275
return " <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" />\n";
276
}
277
278
String _get_screen_sizes_tag(const Ref<EditorExportPreset> &p_preset) {
279
String manifest_screen_sizes = " <supports-screens \n tools:node=\"replace\"";
280
String sizes[] = { "small", "normal", "large", "xlarge" };
281
constexpr size_t num_sizes = std_size(sizes);
282
for (size_t i = 0; i < num_sizes; i++) {
283
String feature_name = vformat("screen/support_%s", sizes[i]);
284
String feature_support = bool_to_string(p_preset->get(feature_name));
285
String xml_entry = vformat("\n android:%sScreens=\"%s\"", sizes[i], feature_support);
286
manifest_screen_sizes += xml_entry;
287
}
288
manifest_screen_sizes += " />\n";
289
return manifest_screen_sizes;
290
}
291
292
String _get_activity_tag(const Ref<EditorExportPlatform> &p_export_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug) {
293
String export_plugins_activity_element_contents;
294
Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
295
for (int i = 0; i < export_plugins.size(); i++) {
296
if (export_plugins[i]->supports_platform(p_export_platform)) {
297
const String contents = export_plugins[i]->get_android_manifest_activity_element_contents(p_export_platform, p_debug);
298
if (!contents.is_empty()) {
299
const String export_plugin_name = export_plugins[i]->get_name();
300
export_plugins_activity_element_contents += "<!-- Start of manifest activity element contents from " + export_plugin_name + " -->\n";
301
export_plugins_activity_element_contents += contents;
302
export_plugins_activity_element_contents += "\n";
303
export_plugins_activity_element_contents += "<!-- End of manifest activity element contents from " + export_plugin_name + " -->\n";
304
}
305
}
306
}
307
308
// Update the GodotApp activity tag.
309
String orientation = _get_android_orientation_label(DisplayServer::ScreenOrientation(int(p_export_platform->get_project_setting(p_preset, "display/window/handheld/orientation"))));
310
String manifest_activity_text = vformat(
311
" <activity android:name=\".GodotApp\" "
312
"tools:replace=\"android:screenOrientation,android:excludeFromRecents,android:resizeableActivity\" "
313
"tools:node=\"mergeOnlyAttributes\" "
314
"android:excludeFromRecents=\"%s\" "
315
"android:screenOrientation=\"%s\" "
316
"android:resizeableActivity=\"%s\">\n",
317
bool_to_string(p_preset->get("package/exclude_from_recents")),
318
orientation,
319
bool_to_string(bool(p_export_platform->get_project_setting(p_preset, "display/window/size/resizable"))));
320
321
// *LAUNCHER and *HOME categories should only go to the activity-alias.
322
Ref<RegEx> activity_content_to_remove_regex = RegEx::create_from_string(R"delim(<category\s+android:name\s*=\s*"\S+(LAUNCHER|HOME)"\s*\/>)delim");
323
String updated_export_plugins_activity_element_contents = activity_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);
324
manifest_activity_text += updated_export_plugins_activity_element_contents;
325
326
manifest_activity_text += " </activity>\n";
327
328
// Update the GodotAppLauncher activity tag.
329
manifest_activity_text += " <activity-alias\n"
330
" tools:node=\"mergeOnlyAttributes\"\n"
331
" android:name=\".GodotAppLauncher\"\n"
332
" android:targetActivity=\".GodotApp\"\n"
333
" android:exported=\"true\">\n";
334
335
manifest_activity_text += " <intent-filter>\n"
336
" <action android:name=\"android.intent.action.MAIN\" />\n"
337
" <category android:name=\"android.intent.category.DEFAULT\" />\n";
338
339
bool show_in_app_library = p_preset->get("package/show_in_app_library");
340
if (show_in_app_library) {
341
manifest_activity_text += " <category android:name=\"android.intent.category.LAUNCHER\" />\n";
342
}
343
344
bool uses_leanback_category = p_preset->get("package/show_in_android_tv");
345
if (uses_leanback_category) {
346
manifest_activity_text += " <category android:name=\"android.intent.category.LEANBACK_LAUNCHER\" />\n";
347
}
348
349
bool uses_home_category = p_preset->get("package/show_as_launcher_app");
350
if (uses_home_category) {
351
manifest_activity_text += " <category android:name=\"android.intent.category.HOME\" />\n";
352
}
353
354
manifest_activity_text += " </intent-filter>\n";
355
356
// Hybrid categories should only go to the actual 'GodotApp' activity.
357
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");
358
String updated_export_plugins_activity_alias_element_contents = activity_alias_content_to_remove_regex->sub(export_plugins_activity_element_contents, "", true);
359
manifest_activity_text += updated_export_plugins_activity_alias_element_contents;
360
361
manifest_activity_text += " </activity-alias>\n";
362
return manifest_activity_text;
363
}
364
365
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) {
366
int app_category_index = (int)(p_preset->get("package/app_category"));
367
bool is_game = app_category_index == APP_CATEGORY_GAME;
368
369
String manifest_application_text = vformat(
370
" <application android:label=\"@string/godot_project_name_string\"\n"
371
" android:allowBackup=\"%s\"\n"
372
" android:icon=\"@mipmap/icon\"\n"
373
" android:isGame=\"%s\"\n"
374
" android:hasFragileUserData=\"%s\"\n"
375
" android:requestLegacyExternalStorage=\"%s\"\n",
376
bool_to_string(p_preset->get("user_data_backup/allow")),
377
bool_to_string(is_game),
378
bool_to_string(p_preset->get("package/retain_data_on_uninstall")),
379
bool_to_string(p_has_read_write_storage_permission));
380
if (app_category_index != APP_CATEGORY_UNDEFINED) {
381
manifest_application_text += vformat(" android:appCategory=\"%s\"\n", _get_app_category_label(app_category_index));
382
manifest_application_text += " tools:replace=\"android:allowBackup,android:appCategory,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";
383
} else {
384
manifest_application_text += " tools:remove=\"android:appCategory\"\n";
385
manifest_application_text += " tools:replace=\"android:allowBackup,android:isGame,android:hasFragileUserData,android:requestLegacyExternalStorage\"\n";
386
}
387
manifest_application_text += " tools:ignore=\"GoogleAppIndexingWarning\">\n\n";
388
389
for (int i = 0; i < p_metadata.size(); i++) {
390
manifest_application_text += vformat(" <meta-data tools:node=\"replace\" android:name=\"%s\" android:value=\"%s\" />\n", p_metadata[i].name, p_metadata[i].value);
391
}
392
393
Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
394
for (int i = 0; i < export_plugins.size(); i++) {
395
if (export_plugins[i]->supports_platform(p_export_platform)) {
396
const String contents = export_plugins[i]->get_android_manifest_application_element_contents(p_export_platform, p_debug);
397
if (!contents.is_empty()) {
398
const String export_plugin_name = export_plugins[i]->get_name();
399
manifest_application_text += "<!-- Start of manifest application element contents from " + export_plugin_name + " -->\n";
400
manifest_application_text += contents;
401
manifest_application_text += "\n";
402
manifest_application_text += "<!-- End of manifest application element contents from " + export_plugin_name + " -->\n";
403
}
404
}
405
}
406
407
manifest_application_text += _get_activity_tag(p_export_platform, p_preset, p_debug);
408
manifest_application_text += " </application>\n";
409
return manifest_application_text;
410
}
411
412
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) {
413
Error err = OK;
414
Ref<FileAccess> ftmp = FileAccess::create_temp(FileAccess::WRITE_READ, "export", "tmp", false, &err);
415
if (err != OK) {
416
return err;
417
}
418
r_sd.path_utf8 = p_simplified_path.trim_prefix("res://").utf8();
419
r_sd.ofs = 0;
420
r_sd.size = p_data.size();
421
r_sd.delta = p_delta;
422
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);
423
if (err != OK) {
424
return err;
425
}
426
427
r_enc_data.resize(ftmp->get_length());
428
ftmp->seek(0);
429
ftmp->get_buffer(r_enc_data.ptrw(), r_enc_data.size());
430
ftmp.unref();
431
432
// Store MD5 of original file.
433
{
434
unsigned char hash[16];
435
CryptoCore::md5(p_data.ptr(), p_data.size(), hash);
436
r_sd.md5.resize(16);
437
for (int i = 0; i < 16; i++) {
438
r_sd.md5.write[i] = hash[i];
439
}
440
}
441
return OK;
442
}
443
444