Debian Codegraph @

editor/export/editor_export_platform.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* editor_export_platform.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 "editor_export_platform.h"
32
33 #include "editor_export_platform.compat.inc"
34
35 #include "core/config/project_settings.h"
36 #include "core/crypto/crypto_core.h"
37 #include "core/extension/gdextension.h"
38 #include "core/io/delta_encoding.h"
39 #include "core/io/dir_access.h"
40 #include "core/io/file_access_encrypted.h"
41 #include "core/io/file_access_pack.h" // PACK_HEADER_MAGIC, PACK_FORMAT_VERSION
42 #include "core/io/image.h"
43 #include "core/io/image_loader.h"
44 #include "core/io/resource_uid.h"
45 #include "core/math/random_pcg.h"
46 #include "core/os/shared_object.h"
47 #include "core/string/translation_server.h"
48 #include "core/version.h"
49 #include "editor/editor_node.h"
50 #include "editor/editor_string_names.h"
51 #include "editor/export/editor_export.h"
52 #include "editor/file_system/editor_file_system.h"
53 #include "editor/file_system/editor_paths.h"
54 #include "editor/script/script_editor_plugin.h"
55 #include "editor/settings/editor_settings.h"
56 #include "editor/themes/editor_scale.h"
57 #include "editor_export_plugin.h"
58 #include "scene/gui/rich_text_label.h"
59 #include "scene/main/node.h"
60 #include "scene/resources/packed_scene.h"
61 #include "scene/resources/texture.h"
62
63 class EditorExportSaveProxy {
64 HashSet<String> saved_paths;
65 EditorExportPlatform::EditorExportSaveFunction save_func;
66 bool tracking_saves = false;
67
68 public:
69 bool has_saved(const String &p_path) const { return saved_paths.has(p_path); }
70
71 Error save_file(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) {
72 if (tracking_saves) {
73 saved_paths.insert(p_path.simplify_path().trim_prefix("res://"));
74 }
75
76 return save_func(p_preset, p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, p_delta);
77 }
78
79 EditorExportSaveProxy(EditorExportPlatform::EditorExportSaveFunction p_save_func, bool p_track_saves) :
80 save_func(p_save_func), tracking_saves(p_track_saves) {}
81 };
82
83 static int _get_pad(int p_alignment, int p_n) {
84 int rest = p_n % p_alignment;
85 int pad = 0;
86 if (rest > 0) {
87 pad = p_alignment - rest;
88 };
89
90 return pad;
91 }
92
93 static constexpr int PCK_PADDING = 16;
94
95 Ref<Image> EditorExportPlatform::_load_icon_or_splash_image(const String &p_path, Error *r_error) const {
96 Ref<Image> image;
97
98 if (!p_path.is_empty() && ResourceLoader::exists(p_path) && !ResourceLoader::get_resource_type(p_path).is_empty()) {
99 Ref<Texture2D> texture = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, r_error);
100 if (texture.is_valid()) {
101 image = texture->get_image();
102 if (image.is_valid() && image->is_compressed()) {
103 image->decompress();
104 }
105 }
106 }
107 if (image.is_null()) {
108 image.instantiate();
109 Error err = ImageLoader::load_image(p_path, image);
110 if (r_error) {
111 *r_error = err;
112 }
113 }
114 return image;
115 }
116
117 bool EditorExportPlatform::fill_log_messages(RichTextLabel *p_log, Error p_err) {
118 bool has_messages = false;
119
120 int msg_count = get_message_count();
121
122 p_log->add_text(TTR("Project export for platform:") + " ");
123 p_log->add_image(get_logo(), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
124 p_log->add_text(" ");
125 p_log->add_text(get_name());
126 p_log->add_text(" - ");
127 if (p_err == OK && get_worst_message_type() < EditorExportPlatform::EXPORT_MESSAGE_ERROR) {
128 if (get_worst_message_type() >= EditorExportPlatform::EXPORT_MESSAGE_WARNING) {
129 p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusWarning")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
130 p_log->add_text(" ");
131 p_log->add_text(TTR("Completed with warnings."));
132 has_messages = true;
133 } else {
134 p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusSuccess")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
135 p_log->add_text(" ");
136 p_log->add_text(TTR("Completed successfully."));
137 if (msg_count > 0) {
138 has_messages = true;
139 }
140 }
141 } else {
142 p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusError")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
143 p_log->add_text(" ");
144 p_log->add_text(TTR("Failed."));
145 has_messages = true;
146 }
147 p_log->add_newline();
148
149 if (msg_count > 0) {
150 p_log->push_table(2);
151 p_log->set_table_column_expand(0, false);
152 p_log->set_table_column_expand(1, true);
153 for (int m = 0; m < msg_count; m++) {
154 EditorExportPlatform::ExportMessage msg = get_message(m);
155 Color color = p_log->get_theme_color(SceneStringName(font_color), SNAME("Label"));
156 Ref<Texture> icon;
157
158 switch (msg.msg_type) {
159 case EditorExportPlatform::EXPORT_MESSAGE_INFO: {
160 color = p_log->get_theme_color(SceneStringName(font_color), EditorStringName(Editor)) * Color(1, 1, 1, 0.6);
161 } break;
162 case EditorExportPlatform::EXPORT_MESSAGE_WARNING: {
163 icon = p_log->get_editor_theme_icon(SNAME("Warning"));
164 color = p_log->get_theme_color(SNAME("warning_color"), EditorStringName(Editor));
165 } break;
166 case EditorExportPlatform::EXPORT_MESSAGE_ERROR: {
167 icon = p_log->get_editor_theme_icon(SNAME("Error"));
168 color = p_log->get_theme_color(SNAME("error_color"), EditorStringName(Editor));
169 } break;
170 default:
171 break;
172 }
173
174 p_log->push_cell();
175 p_log->add_text("\t");
176 if (icon.is_valid()) {
177 p_log->add_image(icon);
178 }
179 p_log->pop();
180
181 p_log->push_cell();
182 p_log->push_color(color);
183 p_log->add_text(vformat("[%s]: %s", msg.category, msg.text));
184 p_log->pop();
185 p_log->pop();
186 }
187 p_log->pop();
188 p_log->add_newline();
189 } else if (p_err != OK) {
190 // We failed but don't show any user-facing messages. This is bad and should not
191 // be allowed, but just in case this happens, let's give the user something at least.
192 p_log->push_table(2);
193 p_log->set_table_column_expand(0, false);
194 p_log->set_table_column_expand(1, true);
195
196 {
197 Color color = p_log->get_theme_color(SNAME("error_color"), EditorStringName(Editor));
198 Ref<Texture> icon = p_log->get_editor_theme_icon(SNAME("Error"));
199
200 p_log->push_cell();
201 p_log->add_text("\t");
202 if (icon.is_valid()) {
203 p_log->add_image(icon);
204 }
205 p_log->pop();
206
207 p_log->push_cell();
208 p_log->push_color(color);
209 p_log->add_text(vformat("[%s]: %s", TTR("Unknown Error"), vformat(TTR("Export failed with error code %d."), p_err)));
210 p_log->pop();
211 p_log->pop();
212 }
213
214 p_log->pop();
215 p_log->add_newline();
216 }
217
218 p_log->add_newline();
219
220 return has_messages;
221 }
222
223 Error EditorExportPlatform::_load_patches(const Vector<String> &p_patches) {
224 Error err = OK;
225 if (!p_patches.is_empty()) {
226 for (const String &path : p_patches) {
227 err = PackedData::get_singleton()->add_pack(path, true, 0);
228 if (err != OK) {
229 add_message(EXPORT_MESSAGE_ERROR, TTR("Patch Creation"), vformat(TTR("Could not load patch pack with path \"%s\"."), path));
230 return err;
231 }
232 }
233 }
234 return err;
235 }
236
237 void EditorExportPlatform::_unload_patches() {
238 PackedData::get_singleton()->clear();
239 }
240
241 Error EditorExportPlatform::_encrypt_and_store_data(Ref<FileAccess> p_fd, const String &p_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 &r_encrypt) {
242 r_encrypt = false;
243 for (int i = 0; i < p_enc_in_filters.size(); ++i) {
244 if (p_path.matchn(p_enc_in_filters[i]) || p_path.trim_prefix("res://").matchn(p_enc_in_filters[i])) {
245 r_encrypt = true;
246 break;
247 }
248 }
249
250 for (int i = 0; i < p_enc_ex_filters.size(); ++i) {
251 if (p_path.matchn(p_enc_ex_filters[i]) || p_path.trim_prefix("res://").matchn(p_enc_ex_filters[i])) {
252 r_encrypt = false;
253 break;
254 }
255 }
256
257 Ref<FileAccessEncrypted> fae;
258 Ref<FileAccess> ftmp = p_fd;
259 if (r_encrypt) {
260 Vector<uint8_t> iv;
261 if (p_seed != 0) {
262 uint64_t seed = p_seed;
263
264 const uint8_t *ptr = p_data.ptr();
265 int64_t len = p_data.size();
266 for (int64_t i = 0; i < len; i++) {
267 seed = ((seed << 5) + seed) ^ ptr[i];
268 }
269
270 RandomPCG rng = RandomPCG(seed);
271 iv.resize(16);
272 for (int i = 0; i < 16; i++) {
273 iv.write[i] = rng.rand() % 256;
274 }
275 }
276
277 fae.instantiate();
278 ERR_FAIL_COND_V(fae.is_null(), ERR_FILE_CANT_OPEN);
279
280 Error err = fae->open_and_parse(ftmp, p_key, FileAccessEncrypted::MODE_WRITE_AES256, false, iv);
281 ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
282 ftmp = fae;
283 }
284
285 // Store file content.
286 ftmp->store_buffer(p_data.ptr(), p_data.size());
287
288 if (fae.is_valid()) {
289 ftmp.unref();
290 fae.unref();
291 }
292 return OK;
293 }
294
295 Error EditorExportPlatform::_save_pack_file(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) {
296 ERR_FAIL_COND_V_MSG(p_total < 1, ERR_PARAMETER_RANGE_ERROR, "Must select at least one file to export.");
297
298 PackData *pd = (PackData *)p_userdata;
299
300 const String simplified_path = simplify_path(p_path);
301
302 Ref<FileAccess> ftmp;
303 if (pd->use_sparse_pck) {
304 ftmp = FileAccess::open(pd->path.get_base_dir().path_join(simplified_path.trim_prefix("res://")), FileAccess::WRITE);
305 } else {
306 ftmp = pd->f;
307 }
308
309 SavedData sd;
310 sd.path_utf8 = simplified_path.trim_prefix("res://").utf8();
311 sd.ofs = (pd->use_sparse_pck) ? 0 : pd->f->get_position();
312 sd.size = p_data.size();
313 sd.delta = p_delta;
314 Error err = _encrypt_and_store_data(ftmp, simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, sd.encrypted);
315 if (err != OK) {
316 return err;
317 }
318 if (!pd->use_sparse_pck) {
319 ERR_FAIL_COND_V(pd->f->get_position() - sd.ofs < (uint64_t)p_data.size(), ERR_FILE_CANT_WRITE);
320 }
321
322 if (!pd->use_sparse_pck) {
323 int pad = _get_pad(PCK_PADDING, pd->f->get_position());
324 for (int i = 0; i < pad; i++) {
325 pd->f->store_8(0);
326 }
327 }
328
329 // Store MD5 of original file.
330 {
331 unsigned char hash[16];
332 CryptoCore::md5(p_data.ptr(), p_data.size(), hash);
333 sd.md5.resize(16);
334 for (int i = 0; i < 16; i++) {
335 sd.md5.write[i] = hash[i];
336 }
337 }
338
339 pd->file_ofs.push_back(sd);
340
341 // TRANSLATORS: This is an editor progress label describing the storing of a file.
342 if (pd->ep->step(vformat(TTR("Storing File: %s"), p_path), 2 + p_file * 100 / p_total, false)) {
343 return ERR_SKIP;
344 }
345
346 return OK;
347 }
348
349 Error EditorExportPlatform::_save_pack_patch_file(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) {
350 Ref<FileAccess> old_file = PackedData::get_singleton()->try_open_path(p_path);
351 if (old_file.is_null()) {
352 return _save_pack_file(p_preset, p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, false);
353 }
354
355 Vector<uint8_t> old_data = old_file->get_buffer(old_file->get_length());
356
357 // We can't rely on the MD5 as stored in the PCKs, since delta patches could have made it stale.
358 if (p_data == old_data) {
359 return OK; // Do nothing if the file hasn't changed.
360 }
361
362 if (!p_preset->is_patch_delta_encoding_enabled()) {
363 return _save_pack_file(p_preset, p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, false);
364 }
365
366 bool delta = false;
367
368 for (const String &filter : p_preset->get_patch_delta_include_filter().split(",", false)) {
369 String filter_stripped = filter.strip_edges();
370 if (p_path.matchn(filter_stripped) || p_path.trim_prefix("res://").matchn(filter_stripped)) {
371 delta = true;
372 break;
373 }
374 }
375
376 for (const String &filter : p_preset->get_patch_delta_exclude_filter().split(",", false)) {
377 String filter_stripped = filter.strip_edges();
378 if (p_path.matchn(filter_stripped) || p_path.trim_prefix("res://").matchn(filter_stripped)) {
379 delta = false;
380 break;
381 }
382 }
383
384 Vector<uint8_t> patch_data = p_data;
385
386 if (delta) {
387 Error err = DeltaEncoding::encode_delta(old_data, p_data, patch_data, p_preset->get_patch_delta_zstd_level());
388 if (err != OK) {
389 return err;
390 }
391
392 int64_t reduction_bytes = MAX(0, p_data.size() - patch_data.size());
393 double reduction_ratio = reduction_bytes / (double)p_data.size();
394
395 if (reduction_ratio >= p_preset->get_patch_delta_min_reduction()) {
396 print_verbose(vformat("Used delta encoding for patch of \"%s\", resulting in a patch of %d bytes, which reduced the size by %.1f%% (%d bytes) compared to the actual file.", p_path, patch_data.size(), reduction_ratio * 100, reduction_bytes));
397 } else {
398 print_verbose(vformat("Skipped delta encoding for patch of \"%s\", as it resulted in a patch of %d bytes, which only reduced the size by %.1f%% (%d bytes) compared to the actual file.", p_path, patch_data.size(), reduction_ratio * 100, reduction_bytes));
399 patch_data = p_data;
400 delta = false;
401 }
402 } else {
403 print_verbose(vformat("Skipped delta encoding for patch of \"%s\", due to include/exclude filters.", p_path));
404 }
405
406 return _save_pack_file(p_preset, p_userdata, p_path, patch_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, delta);
407 }
408
409 Error EditorExportPlatform::_save_zip_file(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) {
410 ERR_FAIL_COND_V_MSG(p_total < 1, ERR_PARAMETER_RANGE_ERROR, "Must select at least one file to export.");
411
412 const String path = simplify_path(p_path).replace_first("res://", "");
413
414 ZipData *zd = (ZipData *)p_userdata;
415
416 zipFile zip = (zipFile)zd->zip;
417
418 zipOpenNewFileInZip(zip,
419 path.utf8().get_data(),
420 nullptr,
421 nullptr,
422 0,
423 nullptr,
424 0,
425 nullptr,
426 Z_DEFLATED,
427 Z_DEFAULT_COMPRESSION);
428
429 zipWriteInFileInZip(zip, p_data.ptr(), p_data.size());
430 zipCloseFileInZip(zip);
431
432 zd->file_count += 1;
433
434 if (zd->ep->step(TTR("Storing File:") + " " + p_path, 2 + p_file * 100 / p_total, false)) {
435 return ERR_SKIP;
436 }
437
438 return OK;
439 }
440
441 Error EditorExportPlatform::_save_zip_patch_file(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) {
442 Ref<FileAccess> old_file = PackedData::get_singleton()->try_open_path(p_path);
443 if (old_file.is_valid()) {
444 Vector<uint8_t> old_data = old_file->get_buffer(old_file->get_length());
445
446 // We can't rely on the MD5 as stored in the PCKs, since delta patches could have made it stale.
447 if (p_data == old_data) {
448 return OK; // Do nothing if the file hasn't changed.
449 }
450 }
451
452 return _save_zip_file(p_preset, p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, p_delta);
453 }
454
455 Ref<Texture2D> EditorExportPlatform::get_option_icon(int p_index) const {
456 Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
457 ERR_FAIL_COND_V(theme.is_null(), Ref<Texture2D>());
458 return theme->get_icon(SNAME("Play"), EditorStringName(EditorIcons));
459 }
460
461 String EditorExportPlatform::find_export_template(const String &template_file_name, String *err) const {
462 String current_version = GODOT_VERSION_FULL_CONFIG;
463 String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(current_version).path_join(template_file_name);
464
465 if (FileAccess::exists(template_path)) {
466 return template_path;
467 }
468
469 // Not found
470 if (err) {
471 *err += TTR("No export template found at the expected path:") + "\n" + template_path + "\n";
472 }
473 return String();
474 }
475
476 bool EditorExportPlatform::exists_export_template(const String &template_file_name, String *err) const {
477 return find_export_template(template_file_name, err) != "";
478 }
479
480 Ref<EditorExportPreset> EditorExportPlatform::create_preset() {
481 Ref<EditorExportPreset> preset;
482 preset.instantiate();
483 preset->platform = Ref<EditorExportPlatform>(this);
484
485 List<ExportOption> options;
486 get_export_options(&options);
487
488 Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
489 for (int i = 0; i < export_plugins.size(); i++) {
490 export_plugins.write[i]->_get_export_options(Ref<EditorExportPlatform>(this), &options);
491 }
492
493 for (const ExportOption &E : options) {
494 StringName option_name = E.option.name;
495 preset->properties[option_name] = E.option;
496 preset->values[option_name] = E.default_value;
497 preset->update_visibility[option_name] = E.update_visibility;
498 }
499
500 return preset;
501 }
502
503 void EditorExportPlatform::_export_find_resources(EditorFileSystemDirectory *p_dir, HashSet<String> &p_paths) {
504 for (int i = 0; i < p_dir->get_subdir_count(); i++) {
505 _export_find_resources(p_dir->get_subdir(i), p_paths);
506 }
507
508 for (int i = 0; i < p_dir->get_file_count(); i++) {
509 if (p_dir->get_file_type(i) == "TextFile") {
510 continue;
511 }
512 p_paths.insert(p_dir->get_file_path(i));
513 }
514 }
515
516 void EditorExportPlatform::_export_find_customized_resources(const Ref<EditorExportPreset> &p_preset, EditorFileSystemDirectory *p_dir, EditorExportPreset::FileExportMode p_mode, HashSet<String> &p_paths) {
517 for (int i = 0; i < p_dir->get_subdir_count(); i++) {
518 EditorFileSystemDirectory *subdir = p_dir->get_subdir(i);
519 _export_find_customized_resources(p_preset, subdir, p_preset->get_file_export_mode(subdir->get_path(), p_mode), p_paths);
520 }
521
522 for (int i = 0; i < p_dir->get_file_count(); i++) {
523 if (p_dir->get_file_type(i) == "TextFile") {
524 continue;
525 }
526 String path = p_dir->get_file_path(i);
527 EditorExportPreset::FileExportMode file_mode = p_preset->get_file_export_mode(path, p_mode);
528 if (file_mode != EditorExportPreset::MODE_FILE_REMOVE) {
529 p_paths.insert(path);
530 }
531 }
532 }
533
534 void EditorExportPlatform::_export_find_dependencies(const String &p_path, HashSet<String> &p_paths) {
535 if (p_paths.has(p_path)) {
536 return;
537 }
538
539 p_paths.insert(p_path);
540
541 EditorFileSystemDirectory *dir;
542 int file_idx;
543 dir = EditorFileSystem::get_singleton()->find_file(p_path, &file_idx);
544 if (!dir) {
545 return;
546 }
547
548 Vector<String> deps = dir->get_file_deps(file_idx);
549
550 for (int i = 0; i < deps.size(); i++) {
551 _export_find_dependencies(deps[i], p_paths);
552 }
553 }
554
555 void EditorExportPlatform::_edit_files_with_filter(Ref<DirAccess> &da, const Vector<String> &p_filters, HashSet<String> &r_list, bool exclude) {
556 da->list_dir_begin();
557 String cur_dir = da->get_current_dir().replace_char('\\', '/');
558 if (!cur_dir.ends_with("/")) {
559 cur_dir += "/";
560 }
561 String cur_dir_no_prefix = cur_dir.replace("res://", "");
562
563 Vector<String> dirs;
564 String f = da->get_next();
565 while (!f.is_empty()) {
566 if (da->current_is_dir()) {
567 dirs.push_back(f);
568 } else {
569 String fullpath = cur_dir + f;
570 // Test also against path without res:// so that filters like `file.txt` can work.
571 String fullpath_no_prefix = cur_dir_no_prefix + f;
572 for (int i = 0; i < p_filters.size(); ++i) {
573 if (fullpath.matchn(p_filters[i]) || fullpath_no_prefix.matchn(p_filters[i])) {
574 if (!exclude) {
575 r_list.insert(fullpath);
576 } else {
577 r_list.erase(fullpath);
578 }
579 }
580 }
581 }
582 f = da->get_next();
583 }
584
585 da->list_dir_end();
586
587 for (int i = 0; i < dirs.size(); ++i) {
588 const String &dir = dirs[i];
589 if (dir.begins_with(".")) {
590 continue;
591 }
592
593 if (EditorFileSystem::_should_skip_directory(cur_dir + dir)) {
594 continue;
595 }
596
597 da->change_dir(dir);
598 _edit_files_with_filter(da, p_filters, r_list, exclude);
599 da->change_dir("..");
600 }
601 }
602
603 void EditorExportPlatform::_edit_filter_list(HashSet<String> &r_list, const String &p_filter, bool exclude) {
604 if (p_filter.is_empty()) {
605 return;
606 }
607 Vector<String> split = p_filter.split(",");
608 Vector<String> filters;
609 for (int i = 0; i < split.size(); i++) {
610 String f = split[i].strip_edges();
611 if (f.is_empty()) {
612 continue;
613 }
614 filters.push_back(f);
615 }
616
617 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
618 ERR_FAIL_COND(da.is_null());
619 _edit_files_with_filter(da, filters, r_list, exclude);
620 }
621
622 HashSet<String> EditorExportPlatform::get_features(const Ref<EditorExportPreset> &p_preset, bool p_debug) const {
623 Ref<EditorExportPlatform> platform = p_preset->get_platform();
624 List<String> feature_list;
625 platform->get_platform_features(&feature_list);
626 platform->get_preset_features(p_preset, &feature_list);
627
628 HashSet<String> result;
629 for (const String &E : feature_list) {
630 result.insert(E);
631 }
632
633 result.insert("template");
634 if (p_debug) {
635 result.insert("debug");
636 result.insert("template_debug");
637 } else {
638 result.insert("release");
639 result.insert("template_release");
640 }
641
642 #ifdef REAL_T_IS_DOUBLE
643 result.insert("double");
644 #else
645 result.insert("single");
646 #endif // REAL_T_IS_DOUBLE
647
648 if (!p_preset->get_custom_features().is_empty()) {
649 Vector<String> tmp_custom_list = p_preset->get_custom_features().split(",");
650
651 for (int i = 0; i < tmp_custom_list.size(); i++) {
652 String f = tmp_custom_list[i].strip_edges();
653 if (!f.is_empty()) {
654 result.insert(f);
655 }
656 }
657 }
658
659 return result;
660 }
661
662 EditorExportPlatform::ExportNotifier::ExportNotifier(EditorExportPlatform &p_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
663 HashSet<String> features = p_platform.get_features(p_preset, p_debug);
664 Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
665 //initial export plugin callback
666 for (int i = 0; i < export_plugins.size(); i++) {
667 export_plugins.write[i]->set_export_preset(p_preset);
668 if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_begin)) {
669 PackedStringArray features_psa;
670 for (const String &feature : features) {
671 features_psa.push_back(feature);
672 }
673 export_plugins.write[i]->_export_begin_script(features_psa, p_debug, p_path, p_flags);
674 } else {
675 export_plugins.write[i]->_export_begin(features, p_debug, p_path, p_flags);
676 }
677 }
678 }
679
680 EditorExportPlatform::ExportNotifier::~ExportNotifier() {
681 Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
682 for (int i = 0; i < export_plugins.size(); i++) {
683 if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_end)) {
684 export_plugins.write[i]->_export_end_script();
685 } else {
686 export_plugins.write[i]->_export_end();
687 }
688 export_plugins.write[i]->_export_end_clear();
689 export_plugins.write[i]->set_export_preset(Ref<EditorExportPreset>());
690 }
691 }
692
693 bool EditorExportPlatform::_export_customize_dictionary(Dictionary &dict, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
694 bool changed = false;
695
696 for (const Variant &K : dict.get_key_list()) {
697 Variant v = dict[K];
698 switch (v.get_type()) {
699 case Variant::OBJECT: {
700 Ref<Resource> res = v;
701 if (res.is_valid()) {
702 for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
703 Ref<Resource> new_res = plugin->_customize_resource(res, "");
704 if (new_res.is_valid()) {
705 changed = true;
706 if (new_res != res) {
707 dict[K] = new_res;
708 res = new_res;
709 }
710 break;
711 }
712 }
713
714 // If it was not replaced, go through and see if there is something to replace.
715 if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins)) {
716 changed = true;
717 }
718 }
719
720 } break;
721 case Variant::DICTIONARY: {
722 Dictionary d = v;
723 if (_export_customize_dictionary(d, customize_resources_plugins)) {
724 changed = true;
725 }
726 } break;
727 case Variant::ARRAY: {
728 Array a = v;
729 if (_export_customize_array(a, customize_resources_plugins)) {
730 changed = true;
731 }
732 } break;
733 default: {
734 }
735 }
736 }
737 return changed;
738 }
739
740 bool EditorExportPlatform::_export_customize_array(Array &arr, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
741 bool changed = false;
742
743 for (int i = 0; i < arr.size(); i++) {
744 Variant v = arr.get(i);
745 switch (v.get_type()) {
746 case Variant::OBJECT: {
747 Ref<Resource> res = v;
748 if (res.is_valid()) {
749 for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
750 Ref<Resource> new_res = plugin->_customize_resource(res, "");
751 if (new_res.is_valid()) {
752 changed = true;
753 if (new_res != res) {
754 arr.set(i, new_res);
755 res = new_res;
756 }
757 break;
758 }
759 }
760
761 // If it was not replaced, go through and see if there is something to replace.
762 if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins)) {
763 changed = true;
764 }
765 }
766 } break;
767 case Variant::DICTIONARY: {
768 Dictionary d = v;
769 if (_export_customize_dictionary(d, customize_resources_plugins)) {
770 changed = true;
771 }
772 } break;
773 case Variant::ARRAY: {
774 Array a = v;
775 if (_export_customize_array(a, customize_resources_plugins)) {
776 changed = true;
777 }
778 } break;
779 default: {
780 }
781 }
782 }
783 return changed;
784 }
785
786 bool EditorExportPlatform::_export_customize_object(Object *p_object, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
787 bool changed = false;
788
789 List<PropertyInfo> props;
790 p_object->get_property_list(&props);
791 for (const PropertyInfo &E : props) {
792 switch (E.type) {
793 case Variant::OBJECT: {
794 Ref<Resource> res = p_object->get(E.name);
795 if (res.is_valid()) {
796 for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
797 Ref<Resource> new_res = plugin->_customize_resource(res, "");
798 if (new_res.is_valid()) {
799 changed = true;
800 if (new_res != res) {
801 p_object->set(E.name, new_res);
802 res = new_res;
803 }
804 break;
805 }
806 }
807
808 // If it was not replaced, go through and see if there is something to replace.
809 if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins)) {
810 changed = true;
811 }
812 }
813
814 } break;
815 case Variant::DICTIONARY: {
816 Dictionary d = p_object->get(E.name);
817 if (_export_customize_dictionary(d, customize_resources_plugins)) {
818 if (p_object->get(E.name) != d) {
819 p_object->set(E.name, d);
820 }
821
822 changed = true;
823 }
824 } break;
825 case Variant::ARRAY: {
826 Array a = p_object->get(E.name);
827 if (_export_customize_array(a, customize_resources_plugins)) {
828 if (p_object->get(E.name) != a) {
829 p_object->set(E.name, a);
830 }
831
832 changed = true;
833 }
834 } break;
835 default: {
836 }
837 }
838 }
839 return changed;
840 }
841
842 bool EditorExportPlatform::_is_editable_ancestor(Node *p_root, Node *p_node) {
843 while (p_node != nullptr && p_node != p_root) {
844 if (p_root->is_editable_instance(p_node)) {
845 return true;
846 }
847 p_node = p_node->get_owner();
848 }
849 return false;
850 }
851
852 bool EditorExportPlatform::_export_customize_scene_resources(Node *p_root, Node *p_node, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
853 bool changed = false;
854
855 if (p_root == p_node || p_node->get_owner() == p_root || _is_editable_ancestor(p_root, p_node)) {
856 if (_export_customize_object(p_node, customize_resources_plugins)) {
857 changed = true;
858 }
859 }
860
861 for (int i = 0; i < p_node->get_child_count(); i++) {
862 if (_export_customize_scene_resources(p_root, p_node->get_child(i), customize_resources_plugins)) {
863 changed = true;
864 }
865 }
866
867 return changed;
868 }
869
870 String EditorExportPlatform::_export_customize(const String &p_path, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins, LocalVector<Ref<EditorExportPlugin>> &customize_scenes_plugins, HashMap<String, FileExportCache> &export_cache, const String &export_base_path, bool p_force_save) {
871 if (!p_force_save && customize_resources_plugins.is_empty() && customize_scenes_plugins.is_empty()) {
872 return p_path; // do none
873 }
874
875 // Check if a cache exists
876 if (export_cache.has(p_path)) {
877 FileExportCache &fec = export_cache[p_path];
878
879 if (fec.saved_path.is_empty() || FileAccess::exists(fec.saved_path)) {
880 // Destination file exists (was not erased) or not needed
881
882 uint64_t mod_time = FileAccess::get_modified_time(p_path);
883 if (fec.source_modified_time == mod_time) {
884 // Cached (modified time matches).
885 fec.used = true;
886 return fec.saved_path.is_empty() ? p_path : fec.saved_path;
887 }
888
889 String md5 = FileAccess::get_md5(p_path);
890 if (FileAccess::exists(p_path + ".import")) {
891 // Also consider the import file in the string
892 md5 += FileAccess::get_md5(p_path + ".import");
893 }
894 if (fec.source_md5 == md5) {
895 // Cached (md5 matches).
896 fec.source_modified_time = mod_time;
897 fec.used = true;
898 return fec.saved_path.is_empty() ? p_path : fec.saved_path;
899 }
900 }
901 }
902
903 FileExportCache fec;
904 fec.used = true;
905 fec.source_modified_time = FileAccess::get_modified_time(p_path);
906
907 String md5 = FileAccess::get_md5(p_path);
908 if (FileAccess::exists(p_path + ".import")) {
909 // Also consider the import file in the string
910 md5 += FileAccess::get_md5(p_path + ".import");
911 }
912
913 fec.source_md5 = md5;
914
915 // Check if it should convert
916
917 String type = ResourceLoader::get_resource_type(p_path);
918
919 bool modified = false;
920
921 String save_path;
922
923 if (type == "PackedScene") { // Its a scene.
924 Ref<PackedScene> ps = ResourceLoader::load(p_path, "PackedScene", ResourceFormatLoader::CACHE_MODE_IGNORE);
925 ERR_FAIL_COND_V(ps.is_null(), p_path);
926 Node *node = ps->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE); // Make sure the child scene root gets the correct inheritance chain.
927 ERR_FAIL_NULL_V(node, p_path);
928 if (!customize_scenes_plugins.is_empty()) {
929 for (Ref<EditorExportPlugin> &plugin : customize_scenes_plugins) {
930 Node *customized = plugin->_customize_scene(node, p_path);
931 if (customized != nullptr) {
932 node = customized;
933 modified = true;
934 }
935 }
936 }
937 if (!customize_resources_plugins.is_empty()) {
938 if (_export_customize_scene_resources(node, node, customize_resources_plugins)) {
939 modified = true;
940 }
941 }
942
943 if (modified || p_force_save) {
944 // If modified, save it again. This is also used for TSCN -> SCN conversion on export.
945
946 String base_file = p_path.get_file().get_basename() + ".scn"; // use SCN for saving (binary) and repack (If conversting, TSCN PackedScene representation is inefficient, so repacking is also desired).
947 save_path = export_base_path.path_join("export-" + p_path.md5_text() + "-" + base_file);
948
949 Ref<PackedScene> s;
950 s.instantiate();
951 s->pack(node);
952 Error err = ResourceSaver::save(s, save_path);
953 ERR_FAIL_COND_V_MSG(err != OK, p_path, "Unable to save export scene file to: " + save_path);
954 }
955
956 node->queue_free();
957 } else {
958 Ref<Resource> res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_IGNORE);
959 ERR_FAIL_COND_V(res.is_null(), p_path);
960
961 if (!customize_resources_plugins.is_empty()) {
962 for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
963 Ref<Resource> new_res = plugin->_customize_resource(res, p_path);
964 if (new_res.is_valid()) {
965 modified = true;
966 if (new_res != res) {
967 res = new_res;
968 }
969 break;
970 }
971 }
972
973 if (_export_customize_object(res.ptr(), customize_resources_plugins)) {
974 modified = true;
975 }
976 }
977
978 if (modified || p_force_save) {
979 // If modified, save it again. This is also used for TRES -> RES conversion on export.
980
981 String base_file = p_path.get_file().get_basename() + ".res"; // use RES for saving (binary)
982 save_path = export_base_path.path_join("export-" + p_path.md5_text() + "-" + base_file);
983
984 Error err = ResourceSaver::save(res, save_path);
985 ERR_FAIL_COND_V_MSG(err != OK, p_path, "Unable to save export resource file to: " + save_path);
986 }
987 }
988
989 fec.saved_path = save_path;
990
991 export_cache[p_path] = fec;
992
993 return save_path.is_empty() ? p_path : save_path;
994 }
995
996 String EditorExportPlatform::_get_script_encryption_key(const Ref<EditorExportPreset> &p_preset) const {
997 const String from_env = OS::get_singleton()->get_environment(ENV_SCRIPT_ENCRYPTION_KEY);
998 if (!from_env.is_empty()) {
999 return from_env.to_lower();
1000 }
1001 return p_preset->get_script_encryption_key().to_lower();
1002 }
1003
1004 Dictionary EditorExportPlatform::get_internal_export_files(const Ref<EditorExportPreset> &p_preset, bool p_debug) {
1005 Dictionary files;
1006
1007 // Text server support data.
1008 if (TS->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
1009 bool include_data = (bool)get_project_setting(p_preset, "internationalization/locale/include_text_server_data");
1010 if (!include_data) {
1011 Vector<String> translations = get_project_setting(p_preset, "internationalization/locale/translations");
1012 for (const String &t : translations) {
1013 Ref<Translation> tr = ResourceLoader::load(t);
1014 if (tr.is_valid() && TS->is_locale_using_support_data(tr->get_locale())) {
1015 include_data = true;
1016 break;
1017 }
1018 }
1019 if (TS->is_locale_using_support_data(get_project_setting(p_preset, "internationalization/locale/fallback"))) {
1020 include_data = true;
1021 }
1022 }
1023 if (include_data) {
1024 String ts_name = TS->get_support_data_filename();
1025 String ts_target = "res://" + ts_name;
1026 if (!ts_name.is_empty()) {
1027 bool export_ok = false;
1028 if (FileAccess::exists(ts_target)) { // Include user supplied data file.
1029 const PackedByteArray &ts_data = FileAccess::get_file_as_bytes(ts_target);
1030 if (!ts_data.is_empty()) {
1031 add_message(EXPORT_MESSAGE_INFO, TTR("Export"), TTR("Using user provided text server data, text display in the exported project might be broken if export template was built with different ICU version!"));
1032 files[ts_target] = ts_data;
1033 export_ok = true;
1034 }
1035 } else {
1036 String current_version = GODOT_VERSION_FULL_CONFIG;
1037 String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(current_version);
1038 if (p_debug && p_preset->has("custom_template/debug") && p_preset->get("custom_template/debug") != "") {
1039 template_path = p_preset->get("custom_template/debug").operator String().get_base_dir();
1040 } else if (!p_debug && p_preset->has("custom_template/release") && p_preset->get("custom_template/release") != "") {
1041 template_path = p_preset->get("custom_template/release").operator String().get_base_dir();
1042 }
1043 String data_file_name = template_path.path_join(ts_name);
1044 if (FileAccess::exists(data_file_name)) {
1045 const PackedByteArray &ts_data = FileAccess::get_file_as_bytes(data_file_name);
1046 if (!ts_data.is_empty()) {
1047 print_line("Using text server data from export templates.");
1048 files[ts_target] = ts_data;
1049 export_ok = true;
1050 }
1051 } else {
1052 const PackedByteArray &ts_data = TS->get_support_data();
1053 if (!ts_data.is_empty()) {
1054 add_message(EXPORT_MESSAGE_INFO, TTR("Export"), TTR("Using editor embedded text server data, text display in the exported project might be broken if export template was built with different ICU version!"));
1055 files[ts_target] = ts_data;
1056 export_ok = true;
1057 }
1058 }
1059 }
1060 if (!export_ok) {
1061 add_message(EXPORT_MESSAGE_WARNING, TTR("Export"), TTR("Missing text server data, text display in the exported project might be broken!"));
1062 }
1063 }
1064 }
1065 }
1066
1067 return files;
1068 }
1069
1070 Vector<String> EditorExportPlatform::get_forced_export_files(const Ref<EditorExportPreset> &p_preset) {
1071 Vector<String> files;
1072
1073 files.push_back(ProjectSettings::get_singleton()->get_global_class_list_path());
1074
1075 String icon = ResourceUID::ensure_path(get_project_setting(p_preset, "application/config/icon"));
1076 String splash = ResourceUID::ensure_path(get_project_setting(p_preset, "application/boot_splash/image"));
1077 if (!icon.is_empty() && FileAccess::exists(icon)) {
1078 files.push_back(icon);
1079 }
1080 if (!splash.is_empty() && FileAccess::exists(splash) && icon != splash) {
1081 files.push_back(splash);
1082 }
1083 String resource_cache_file = ResourceUID::get_cache_file();
1084 if (FileAccess::exists(resource_cache_file)) {
1085 files.push_back(resource_cache_file);
1086 }
1087
1088 String extension_list_config_file = GDExtension::get_extension_list_config_file();
1089 if (FileAccess::exists(extension_list_config_file)) {
1090 files.push_back(extension_list_config_file);
1091 }
1092
1093 return files;
1094 }
1095
1096 Error EditorExportPlatform::_script_save_file(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) {
1097 Callable cb = ((ScriptCallbackData *)p_userdata)->file_cb;
1098 ERR_FAIL_COND_V(!cb.is_valid(), FAILED);
1099
1100 const String simplified_path = simplify_path(p_path);
1101
1102 Variant path = simplified_path;
1103 Variant data = p_data;
1104 Variant file = p_file;
1105 Variant total = p_total;
1106 Variant enc_in = p_enc_in_filters;
1107 Variant enc_ex = p_enc_ex_filters;
1108 Variant enc_key = p_key;
1109
1110 Variant ret;
1111 Callable::CallError ce;
1112 const Variant *args[7] = { &path, &data, &file, &total, &enc_in, &enc_ex, &enc_key };
1113
1114 cb.callp(args, 7, ret, ce);
1115 ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, FAILED, vformat("Failed to execute file save callback: %s.", Variant::get_callable_error_text(cb, args, 7, ce)));
1116
1117 return (Error)ret.operator int();
1118 }
1119
1120 Error EditorExportPlatform::_script_add_shared_object(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const SharedObject &p_so) {
1121 Callable cb = ((ScriptCallbackData *)p_userdata)->so_cb;
1122 if (!cb.is_valid()) {
1123 return OK; // Optional.
1124 }
1125
1126 Variant path = p_so.path;
1127 Variant tags = p_so.tags;
1128 Variant target = p_so.target;
1129
1130 Variant ret;
1131 Callable::CallError ce;
1132 const Variant *args[3] = { &path, &tags, &target };
1133
1134 cb.callp(args, 3, ret, ce);
1135 ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, FAILED, vformat("Failed to execute shared object save callback: %s.", Variant::get_callable_error_text(cb, args, 3, ce)));
1136
1137 return (Error)ret.operator int();
1138 }
1139
1140 Error EditorExportPlatform::_export_project_files(const Ref<EditorExportPreset> &p_preset, bool p_debug, const Callable &p_save_func, const Callable &p_so_func) {
1141 ScriptCallbackData data;
1142 data.file_cb = p_save_func;
1143 data.so_cb = p_so_func;
1144 return export_project_files(p_preset, p_debug, _script_save_file, nullptr, &data, _script_add_shared_object);
1145 }
1146
1147 Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &p_preset, bool p_debug, EditorExportSaveFunction p_save_func, EditorExportRemoveFunction p_remove_func, void *p_udata, EditorExportSaveSharedObject p_so_func) {
1148 //figure out paths of files that will be exported
1149 HashSet<String> paths;
1150 Vector<String> path_remaps;
1151
1152 if (p_preset->get_export_filter() == EditorExportPreset::EXPORT_ALL_RESOURCES) {
1153 //find stuff
1154 _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(), paths);
1155 } else if (p_preset->get_export_filter() == EditorExportPreset::EXCLUDE_SELECTED_RESOURCES) {
1156 _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(), paths);
1157 Vector<String> files = p_preset->get_files_to_export();
1158 for (int i = 0; i < files.size(); i++) {
1159 paths.erase(files[i]);
1160 }
1161 } else if (p_preset->get_export_filter() == EditorExportPreset::EXPORT_CUSTOMIZED) {
1162 _export_find_customized_resources(p_preset, EditorFileSystem::get_singleton()->get_filesystem(), p_preset->get_file_export_mode("res://"), paths);
1163 } else {
1164 bool scenes_only = p_preset->get_export_filter() == EditorExportPreset::EXPORT_SELECTED_SCENES;
1165
1166 Vector<String> files = p_preset->get_files_to_export();
1167 for (int i = 0; i < files.size(); i++) {
1168 if (scenes_only && ResourceLoader::get_resource_type(files[i]) != "PackedScene") {
1169 continue;
1170 }
1171
1172 _export_find_dependencies(files[i], paths);
1173 }
1174
1175 // Add autoload resources and their dependencies
1176 List<PropertyInfo> props;
1177 ProjectSettings::get_singleton()->get_property_list(&props);
1178
1179 for (const PropertyInfo &pi : props) {
1180 if (!pi.name.begins_with("autoload/")) {
1181 continue;
1182 }
1183
1184 String autoload_path = get_project_setting(p_preset, pi.name);
1185
1186 if (autoload_path.begins_with("*")) {
1187 autoload_path = autoload_path.substr(1);
1188 }
1189
1190 _export_find_dependencies(autoload_path, paths);
1191 }
1192 }
1193
1194 //add native icons to non-resource include list
1195 _edit_filter_list(paths, String("*.icns"), false);
1196 _edit_filter_list(paths, String("*.ico"), false);
1197
1198 _edit_filter_list(paths, p_preset->get_include_filter(), false);
1199 _edit_filter_list(paths, p_preset->get_exclude_filter(), true);
1200
1201 // Ignore import files, since these are automatically added to the jar later with the resources
1202 _edit_filter_list(paths, String("*.import"), true);
1203
1204 // Get encryption filters.
1205 bool enc_pck = p_preset->get_enc_pck();
1206 Vector<String> enc_in_filters;
1207 Vector<String> enc_ex_filters;
1208 Vector<uint8_t> key;
1209 uint64_t seed = 0;
1210
1211 if (enc_pck) {
1212 seed = p_preset->get_seed();
1213 Vector<String> enc_in_split = p_preset->get_enc_in_filter().split(",");
1214 for (int i = 0; i < enc_in_split.size(); i++) {
1215 String f = enc_in_split[i].strip_edges();
1216 if (f.is_empty()) {
1217 continue;
1218 }
1219 enc_in_filters.push_back(f);
1220 }
1221
1222 Vector<String> enc_ex_split = p_preset->get_enc_ex_filter().split(",");
1223 for (int i = 0; i < enc_ex_split.size(); i++) {
1224 String f = enc_ex_split[i].strip_edges();
1225 if (f.is_empty()) {
1226 continue;
1227 }
1228 enc_ex_filters.push_back(f);
1229 }
1230
1231 // Get encryption key.
1232 String script_key = _get_script_encryption_key(p_preset);
1233 key.resize(32);
1234 if (script_key.length() == 64) {
1235 for (int i = 0; i < 32; i++) {
1236 int v = 0;
1237 if (i * 2 < script_key.length()) {
1238 char32_t ct = script_key[i * 2];
1239 if (is_digit(ct)) {
1240 ct = ct - '0';
1241 } else if (ct >= 'a' && ct <= 'f') {
1242 ct = 10 + ct - 'a';
1243 }
1244 v |= ct << 4;
1245 }
1246
1247 if (i * 2 + 1 < script_key.length()) {
1248 char32_t ct = script_key[i * 2 + 1];
1249 if (is_digit(ct)) {
1250 ct = ct - '0';
1251 } else if (ct >= 'a' && ct <= 'f') {
1252 ct = 10 + ct - 'a';
1253 }
1254 v |= ct;
1255 }
1256 key.write[i] = v;
1257 }
1258 }
1259 }
1260
1261 EditorExportSaveProxy save_proxy(p_save_func, p_remove_func != nullptr);
1262
1263 Error err = OK;
1264 Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
1265
1266 struct SortByName {
1267 bool operator()(const Ref<EditorExportPlugin> &left, const Ref<EditorExportPlugin> &right) const {
1268 return left->get_name() < right->get_name();
1269 }
1270 };
1271
1272 auto add_shared_objects_and_extra_files_from_export_plugins = [&]() {
1273 for (int i = 0; i < export_plugins.size(); i++) {
1274 if (p_so_func) {
1275 for (int j = 0; j < export_plugins[i]->shared_objects.size(); j++) {
1276 err = p_so_func(p_preset, p_udata, export_plugins[i]->shared_objects[j]);
1277 if (err != OK) {
1278 return err;
1279 }
1280 }
1281 }
1282 for (int j = 0; j < export_plugins[i]->extra_files.size(); j++) {
1283 err = save_proxy.save_file(p_preset, p_udata, export_plugins[i]->extra_files[j].path, export_plugins[i]->extra_files[j].data, 0, paths.size(), enc_in_filters, enc_ex_filters, key, seed, false);
1284 if (err != OK) {
1285 return err;
1286 }
1287 }
1288
1289 export_plugins.write[i]->_clear();
1290 }
1291
1292 return OK;
1293 };
1294
1295 // Always sort by name, to so if for some reason they are re-arranged, it still works.
1296 export_plugins.sort_custom<SortByName>();
1297
1298 HashSet<String> features = get_features(p_preset, p_debug);
1299 PackedStringArray features_psa;
1300 for (const String &feature : features) {
1301 features_psa.push_back(feature);
1302 }
1303
1304 // Check if custom processing is needed
1305 uint32_t custom_resources_hash = HASH_MURMUR3_SEED;
1306 uint32_t custom_scene_hash = HASH_MURMUR3_SEED;
1307
1308 LocalVector<Ref<EditorExportPlugin>> customize_resources_plugins;
1309 LocalVector<Ref<EditorExportPlugin>> customize_scenes_plugins;
1310
1311 for (int i = 0; i < export_plugins.size(); i++) {
1312 if (export_plugins.write[i]->_begin_customize_resources(Ref<EditorExportPlatform>(this), features_psa)) {
1313 customize_resources_plugins.push_back(export_plugins[i]);
1314
1315 custom_resources_hash = hash_murmur3_one_64(export_plugins[i]->get_name().hash64(), custom_resources_hash);
1316 uint64_t hash = export_plugins[i]->_get_customization_configuration_hash();
1317 custom_resources_hash = hash_murmur3_one_64(hash, custom_resources_hash);
1318 }
1319 if (export_plugins.write[i]->_begin_customize_scenes(Ref<EditorExportPlatform>(this), features_psa)) {
1320 customize_scenes_plugins.push_back(export_plugins[i]);
1321
1322 custom_resources_hash = hash_murmur3_one_64(export_plugins[i]->get_name().hash64(), custom_resources_hash);
1323 uint64_t hash = export_plugins[i]->_get_customization_configuration_hash();
1324 custom_scene_hash = hash_murmur3_one_64(hash, custom_scene_hash);
1325 }
1326 }
1327
1328 // Add any files that might've been defined during the initial steps of the export plugins.
1329 err = add_shared_objects_and_extra_files_from_export_plugins();
1330 if (err != OK) {
1331 return err;
1332 }
1333
1334 HashMap<String, FileExportCache> export_cache;
1335 String export_base_path = ProjectSettings::get_singleton()->get_project_data_path().path_join("exported/") + itos(custom_resources_hash);
1336
1337 bool convert_text_to_binary = get_project_setting(p_preset, "editor/export/convert_text_resources_to_binary");
1338
1339 if (convert_text_to_binary || !customize_resources_plugins.is_empty() || !customize_scenes_plugins.is_empty()) {
1340 // See if we have something to open
1341 Ref<FileAccess> f = FileAccess::open(export_base_path.path_join("file_cache"), FileAccess::READ);
1342 if (f.is_valid()) {
1343 String l = f->get_line();
1344 while (l != String()) {
1345 Vector<String> fields = l.split("::");
1346 if (fields.size() == 4) {
1347 FileExportCache fec;
1348 const String &path = fields[0];
1349 fec.source_md5 = fields[1].strip_edges();
1350 fec.source_modified_time = fields[2].strip_edges().to_int();
1351 fec.saved_path = fields[3];
1352 fec.used = false; // Assume unused until used.
1353 export_cache[path] = fec;
1354 }
1355 l = f->get_line();
1356 }
1357 } else {
1358 // create the path
1359 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1360 d->change_dir(ProjectSettings::get_singleton()->get_project_data_path());
1361 d->make_dir_recursive("exported/" + itos(custom_resources_hash));
1362 }
1363 }
1364
1365 for (int i = 0; i < export_plugins.size(); i++) {
1366 export_plugins.write[i]->set_export_base_path(export_base_path);
1367 }
1368
1369 //store everything in the export medium
1370 int total = paths.size();
1371 // idx is incremented at the beginning of the paths loop to easily allow
1372 // for continue statements without accidentally skipping an increment.
1373 int idx = total > 0 ? -1 : 0;
1374
1375 for (const String &path : paths) {
1376 idx++;
1377 String type = ResourceLoader::get_resource_type(path);
1378
1379 bool has_import_file = FileAccess::exists(path + ".import");
1380 Ref<ConfigFile> config;
1381 if (has_import_file) {
1382 config.instantiate();
1383 err = config->load(path + ".import");
1384 if (err != OK) {
1385 ERR_PRINT("Could not parse: '" + path + "', not exported.");
1386 continue;
1387 }
1388
1389 String importer_type = config->get_value("remap", "importer");
1390
1391 if (importer_type == "skip") {
1392 // Skip file.
1393 continue;
1394 }
1395 }
1396
1397 bool do_export = true;
1398 for (int i = 0; i < export_plugins.size(); i++) {
1399 if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_file)) {
1400 export_plugins.write[i]->_export_file_script(path, type, features_psa);
1401 } else {
1402 export_plugins.write[i]->_export_file(path, type, features);
1403 }
1404 if (p_so_func) {
1405 for (int j = 0; j < export_plugins[i]->shared_objects.size(); j++) {
1406 err = p_so_func(p_preset, p_udata, export_plugins[i]->shared_objects[j]);
1407 if (err != OK) {
1408 return err;
1409 }
1410 }
1411 }
1412
1413 for (int j = 0; j < export_plugins[i]->extra_files.size(); j++) {
1414 err = save_proxy.save_file(p_preset, p_udata, export_plugins[i]->extra_files[j].path, export_plugins[i]->extra_files[j].data, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1415 if (err != OK) {
1416 return err;
1417 }
1418 if (export_plugins[i]->extra_files[j].remap) {
1419 do_export = false; // If remap, do not.
1420 path_remaps.push_back(path);
1421 path_remaps.push_back(export_plugins[i]->extra_files[j].path);
1422 }
1423 }
1424
1425 if (export_plugins[i]->skipped) {
1426 do_export = false;
1427 }
1428 export_plugins.write[i]->_clear();
1429
1430 if (!do_export) {
1431 break;
1432 }
1433 }
1434 if (!do_export) {
1435 continue;
1436 }
1437
1438 if (has_import_file) {
1439 String importer_type = config->get_value("remap", "importer");
1440
1441 if (importer_type == "keep") {
1442 // Just keep file as-is.
1443 Vector<uint8_t> array = FileAccess::get_file_as_bytes(path);
1444 err = save_proxy.save_file(p_preset, p_udata, path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1445
1446 if (err != OK) {
1447 return err;
1448 }
1449
1450 continue;
1451 }
1452
1453 // Before doing this, try to see if it can be customized.
1454 String export_path = _export_customize(path, customize_resources_plugins, customize_scenes_plugins, export_cache, export_base_path, false);
1455
1456 if (export_path != path) {
1457 // It was actually customized.
1458 // Since the original file is likely not recognized, just use the import system.
1459
1460 config->set_value("remap", "type", ResourceLoader::get_resource_type(export_path));
1461
1462 // Erase all Paths.
1463 Vector<String> keys = config->get_section_keys("remap");
1464 for (const String &K : keys) {
1465 if (K.begins_with("path")) {
1466 config->erase_section_key("remap", K);
1467 }
1468 }
1469 // Set actual converted path.
1470 config->set_value("remap", "path", export_path);
1471
1472 // Erase useless sections.
1473 if (config->has_section("deps")) {
1474 config->erase_section("deps");
1475 }
1476 if (config->has_section("params")) {
1477 config->erase_section("params");
1478 }
1479
1480 String import_text = config->encode_to_text();
1481 CharString cs = import_text.utf8();
1482 Vector<uint8_t> sarr;
1483 sarr.resize(cs.size());
1484 memcpy(sarr.ptrw(), cs.ptr(), sarr.size());
1485
1486 err = save_proxy.save_file(p_preset, p_udata, path + ".import", sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1487 if (err != OK) {
1488 return err;
1489 }
1490 // Now actual remapped file:
1491 sarr = FileAccess::get_file_as_bytes(export_path);
1492 err = save_proxy.save_file(p_preset, p_udata, export_path, sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1493 if (err != OK) {
1494 return err;
1495 }
1496 } else {
1497 // File is imported and not customized, replace by what it imports.
1498 Vector<String> remaps = config->get_section_keys("remap");
1499 HashSet<String> remap_features;
1500
1501 for (const String &F : remaps) {
1502 String remap = F;
1503 String feature = remap.get_slicec('.', 1);
1504 if (features.has(feature)) {
1505 remap_features.insert(feature);
1506 }
1507 }
1508
1509 if (remap_features.size() > 1) {
1510 resolve_platform_feature_priorities(p_preset, remap_features);
1511 }
1512
1513 err = OK;
1514
1515 for (const String &F : remaps) {
1516 String remap = F;
1517 if (remap == "path") {
1518 String remapped_path = config->get_value("remap", remap);
1519 Vector<uint8_t> array = FileAccess::get_file_as_bytes(remapped_path);
1520 err = save_proxy.save_file(p_preset, p_udata, remapped_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1521 } else if (remap.begins_with("path.")) {
1522 String feature = remap.get_slicec('.', 1);
1523
1524 if (remap_features.has(feature)) {
1525 String remapped_path = config->get_value("remap", remap);
1526 Vector<uint8_t> array = FileAccess::get_file_as_bytes(remapped_path);
1527 err = save_proxy.save_file(p_preset, p_udata, remapped_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1528 } else {
1529 // Remove paths if feature not enabled.
1530 config->erase_section_key("remap", remap);
1531 }
1532 }
1533 }
1534
1535 if (err != OK) {
1536 return err;
1537 }
1538
1539 // Erase useless sections.
1540 if (config->has_section("deps")) {
1541 config->erase_section("deps");
1542 }
1543 if (config->has_section("params")) {
1544 config->erase_section("params");
1545 }
1546
1547 String import_text = config->encode_to_text();
1548 CharString cs = import_text.utf8();
1549 Vector<uint8_t> sarr;
1550 sarr.resize(cs.size());
1551 memcpy(sarr.ptrw(), cs.ptr(), sarr.size());
1552
1553 err = save_proxy.save_file(p_preset, p_udata, path + ".import", sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1554
1555 if (err != OK) {
1556 return err;
1557 }
1558 }
1559
1560 } else {
1561 // Just store it as it comes.
1562
1563 // Customization only happens if plugins did not take care of it before.
1564 bool force_binary = convert_text_to_binary && (path.has_extension("tres") || path.has_extension("tscn"));
1565 String export_path = _export_customize(path, customize_resources_plugins, customize_scenes_plugins, export_cache, export_base_path, force_binary);
1566
1567 if (export_path != path) {
1568 // Add a remap entry.
1569 path_remaps.push_back(path);
1570 path_remaps.push_back(export_path);
1571 }
1572
1573 Vector<uint8_t> array = FileAccess::get_file_as_bytes(export_path);
1574 err = save_proxy.save_file(p_preset, p_udata, export_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1575 if (err != OK) {
1576 return err;
1577 }
1578 }
1579 }
1580
1581 if (convert_text_to_binary || !customize_resources_plugins.is_empty() || !customize_scenes_plugins.is_empty()) {
1582 // End scene customization
1583
1584 String fcache = export_base_path.path_join("file_cache");
1585 Ref<FileAccess> f = FileAccess::open(fcache, FileAccess::WRITE);
1586
1587 if (f.is_valid()) {
1588 for (const KeyValue<String, FileExportCache> &E : export_cache) {
1589 if (E.value.used) { // May be old, unused
1590 String l = E.key + "::" + E.value.source_md5 + "::" + itos(E.value.source_modified_time) + "::" + E.value.saved_path;
1591 f->store_line(l);
1592 }
1593 }
1594 } else {
1595 ERR_PRINT("Error opening export file cache: " + fcache);
1596 }
1597
1598 for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
1599 plugin->_end_customize_resources();
1600 }
1601
1602 for (Ref<EditorExportPlugin> &plugin : customize_scenes_plugins) {
1603 plugin->_end_customize_scenes();
1604 }
1605 }
1606
1607 // Add any files that might've been defined during the final steps of the export plugins.
1608 err = add_shared_objects_and_extra_files_from_export_plugins();
1609 if (err != OK) {
1610 return err;
1611 }
1612
1613 //save config!
1614
1615 Vector<String> custom_list;
1616
1617 if (!p_preset->get_custom_features().is_empty()) {
1618 Vector<String> tmp_custom_list = p_preset->get_custom_features().split(",");
1619
1620 for (int i = 0; i < tmp_custom_list.size(); i++) {
1621 String f = tmp_custom_list[i].strip_edges();
1622 if (!f.is_empty()) {
1623 custom_list.push_back(f);
1624 }
1625 }
1626 }
1627 for (int i = 0; i < export_plugins.size(); i++) {
1628 custom_list.append_array(export_plugins[i]->_get_export_features(Ref<EditorExportPlatform>(this), p_debug));
1629 }
1630
1631 if (path_remaps.size()) {
1632 for (int i = 0; i < path_remaps.size(); i += 2) {
1633 const String &from = path_remaps[i];
1634 const String &to = path_remaps[i + 1];
1635 String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
1636 CharString utf8 = remap_file.utf8();
1637 Vector<uint8_t> new_file;
1638 new_file.resize(utf8.length());
1639 for (int j = 0; j < utf8.length(); j++) {
1640 new_file.write[j] = utf8[j];
1641 }
1642
1643 err = save_proxy.save_file(p_preset, p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1644 if (err != OK) {
1645 return err;
1646 }
1647 }
1648 }
1649
1650 Vector<String> forced_export = get_forced_export_files(p_preset);
1651 for (int i = 0; i < forced_export.size(); i++) {
1652 Vector<uint8_t> array;
1653 if (GDExtension::get_extension_list_config_file() == forced_export[i]) {
1654 array = _filter_extension_list_config_file(forced_export[i], paths);
1655 if (array.is_empty()) {
1656 continue;
1657 }
1658 } else {
1659 array = FileAccess::get_file_as_bytes(forced_export[i]);
1660 }
1661 err = save_proxy.save_file(p_preset, p_udata, forced_export[i], array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1662 if (err != OK) {
1663 return err;
1664 }
1665 }
1666
1667 Dictionary int_export = get_internal_export_files(p_preset, p_debug);
1668 for (const KeyValue<Variant, Variant> &int_export_kv : int_export) {
1669 const PackedByteArray &array = int_export_kv.value;
1670 err = save_proxy.save_file(p_preset, p_udata, int_export_kv.key, array, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1671 if (err != OK) {
1672 return err;
1673 }
1674 }
1675
1676 String config_file = "project.binary";
1677 String engine_cfb = EditorPaths::get_singleton()->get_temp_dir().path_join("tmp" + config_file);
1678 ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
1679 ProjectSettings::get_singleton()->save_custom(engine_cfb, custom_map, custom_list);
1680 Vector<uint8_t> data = FileAccess::get_file_as_bytes(engine_cfb);
1681 DirAccess::remove_file_or_error(engine_cfb);
1682
1683 err = save_proxy.save_file(p_preset, p_udata, "res://" + config_file, data, idx, total, enc_in_filters, enc_ex_filters, key, seed, false);
1684 if (err != OK) {
1685 return err;
1686 }
1687
1688 if (p_remove_func) {
1689 HashSet<String> currently_loaded_paths = PackedData::get_singleton()->get_file_paths();
1690 for (const String &path : currently_loaded_paths) {
1691 if (!save_proxy.has_saved(path)) {
1692 err = p_remove_func(p_preset, p_udata, path);
1693 if (err != OK) {
1694 return err;
1695 }
1696 }
1697 }
1698 }
1699
1700 return OK;
1701 }
1702
1703 Vector<uint8_t> EditorExportPlatform::_filter_extension_list_config_file(const String &p_config_path, const HashSet<String> &p_paths) {
1704 Ref<FileAccess> f = FileAccess::open(p_config_path, FileAccess::READ);
1705 if (f.is_null()) {
1706 ERR_FAIL_V_MSG(Vector<uint8_t>(), "Can't open file from path '" + String(p_config_path) + "'.");
1707 }
1708 Vector<uint8_t> data;
1709 while (!f->eof_reached()) {
1710 String l = f->get_line().strip_edges();
1711 if (p_paths.has(l)) {
1712 data.append_array(l.to_utf8_buffer());
1713 data.append('\n');
1714 }
1715 }
1716 return data;
1717 }
1718
1719 Error EditorExportPlatform::_pack_add_shared_object(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const SharedObject &p_so) {
1720 PackData *pack_data = (PackData *)p_userdata;
1721 if (pack_data->so_files) {
1722 pack_data->so_files->push_back(p_so);
1723 }
1724
1725 return OK;
1726 }
1727
1728 Error EditorExportPlatform::_remove_pack_file(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const String &p_path) {
1729 PackData *pd = (PackData *)p_userdata;
1730
1731 SavedData sd;
1732 sd.path_utf8 = p_path.utf8();
1733 sd.ofs = pd->f->get_position();
1734 sd.size = 0;
1735 sd.removal = true;
1736
1737 // This padding will likely never be added, as we should already be aligned when removals are added.
1738 int pad = _get_pad(PCK_PADDING, pd->f->get_position());
1739 for (int i = 0; i < pad; i++) {
1740 pd->f->store_8(0);
1741 }
1742
1743 sd.md5.resize_initialized(16);
1744
1745 pd->file_ofs.push_back(sd);
1746
1747 return OK;
1748 }
1749
1750 Error EditorExportPlatform::_zip_add_shared_object(const Ref<EditorExportPreset> &p_preset, void *p_userdata, const SharedObject &p_so) {
1751 ZipData *zip_data = (ZipData *)p_userdata;
1752 if (zip_data->so_files) {
1753 zip_data->so_files->push_back(p_so);
1754 }
1755
1756 return OK;
1757 }
1758
1759 void EditorExportPlatform::zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name) {
1760 String dir = p_folder.is_empty() ? p_root_path : p_root_path.path_join(p_folder);
1761
1762 Ref<DirAccess> da = DirAccess::open(dir);
1763 ERR_FAIL_COND(da.is_null());
1764
1765 da->list_dir_begin();
1766 String f = da->get_next();
1767 while (!f.is_empty()) {
1768 if (f == "." || f == "..") {
1769 f = da->get_next();
1770 continue;
1771 }
1772 if (da->is_link(f)) {
1773 OS::DateTime dt = OS::get_singleton()->get_datetime();
1774
1775 zip_fileinfo zipfi;
1776 zipfi.tmz_date.tm_year = dt.year;
1777 zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/
1778 zipfi.tmz_date.tm_mday = dt.day;
1779 zipfi.tmz_date.tm_hour = dt.hour;
1780 zipfi.tmz_date.tm_min = dt.minute;
1781 zipfi.tmz_date.tm_sec = dt.second;
1782 zipfi.dosDate = 0;
1783 // 0120000: symbolic link type
1784 // 0000755: permissions rwxr-xr-x
1785 // 0000644: permissions rw-r--r--
1786 uint32_t _mode = 0120644;
1787 zipfi.external_fa = (_mode << 16L) | ((_mode & 0200) ? 0 : 1); // UUUUUUUUUUUUUUUU0000000000ADVSHR: Unix permissions (U) + DOS read-only flag (R).
1788 zipfi.internal_fa = 0;
1789
1790 zipOpenNewFileInZip4(p_zip,
1791 p_folder.path_join(f).utf8().get_data(),
1792 &zipfi,
1793 nullptr,
1794 0,
1795 nullptr,
1796 0,
1797 nullptr,
1798 Z_DEFLATED,
1799 Z_DEFAULT_COMPRESSION,
1800 0,
1801 -MAX_WBITS,
1802 DEF_MEM_LEVEL,
1803 Z_DEFAULT_STRATEGY,
1804 nullptr,
1805 0,
1806 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions
1807 1 << 11); // Bit 11 is the language encoding flag. When set, filename and comment fields must be encoded using UTF-8.
1808
1809 const CharString target_utf8 = da->read_link(f).utf8();
1810 zipWriteInFileInZip(p_zip, target_utf8.get_data(), target_utf8.size());
1811 zipCloseFileInZip(p_zip);
1812 } else if (da->current_is_dir()) {
1813 zip_folder_recursive(p_zip, p_root_path, p_folder.path_join(f), p_pkg_name);
1814 } else {
1815 bool _is_executable = is_executable(dir.path_join(f));
1816
1817 OS::DateTime dt = OS::get_singleton()->get_datetime();
1818
1819 zip_fileinfo zipfi;
1820 zipfi.tmz_date.tm_year = dt.year;
1821 zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/
1822 zipfi.tmz_date.tm_mday = dt.day;
1823 zipfi.tmz_date.tm_hour = dt.hour;
1824 zipfi.tmz_date.tm_min = dt.minute;
1825 zipfi.tmz_date.tm_sec = dt.second;
1826 zipfi.dosDate = 0;
1827 // 0100000: regular file type
1828 // 0000755: permissions rwxr-xr-x
1829 // 0000644: permissions rw-r--r--
1830 uint32_t _mode = (_is_executable ? 0100755 : 0100644);
1831 zipfi.external_fa = (_mode << 16L) | ((_mode & 0200) ? 0 : 1); // UUUUUUUUUUUUUUUU0000000000ADVSHR: Unix permissions (U) + DOS read-only flag (R).
1832 zipfi.internal_fa = 0;
1833
1834 zipOpenNewFileInZip4(p_zip,
1835 p_folder.path_join(f).utf8().get_data(),
1836 &zipfi,
1837 nullptr,
1838 0,
1839 nullptr,
1840 0,
1841 nullptr,
1842 Z_DEFLATED,
1843 Z_DEFAULT_COMPRESSION,
1844 0,
1845 -MAX_WBITS,
1846 DEF_MEM_LEVEL,
1847 Z_DEFAULT_STRATEGY,
1848 nullptr,
1849 0,
1850 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions
1851 1 << 11); // Bit 11 is the language encoding flag. When set, filename and comment fields must be encoded using UTF-8.
1852
1853 Ref<FileAccess> fa = FileAccess::open(dir.path_join(f), FileAccess::READ);
1854 if (fa.is_null()) {
1855 add_message(EXPORT_MESSAGE_ERROR, TTR("ZIP Creation"), vformat(TTR("Could not open file to read from path \"%s\"."), dir.path_join(f)));
1856 return;
1857 }
1858 const int bufsize = 16384;
1859 uint8_t buf[bufsize];
1860
1861 while (true) {
1862 uint64_t got = fa->get_buffer(buf, bufsize);
1863 if (got == 0) {
1864 break;
1865 }
1866 zipWriteInFileInZip(p_zip, buf, got);
1867 }
1868
1869 zipCloseFileInZip(p_zip);
1870 }
1871 f = da->get_next();
1872 }
1873 da->list_dir_end();
1874 }
1875
1876 Dictionary EditorExportPlatform::_save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, bool p_embed) {
1877 Vector<SharedObject> so_files;
1878 int64_t embedded_start = 0;
1879 int64_t embedded_size = 0;
1880 Error err_code = save_pack(p_preset, p_debug, p_path, &so_files, nullptr, nullptr, p_embed, &embedded_start, &embedded_size);
1881
1882 Dictionary ret;
1883 ret["result"] = err_code;
1884 if (err_code == OK) {
1885 Array arr;
1886 for (const SharedObject &E : so_files) {
1887 Dictionary so;
1888 so["path"] = E.path;
1889 so["tags"] = E.tags;
1890 so["target_folder"] = E.target;
1891 arr.push_back(so);
1892 }
1893 ret["so_files"] = arr;
1894 if (p_embed) {
1895 ret["embedded_start"] = embedded_start;
1896 ret["embedded_size"] = embedded_size;
1897 }
1898 }
1899
1900 return ret;
1901 }
1902
1903 Dictionary EditorExportPlatform::_save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
1904 Vector<SharedObject> so_files;
1905 Error err_code = save_zip(p_preset, p_debug, p_path, &so_files);
1906
1907 Dictionary ret;
1908 ret["result"] = err_code;
1909 if (err_code == OK) {
1910 Array arr;
1911 for (const SharedObject &E : so_files) {
1912 Dictionary so;
1913 so["path"] = E.path;
1914 so["tags"] = E.tags;
1915 so["target_folder"] = E.target;
1916 arr.push_back(so);
1917 }
1918 ret["so_files"] = arr;
1919 }
1920
1921 return ret;
1922 }
1923
1924 Dictionary EditorExportPlatform::_save_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
1925 Vector<SharedObject> so_files;
1926 Error err_code = save_pack_patch(p_preset, p_debug, p_path, &so_files);
1927
1928 Dictionary ret;
1929 ret["result"] = err_code;
1930 if (err_code == OK) {
1931 Array arr;
1932 for (const SharedObject &E : so_files) {
1933 Dictionary so;
1934 so["path"] = E.path;
1935 so["tags"] = E.tags;
1936 so["target_folder"] = E.target;
1937 arr.push_back(so);
1938 }
1939 ret["so_files"] = arr;
1940 }
1941
1942 return ret;
1943 }
1944
1945 Dictionary EditorExportPlatform::_save_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
1946 Vector<SharedObject> so_files;
1947 Error err_code = save_zip_patch(p_preset, p_debug, p_path, &so_files);
1948
1949 Dictionary ret;
1950 ret["result"] = err_code;
1951 if (err_code == OK) {
1952 Array arr;
1953 for (const SharedObject &E : so_files) {
1954 Dictionary so;
1955 so["path"] = E.path;
1956 so["tags"] = E.tags;
1957 so["target_folder"] = E.target;
1958 arr.push_back(so);
1959 }
1960 ret["so_files"] = arr;
1961 }
1962
1963 return ret;
1964 }
1965
1966 bool EditorExportPlatform::_store_header(Ref<FileAccess> p_fd, bool p_enc, bool p_sparse, uint64_t &r_file_base_ofs, uint64_t &r_dir_base_ofs) {
1967 p_fd->store_32(PACK_HEADER_MAGIC);
1968 p_fd->store_32(PACK_FORMAT_VERSION);
1969 p_fd->store_32(GODOT_VERSION_MAJOR);
1970 p_fd->store_32(GODOT_VERSION_MINOR);
1971 p_fd->store_32(GODOT_VERSION_PATCH);
1972
1973 uint32_t pack_flags = PACK_REL_FILEBASE;
1974 if (p_enc) {
1975 pack_flags |= PACK_DIR_ENCRYPTED;
1976 }
1977 if (p_sparse) {
1978 pack_flags |= PACK_SPARSE_BUNDLE;
1979 }
1980 p_fd->store_32(pack_flags); // Flags.
1981
1982 r_file_base_ofs = p_fd->get_position();
1983 p_fd->store_64(0); // Files base offset.
1984
1985 r_dir_base_ofs = p_fd->get_position();
1986 p_fd->store_64(0); // Directory offset.
1987
1988 for (int i = 0; i < 16; i++) {
1989 //reserved
1990 p_fd->store_32(0);
1991 }
1992 return true;
1993 }
1994
1995 bool EditorExportPlatform::_encrypt_and_store_directory(Ref<FileAccess> p_fd, PackData &p_pack_data, const Vector<uint8_t> &p_key, uint64_t p_seed, uint64_t p_file_base) {
1996 Ref<FileAccessEncrypted> fae;
1997 Ref<FileAccess> fhead = p_fd;
1998
1999 fhead->store_32(p_pack_data.file_ofs.size()); //amount of files
2000
2001 if (!p_key.is_empty()) {
2002 uint64_t seed = p_seed;
2003 fae.instantiate();
2004 if (fae.is_null()) {
2005 return false;
2006 }
2007
2008 Vector<uint8_t> iv;
2009 if (seed != 0) {
2010 for (int i = 0; i < p_pack_data.file_ofs.size(); i++) {
2011 for (int64_t j = 0; j < p_pack_data.file_ofs[i].path_utf8.length(); j++) {
2012 seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].path_utf8.get_data()[j];
2013 }
2014 for (int64_t j = 0; j < p_pack_data.file_ofs[i].md5.size(); j++) {
2015 seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].md5[j];
2016 }
2017 seed = ((seed << 5) + seed) ^ (p_pack_data.file_ofs[i].ofs - p_file_base);
2018 seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].size;
2019 }
2020
2021 RandomPCG rng = RandomPCG(seed);
2022 iv.resize(16);
2023 for (int i = 0; i < 16; i++) {
2024 iv.write[i] = rng.rand() % 256;
2025 }
2026 }
2027
2028 Error err = fae->open_and_parse(fhead, p_key, FileAccessEncrypted::MODE_WRITE_AES256, false, iv);
2029 if (err != OK) {
2030 return false;
2031 }
2032
2033 fhead = fae;
2034 }
2035 for (int i = 0; i < p_pack_data.file_ofs.size(); i++) {
2036 uint32_t string_len = p_pack_data.file_ofs[i].path_utf8.length();
2037 uint32_t pad = _get_pad(4, string_len);
2038
2039 fhead->store_32(string_len + pad);
2040 fhead->store_buffer((const uint8_t *)p_pack_data.file_ofs[i].path_utf8.get_data(), string_len);
2041 for (uint32_t j = 0; j < pad; j++) {
2042 fhead->store_8(0);
2043 }
2044
2045 fhead->store_64(p_pack_data.file_ofs[i].ofs - p_file_base);
2046 fhead->store_64(p_pack_data.file_ofs[i].size); // pay attention here, this is where file is
2047 fhead->store_buffer(p_pack_data.file_ofs[i].md5.ptr(), 16); //also save md5 for file
2048 uint32_t flags = 0;
2049 if (p_pack_data.file_ofs[i].encrypted) {
2050 flags |= PACK_FILE_ENCRYPTED;
2051 }
2052 if (p_pack_data.file_ofs[i].removal) {
2053 flags |= PACK_FILE_REMOVAL;
2054 }
2055 if (p_pack_data.file_ofs[i].delta) {
2056 flags |= PACK_FILE_DELTA;
2057 }
2058 fhead->store_32(flags);
2059 }
2060
2061 if (fae.is_valid()) {
2062 fhead.unref();
2063 fae.unref();
2064 }
2065 return true;
2066 }
2067
2068 Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, EditorExportSaveFunction p_save_func, EditorExportRemoveFunction p_remove_func, bool p_embed, int64_t *r_embedded_start, int64_t *r_embedded_size) {
2069 EditorProgress ep("savepack", TTR("Packing"), 102, true);
2070
2071 if (p_save_func == nullptr) {
2072 p_save_func = _save_pack_file;
2073 }
2074
2075 // Create the temporary export directory if it doesn't exist.
2076 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
2077 da->make_dir_recursive(EditorPaths::get_singleton()->get_temp_dir());
2078
2079 Ref<FileAccess> f;
2080 int64_t embed_pos = 0;
2081 if (!p_embed) {
2082 // Regular output to separate PCK file.
2083 f = FileAccess::open(p_path, FileAccess::WRITE);
2084 if (f.is_null()) {
2085 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), vformat(TTR("Can't open file for writing at path \"%s\"."), p_path));
2086 return ERR_CANT_CREATE;
2087 }
2088 } else {
2089 // Append to executable.
2090 f = FileAccess::open(p_path, FileAccess::READ_WRITE);
2091 if (f.is_null()) {
2092 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), vformat(TTR("Can't open file for reading-writing at path \"%s\"."), p_path));
2093 return ERR_FILE_CANT_OPEN;
2094 }
2095
2096 f->seek_end();
2097 embed_pos = f->get_position();
2098
2099 if (r_embedded_start) {
2100 *r_embedded_start = embed_pos;
2101 }
2102
2103 // Ensure embedded PCK starts at a 64-bit multiple
2104 int pad = f->get_position() % 8;
2105 for (int i = 0; i < pad; i++) {
2106 f->store_8(0);
2107 }
2108 }
2109
2110 int64_t pck_start_pos = f->get_position();
2111 uint64_t file_base_ofs = 0;
2112 uint64_t dir_base_ofs = 0;
2113
2114 _store_header(f, p_preset->get_enc_pck() && p_preset->get_enc_directory(), false, file_base_ofs, dir_base_ofs);
2115
2116 // Align for first file.
2117 int file_padding = _get_pad(PCK_PADDING, f->get_position());
2118 for (int i = 0; i < file_padding; i++) {
2119 f->store_8(0);
2120 }
2121
2122 uint64_t file_base = f->get_position();
2123 f->seek(file_base_ofs);
2124 f->store_64(file_base - pck_start_pos); // Update files base.
2125 f->seek(file_base);
2126
2127 // Write files.
2128 PackData pd;
2129 pd.ep = &ep;
2130 pd.f = f;
2131 pd.so_files = p_so_files;
2132 pd.path = p_path;
2133
2134 Error err = export_project_files(p_preset, p_debug, p_save_func, p_remove_func, &pd, _pack_add_shared_object);
2135
2136 if (err != OK) {
2137 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Failed to export project files."));
2138 return err;
2139 }
2140
2141 if (pd.file_ofs.is_empty()) {
2142 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("No files or changes to export."));
2143 return FAILED;
2144 }
2145
2146 pd.file_ofs.sort(); // Do sort, so we can do binary search later (where ?).
2147
2148 int dir_padding = _get_pad(PCK_PADDING, f->get_position());
2149 for (int i = 0; i < dir_padding; i++) {
2150 f->store_8(0);
2151 }
2152
2153 // Write directory.
2154 uint64_t dir_offset = f->get_position();
2155 f->seek(dir_base_ofs);
2156 f->store_64(dir_offset - pck_start_pos);
2157 f->seek(dir_offset);
2158
2159 Vector<uint8_t> key;
2160 if (p_preset->get_enc_pck() && p_preset->get_enc_directory()) {
2161 String script_key = _get_script_encryption_key(p_preset);
2162 key.resize(32);
2163 if (script_key.length() == 64) {
2164 for (int i = 0; i < 32; i++) {
2165 int v = 0;
2166 if (i * 2 < script_key.length()) {
2167 char32_t ct = script_key[i * 2];
2168 if (is_digit(ct)) {
2169 ct = ct - '0';
2170 } else if (ct >= 'a' && ct <= 'f') {
2171 ct = 10 + ct - 'a';
2172 }
2173 v |= ct << 4;
2174 }
2175
2176 if (i * 2 + 1 < script_key.length()) {
2177 char32_t ct = script_key[i * 2 + 1];
2178 if (is_digit(ct)) {
2179 ct = ct - '0';
2180 } else if (ct >= 'a' && ct <= 'f') {
2181 ct = 10 + ct - 'a';
2182 }
2183 v |= ct;
2184 }
2185 key.write[i] = v;
2186 }
2187 }
2188 }
2189
2190 if (!_encrypt_and_store_directory(f, pd, key, p_preset->get_seed(), file_base)) {
2191 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Can't create encrypted file."));
2192 return ERR_CANT_CREATE;
2193 }
2194
2195 if (p_embed) {
2196 // Ensure embedded data ends at a 64-bit multiple.
2197 uint64_t embed_end = f->get_position() - embed_pos + 12;
2198 uint64_t pad = embed_end % 8;
2199 for (uint64_t i = 0; i < pad; i++) {
2200 f->store_8(0);
2201 }
2202
2203 uint64_t pck_size = f->get_position() - pck_start_pos;
2204 f->store_64(pck_size);
2205 f->store_32(PACK_HEADER_MAGIC);
2206
2207 if (r_embedded_size) {
2208 *r_embedded_size = f->get_position() - embed_pos;
2209 }
2210 }
2211 f->close();
2212
2213 return OK;
2214 }
2215
2216 Error EditorExportPlatform::save_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, bool p_embed, int64_t *r_embedded_start, int64_t *r_embedded_size) {
2217 return save_pack(p_preset, p_debug, p_path, p_so_files, _save_pack_patch_file, _remove_pack_file, p_embed, r_embedded_start, r_embedded_size);
2218 }
2219
2220 Error EditorExportPlatform::save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, EditorExportSaveFunction p_save_func) {
2221 EditorProgress ep("savezip", TTR("Packing"), 102, true);
2222
2223 if (p_save_func == nullptr) {
2224 p_save_func = _save_zip_file;
2225 }
2226
2227 String tmppath = EditorPaths::get_singleton()->get_temp_dir().path_join("packtmp");
2228
2229 Ref<FileAccess> io_fa;
2230 zlib_filefunc_def io = zipio_create_io(&io_fa);
2231 zipFile zip = zipOpen2(tmppath.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io);
2232
2233 ZipData zd;
2234 zd.ep = &ep;
2235 zd.zip = zip;
2236 zd.so_files = p_so_files;
2237
2238 Error err = export_project_files(p_preset, p_debug, p_save_func, nullptr, &zd, _zip_add_shared_object);
2239 if (err != OK && err != ERR_SKIP) {
2240 add_message(EXPORT_MESSAGE_ERROR, TTR("Save ZIP"), TTR("Failed to export project files."));
2241 }
2242
2243 zipClose(zip, nullptr);
2244
2245 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
2246
2247 if (zd.file_count == 0) {
2248 da->remove(tmppath);
2249 add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("No files or changes to export."));
2250 return FAILED;
2251 }
2252
2253 err = da->rename(tmppath, p_path);
2254 if (err != OK) {
2255 da->remove(tmppath);
2256 add_message(EXPORT_MESSAGE_ERROR, TTR("Save ZIP"), vformat(TTR("Failed to move temporary file \"%s\" to \"%s\"."), tmppath, p_path));
2257 }
2258
2259 return OK;
2260 }
2261
2262 Error EditorExportPlatform::save_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files) {
2263 return save_zip(p_preset, p_debug, p_path, p_so_files, _save_zip_patch_file);
2264 }
2265
2266 Error EditorExportPlatform::export_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
2267 ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
2268 return save_pack(p_preset, p_debug, p_path);
2269 }
2270
2271 Error EditorExportPlatform::export_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
2272 ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
2273 return save_zip(p_preset, p_debug, p_path);
2274 }
2275
2276 Error EditorExportPlatform::export_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, const Vector<String> &p_patches, BitField<EditorExportPlatform::DebugFlags> p_flags) {
2277 ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
2278 Error err = _load_patches(p_patches.is_empty() ? p_preset->get_patches() : p_patches);
2279 if (err != OK) {
2280 return err;
2281 }
2282 err = save_pack_patch(p_preset, p_debug, p_path);
2283 _unload_patches();
2284 return err;
2285 }
2286
2287 Error EditorExportPlatform::export_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, const Vector<String> &p_patches, BitField<EditorExportPlatform::DebugFlags> p_flags) {
2288 ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
2289 Error err = _load_patches(p_patches.is_empty() ? p_preset->get_patches() : p_patches);
2290 if (err != OK) {
2291 return err;
2292 }
2293 err = save_zip_patch(p_preset, p_debug, p_path);
2294 _unload_patches();
2295 return err;
2296 }
2297
2298 Vector<String> EditorExportPlatform::gen_export_flags(BitField<EditorExportPlatform::DebugFlags> p_flags) {
2299 Vector<String> ret;
2300 String host = EDITOR_GET("network/debug/remote_host");
2301 int remote_port = (int)EDITOR_GET("network/debug/remote_port");
2302
2303 if (get_name() == "Android" && EditorSettings::get_singleton()->has_setting("export/android/use_wifi_for_remote_debug") && EDITOR_GET("export/android/use_wifi_for_remote_debug")) {
2304 host = EDITOR_GET("export/android/wifi_remote_debug_host");
2305 } else if (p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST)) {
2306 host = "localhost";
2307 }
2308
2309 if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {
2310 int port = EDITOR_GET("filesystem/file_server/port");
2311 String passwd = EDITOR_GET("filesystem/file_server/password");
2312 ret.push_back("--remote-fs");
2313 ret.push_back(host + ":" + itos(port));
2314 if (!passwd.is_empty()) {
2315 ret.push_back("--remote-fs-password");
2316 ret.push_back(passwd);
2317 }
2318 }
2319
2320 if (p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG)) {
2321 ret.push_back("--remote-debug");
2322
2323 ret.push_back(get_debug_protocol() + host + ":" + String::num_int64(remote_port));
2324
2325 List<String> breakpoints;
2326 ScriptEditor::get_singleton()->get_breakpoints(&breakpoints);
2327
2328 if (breakpoints.size()) {
2329 ret.push_back("--breakpoints");
2330 String bpoints;
2331 for (List<String>::Element *E = breakpoints.front(); E; E = E->next()) {
2332 bpoints += E->get().replace(" ", "%20");
2333 if (E->next()) {
2334 bpoints += ",";
2335 }
2336 }
2337
2338 ret.push_back(bpoints);
2339 }
2340 }
2341
2342 if (p_flags.has_flag(DEBUG_FLAG_VIEW_COLLISIONS)) {
2343 ret.push_back("--debug-collisions");
2344 }
2345
2346 if (p_flags.has_flag(DEBUG_FLAG_VIEW_NAVIGATION)) {
2347 ret.push_back("--debug-navigation");
2348 }
2349 return ret;
2350 }
2351
2352 bool EditorExportPlatform::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates, bool p_debug) const {
2353 bool valid = true;
2354
2355 String templates_error;
2356 valid = valid && has_valid_export_configuration(p_preset, templates_error, r_missing_templates, p_debug);
2357
2358 if (!templates_error.is_empty()) {
2359 r_error += templates_error;
2360 }
2361
2362 String export_plugins_warning;
2363 Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
2364 for (int i = 0; i < export_plugins.size(); i++) {
2365 Ref<EditorExportPlatform> export_platform = Ref<EditorExportPlatform>(this);
2366 if (!export_plugins[i]->supports_platform(export_platform)) {
2367 continue;
2368 }
2369
2370 String plugin_warning = export_plugins.write[i]->_has_valid_export_configuration(export_platform, p_preset);
2371 if (!plugin_warning.is_empty()) {
2372 export_plugins_warning += plugin_warning;
2373 }
2374 }
2375
2376 if (!export_plugins_warning.is_empty()) {
2377 r_error += export_plugins_warning;
2378 }
2379
2380 String project_configuration_error;
2381 valid = valid && has_valid_project_configuration(p_preset, project_configuration_error);
2382
2383 if (!project_configuration_error.is_empty()) {
2384 r_error += project_configuration_error;
2385 }
2386
2387 return valid;
2388 }
2389
2390 Error EditorExportPlatform::ssh_run_on_remote(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, String *r_out, int p_port_fwd) const {
2391 String ssh_path = EDITOR_GET("export/ssh/ssh");
2392 if (ssh_path.is_empty()) {
2393 ssh_path = "ssh";
2394 }
2395
2396 List<String> args;
2397 args.push_back("-p");
2398 args.push_back(p_port);
2399 args.push_back("-q");
2400 args.push_back("-o");
2401 args.push_back("LogLevel=error");
2402 args.push_back("-o");
2403 args.push_back("BatchMode=yes");
2404 args.push_back("-o");
2405 args.push_back("StrictHostKeyChecking=no");
2406 for (const String &E : p_ssh_args) {
2407 args.push_back(E);
2408 }
2409 if (p_port_fwd > 0) {
2410 args.push_back("-R");
2411 args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd));
2412 }
2413 args.push_back(p_host);
2414 args.push_back(p_cmd_args);
2415
2416 String out;
2417 int exit_code = -1;
2418
2419 if (OS::get_singleton()->is_stdout_verbose()) {
2420 OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data());
2421 for (const String &arg : args) {
2422 OS::get_singleton()->print(" %s", arg.utf8().get_data());
2423 }
2424 OS::get_singleton()->print("\n");
2425 }
2426
2427 Error err = OS::get_singleton()->execute(ssh_path, args, &out, &exit_code, true);
2428 if (out.is_empty()) {
2429 print_verbose(vformat("Exit code: %d", exit_code));
2430 } else {
2431 print_verbose(vformat("Exit code: %d, Output: %s", exit_code, out.replace("\r\n", "\n")));
2432 }
2433 if (r_out) {
2434 *r_out = out.replace("\r\n", "\n").get_slicec('\n', 0);
2435 }
2436 if (err != OK) {
2437 return err;
2438 } else if (exit_code != 0) {
2439 if (!out.is_empty()) {
2440 print_line(out);
2441 }
2442 return FAILED;
2443 }
2444 return OK;
2445 }
2446
2447 Error EditorExportPlatform::ssh_run_on_remote_no_wait(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, OS::ProcessID *r_pid, int p_port_fwd) const {
2448 String ssh_path = EDITOR_GET("export/ssh/ssh");
2449 if (ssh_path.is_empty()) {
2450 ssh_path = "ssh";
2451 }
2452
2453 List<String> args;
2454 args.push_back("-p");
2455 args.push_back(p_port);
2456 args.push_back("-q");
2457 args.push_back("-o");
2458 args.push_back("LogLevel=error");
2459 args.push_back("-o");
2460 args.push_back("BatchMode=yes");
2461 args.push_back("-o");
2462 args.push_back("StrictHostKeyChecking=no");
2463 for (const String &E : p_ssh_args) {
2464 args.push_back(E);
2465 }
2466 if (p_port_fwd > 0) {
2467 args.push_back("-R");
2468 args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd));
2469 }
2470 args.push_back(p_host);
2471 args.push_back(p_cmd_args);
2472
2473 if (OS::get_singleton()->is_stdout_verbose()) {
2474 OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data());
2475 for (const String &arg : args) {
2476 OS::get_singleton()->print(" %s", arg.utf8().get_data());
2477 }
2478 OS::get_singleton()->print("\n");
2479 }
2480
2481 return OS::get_singleton()->create_process(ssh_path, args, r_pid);
2482 }
2483
2484 Error EditorExportPlatform::ssh_push_to_remote(const String &p_host, const String &p_port, const Vector<String> &p_scp_args, const String &p_src_file, const String &p_dst_file) const {
2485 String scp_path = EDITOR_GET("export/ssh/scp");
2486 if (scp_path.is_empty()) {
2487 scp_path = "scp";
2488 }
2489
2490 List<String> args;
2491 args.push_back("-P");
2492 args.push_back(p_port);
2493 args.push_back("-q");
2494 args.push_back("-o");
2495 args.push_back("LogLevel=error");
2496 args.push_back("-o");
2497 args.push_back("BatchMode=yes");
2498 args.push_back("-o");
2499 args.push_back("StrictHostKeyChecking=no");
2500 for (const String &E : p_scp_args) {
2501 args.push_back(E);
2502 }
2503 args.push_back(p_src_file);
2504 args.push_back(vformat("%s:%s", p_host, p_dst_file));
2505
2506 String out;
2507 int exit_code = -1;
2508
2509 if (OS::get_singleton()->is_stdout_verbose()) {
2510 OS::get_singleton()->print("Executing: %s", scp_path.utf8().get_data());
2511 for (const String &arg : args) {
2512 OS::get_singleton()->print(" %s", arg.utf8().get_data());
2513 }
2514 OS::get_singleton()->print("\n");
2515 }
2516
2517 Error err = OS::get_singleton()->execute(scp_path, args, &out, &exit_code, true);
2518 if (err != OK) {
2519 return err;
2520 } else if (exit_code != 0) {
2521 if (!out.is_empty()) {
2522 print_line(out);
2523 }
2524 return FAILED;
2525 }
2526 return OK;
2527 }
2528
2529 Array EditorExportPlatform::get_current_presets() const {
2530 Array ret;
2531 for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
2532 Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
2533 if (ep->get_platform() == this) {
2534 ret.push_back(ep);
2535 }
2536 }
2537 return ret;
2538 }
2539
2540 String EditorExportPlatform::simplify_path(const String &p_path) {
2541 if (p_path.begins_with("uid://")) {
2542 const String path = ResourceUID::uid_to_path(p_path);
2543 print_verbose(vformat(R"(UID-referenced exported file name "%s" was replaced with "%s".)", p_path, path));
2544 return path.simplify_path();
2545 } else {
2546 return p_path.simplify_path();
2547 }
2548 }
2549
2550 Variant EditorExportPlatform::get_project_setting(const Ref<EditorExportPreset> &p_preset, const StringName &p_name) {
2551 if (p_preset.is_valid()) {
2552 return p_preset->get_project_setting(p_name);
2553 } else {
2554 return GLOBAL_GET(p_name);
2555 }
2556 }
2557
2558 void EditorExportPlatform::_bind_methods() {
2559 ClassDB::bind_method(D_METHOD("get_os_name"), &EditorExportPlatform::get_os_name);
2560
2561 ClassDB::bind_method(D_METHOD("create_preset"), &EditorExportPlatform::create_preset);
2562
2563 ClassDB::bind_method(D_METHOD("find_export_template", "template_file_name"), &EditorExportPlatform::_find_export_template);
2564 ClassDB::bind_method(D_METHOD("get_current_presets"), &EditorExportPlatform::get_current_presets);
2565
2566 ClassDB::bind_method(D_METHOD("save_pack", "preset", "debug", "path", "embed"), &EditorExportPlatform::_save_pack, DEFVAL(false));
2567 ClassDB::bind_method(D_METHOD("save_zip", "preset", "debug", "path"), &EditorExportPlatform::_save_zip);
2568 ClassDB::bind_method(D_METHOD("save_pack_patch", "preset", "debug", "path"), &EditorExportPlatform::_save_pack_patch);
2569 ClassDB::bind_method(D_METHOD("save_zip_patch", "preset", "debug", "path"), &EditorExportPlatform::_save_zip_patch);
2570
2571 ClassDB::bind_method(D_METHOD("gen_export_flags", "flags"), &EditorExportPlatform::gen_export_flags);
2572
2573 ClassDB::bind_method(D_METHOD("export_project_files", "preset", "debug", "save_cb", "shared_cb"), &EditorExportPlatform::_export_project_files, DEFVAL(Callable()));
2574
2575 ClassDB::bind_method(D_METHOD("export_project", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_project, DEFVAL(0));
2576 ClassDB::bind_method(D_METHOD("export_pack", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_pack, DEFVAL(0));
2577 ClassDB::bind_method(D_METHOD("export_zip", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_zip, DEFVAL(0));
2578 ClassDB::bind_method(D_METHOD("export_pack_patch", "preset", "debug", "path", "patches", "flags"), &EditorExportPlatform::export_pack_patch, DEFVAL(PackedStringArray()), DEFVAL(0));
2579 ClassDB::bind_method(D_METHOD("export_zip_patch", "preset", "debug", "path", "patches", "flags"), &EditorExportPlatform::export_zip_patch, DEFVAL(PackedStringArray()), DEFVAL(0));
2580
2581 ClassDB::bind_method(D_METHOD("clear_messages"), &EditorExportPlatform::clear_messages);
2582 ClassDB::bind_method(D_METHOD("add_message", "type", "category", "message"), &EditorExportPlatform::add_message);
2583 ClassDB::bind_method(D_METHOD("get_message_count"), &EditorExportPlatform::get_message_count);
2584
2585 ClassDB::bind_method(D_METHOD("get_message_type", "index"), &EditorExportPlatform::_get_message_type);
2586 ClassDB::bind_method(D_METHOD("get_message_category", "index"), &EditorExportPlatform::_get_message_category);
2587 ClassDB::bind_method(D_METHOD("get_message_text", "index"), &EditorExportPlatform::_get_message_text);
2588 ClassDB::bind_method(D_METHOD("get_worst_message_type"), &EditorExportPlatform::get_worst_message_type);
2589
2590 ClassDB::bind_method(D_METHOD("ssh_run_on_remote", "host", "port", "ssh_arg", "cmd_args", "output", "port_fwd"), &EditorExportPlatform::_ssh_run_on_remote, DEFVAL(Array()), DEFVAL(-1));
2591 ClassDB::bind_method(D_METHOD("ssh_run_on_remote_no_wait", "host", "port", "ssh_args", "cmd_args", "port_fwd"), &EditorExportPlatform::_ssh_run_on_remote_no_wait, DEFVAL(-1));
2592 ClassDB::bind_method(D_METHOD("ssh_push_to_remote", "host", "port", "scp_args", "src_file", "dst_file"), &EditorExportPlatform::ssh_push_to_remote);
2593
2594 ClassDB::bind_method(D_METHOD("get_internal_export_files", "preset", "debug"), &EditorExportPlatform::get_internal_export_files);
2595
2596 ClassDB::bind_static_method("EditorExportPlatform", D_METHOD("get_forced_export_files", "preset"), &EditorExportPlatform::get_forced_export_files, DEFVAL(Ref<EditorExportPreset>()));
2597
2598 BIND_ENUM_CONSTANT(EXPORT_MESSAGE_NONE);
2599 BIND_ENUM_CONSTANT(EXPORT_MESSAGE_INFO);
2600 BIND_ENUM_CONSTANT(EXPORT_MESSAGE_WARNING);
2601 BIND_ENUM_CONSTANT(EXPORT_MESSAGE_ERROR);
2602
2603 BIND_BITFIELD_FLAG(DEBUG_FLAG_DUMB_CLIENT);
2604 BIND_BITFIELD_FLAG(DEBUG_FLAG_REMOTE_DEBUG);
2605 BIND_BITFIELD_FLAG(DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST);
2606 BIND_BITFIELD_FLAG(DEBUG_FLAG_VIEW_COLLISIONS);
2607 BIND_BITFIELD_FLAG(DEBUG_FLAG_VIEW_NAVIGATION);
2608 }