Debian Codegraph @

editor/file_system/editor_file_system.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* editor_file_system.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_file_system.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/extension/gdextension_manager.h"
35 #include "core/io/dir_access.h"
36 #include "core/io/file_access.h"
37 #include "core/io/resource_saver.h"
38 #include "core/object/worker_thread_pool.h"
39 #include "core/os/os.h"
40 #include "core/variant/variant_parser.h"
41 #include "editor/doc/editor_help.h"
42 #include "editor/editor_node.h"
43 #include "editor/file_system/editor_paths.h"
44 #include "editor/inspector/editor_resource_preview.h"
45 #include "editor/script/script_editor_plugin.h"
46 #include "editor/settings/editor_settings.h"
47 #include "editor/settings/project_settings_editor.h"
48 #include "scene/resources/packed_scene.h"
49
50 EditorFileSystem *EditorFileSystem::singleton = nullptr;
51 int EditorFileSystem::nb_files_total = 0;
52 EditorFileSystem::ScannedDirectory *EditorFileSystem::first_scan_root_dir = nullptr;
53
54 //the name is the version, to keep compatibility with different versions of Godot
55 #define CACHE_FILE_NAME "filesystem_cache10"
56
57 int EditorFileSystemDirectory::find_file_index(const String &p_file) const {
58 for (int i = 0; i < files.size(); i++) {
59 if (files[i]->file == p_file) {
60 return i;
61 }
62 }
63 return -1;
64 }
65
66 int EditorFileSystemDirectory::find_dir_index(const String &p_dir) const {
67 for (int i = 0; i < subdirs.size(); i++) {
68 if (subdirs[i]->name == p_dir) {
69 return i;
70 }
71 }
72
73 return -1;
74 }
75
76 void EditorFileSystemDirectory::force_update() {
77 // We set modified_time to 0 to force `EditorFileSystem::_scan_fs_changes` to search changes in the directory
78 modified_time = 0;
79 }
80
81 int EditorFileSystemDirectory::get_subdir_count() const {
82 return subdirs.size();
83 }
84
85 EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) {
86 ERR_FAIL_INDEX_V(p_idx, subdirs.size(), nullptr);
87 return subdirs[p_idx];
88 }
89
90 int EditorFileSystemDirectory::get_file_count() const {
91 return files.size();
92 }
93
94 String EditorFileSystemDirectory::get_file(int p_idx) const {
95 ERR_FAIL_INDEX_V(p_idx, files.size(), "");
96
97 return files[p_idx]->file;
98 }
99
100 String EditorFileSystemDirectory::get_path() const {
101 int parents = 0;
102 const EditorFileSystemDirectory *efd = this;
103 // Determine the level of nesting.
104 while (efd->parent) {
105 parents++;
106 efd = efd->parent;
107 }
108
109 if (parents == 0) {
110 return "res://";
111 }
112
113 // Using PackedStringArray, because the path is built in reverse order.
114 PackedStringArray path_bits;
115 // Allocate an array based on nesting. It will store path bits.
116 path_bits.resize(parents + 2); // Last String is empty, so paths end with /.
117 String *path_write = path_bits.ptrw();
118 path_write[0] = "res:/";
119
120 efd = this;
121 for (int i = parents; i > 0; i--) {
122 path_write[i] = efd->name;
123 efd = efd->parent;
124 }
125 return String("/").join(path_bits);
126 }
127
128 String EditorFileSystemDirectory::get_file_path(int p_idx) const {
129 return get_path().path_join(get_file(p_idx));
130 }
131
132 Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const {
133 ERR_FAIL_INDEX_V(p_idx, files.size(), Vector<String>());
134 Vector<String> deps;
135
136 for (int i = 0; i < files[p_idx]->deps.size(); i++) {
137 String dep = files[p_idx]->deps[i];
138 int sep_idx = dep.find("::"); //may contain type information, unwanted
139 if (sep_idx != -1) {
140 dep = dep.substr(0, sep_idx);
141 }
142 ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(dep);
143 if (uid != ResourceUID::INVALID_ID) {
144 //return proper dependency resource from uid
145 if (ResourceUID::get_singleton()->has_id(uid)) {
146 dep = ResourceUID::get_singleton()->get_id_path(uid);
147 } else {
148 continue;
149 }
150 }
151 deps.push_back(dep);
152 }
153 return deps;
154 }
155
156 bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const {
157 ERR_FAIL_INDEX_V(p_idx, files.size(), false);
158 return files[p_idx]->import_valid;
159 }
160
161 uint64_t EditorFileSystemDirectory::get_file_modified_time(int p_idx) const {
162 ERR_FAIL_INDEX_V(p_idx, files.size(), 0);
163 return files[p_idx]->modified_time;
164 }
165
166 uint64_t EditorFileSystemDirectory::get_file_import_modified_time(int p_idx) const {
167 ERR_FAIL_INDEX_V(p_idx, files.size(), 0);
168 return files[p_idx]->import_modified_time;
169 }
170
171 String EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const {
172 return files[p_idx]->class_info.name;
173 }
174
175 String EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const {
176 return files[p_idx]->class_info.extends;
177 }
178
179 String EditorFileSystemDirectory::get_file_script_class_icon_path(int p_idx) const {
180 return files[p_idx]->class_info.icon_path;
181 }
182
183 String EditorFileSystemDirectory::get_file_icon_path(int p_idx) const {
184 return files[p_idx]->class_info.icon_path;
185 }
186
187 StringName EditorFileSystemDirectory::get_file_type(int p_idx) const {
188 ERR_FAIL_INDEX_V(p_idx, files.size(), "");
189 return files[p_idx]->type;
190 }
191
192 StringName EditorFileSystemDirectory::get_file_resource_script_class(int p_idx) const {
193 ERR_FAIL_INDEX_V(p_idx, files.size(), "");
194 return files[p_idx]->resource_script_class;
195 }
196
197 String EditorFileSystemDirectory::get_name() {
198 return name;
199 }
200
201 EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() {
202 return parent;
203 }
204
205 void EditorFileSystemDirectory::_bind_methods() {
206 ClassDB::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count);
207 ClassDB::bind_method(D_METHOD("get_subdir", "idx"), &EditorFileSystemDirectory::get_subdir);
208 ClassDB::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count);
209 ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file);
210 ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path);
211 ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type);
212 ClassDB::bind_method(D_METHOD("get_file_script_class_name", "idx"), &EditorFileSystemDirectory::get_file_script_class_name);
213 ClassDB::bind_method(D_METHOD("get_file_script_class_extends", "idx"), &EditorFileSystemDirectory::get_file_script_class_extends);
214 ClassDB::bind_method(D_METHOD("get_file_import_is_valid", "idx"), &EditorFileSystemDirectory::get_file_import_is_valid);
215 ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name);
216 ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path);
217 ClassDB::bind_method(D_METHOD("get_parent"), &EditorFileSystemDirectory::get_parent);
218 ClassDB::bind_method(D_METHOD("find_file_index", "name"), &EditorFileSystemDirectory::find_file_index);
219 ClassDB::bind_method(D_METHOD("find_dir_index", "name"), &EditorFileSystemDirectory::find_dir_index);
220 }
221
222 EditorFileSystemDirectory::EditorFileSystemDirectory() {
223 modified_time = 0;
224 parent = nullptr;
225 }
226
227 EditorFileSystemDirectory::~EditorFileSystemDirectory() {
228 for (EditorFileSystemDirectory::FileInfo *fi : files) {
229 memdelete(fi);
230 }
231
232 for (EditorFileSystemDirectory *dir : subdirs) {
233 memdelete(dir);
234 }
235 }
236
237 EditorFileSystem::ScannedDirectory::~ScannedDirectory() {
238 for (ScannedDirectory *dir : subdirs) {
239 memdelete(dir);
240 }
241 }
242
243 void EditorFileSystem::_load_first_scan_root_dir() {
244 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
245 first_scan_root_dir = memnew(ScannedDirectory);
246 first_scan_root_dir->full_path = "res://";
247
248 nb_files_total = _scan_new_dir(first_scan_root_dir, d);
249 }
250
251 void EditorFileSystem::scan_for_uid() {
252 // Load file structure into memory.
253 _load_first_scan_root_dir();
254
255 // Load extensions for which an .import should exists.
256 List<String> extensionsl;
257 HashSet<String> import_extensions;
258 ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl);
259 for (const String &E : extensionsl) {
260 import_extensions.insert(E);
261 }
262
263 // Scan the file system to load uid.
264 _scan_for_uid_directory(first_scan_root_dir, import_extensions);
265
266 // It's done, resetting the callback method to prevent a second scan.
267 ResourceUID::scan_for_uid_on_startup = nullptr;
268 }
269
270 void EditorFileSystem::_scan_for_uid_directory(const ScannedDirectory *p_scan_dir, const HashSet<String> &p_import_extensions) {
271 for (ScannedDirectory *scan_sub_dir : p_scan_dir->subdirs) {
272 _scan_for_uid_directory(scan_sub_dir, p_import_extensions);
273 }
274
275 for (const String &scan_file : p_scan_dir->files) {
276 const String ext = scan_file.get_extension().to_lower();
277
278 if (ext == "uid" || ext == "import") {
279 continue;
280 }
281
282 const String path = p_scan_dir->full_path.path_join(scan_file);
283 ResourceUID::ID uid = ResourceUID::INVALID_ID;
284 if (p_import_extensions.has(ext)) {
285 if (FileAccess::exists(path + ".import")) {
286 uid = ResourceFormatImporter::get_singleton()->get_resource_uid(path);
287 }
288 } else {
289 uid = ResourceLoader::get_resource_uid(path);
290 }
291
292 if (uid != ResourceUID::INVALID_ID) {
293 if (!ResourceUID::get_singleton()->has_id(uid)) {
294 ResourceUID::get_singleton()->add_id(uid, path);
295 }
296 }
297 }
298 }
299
300 void EditorFileSystem::_first_scan_filesystem() {
301 EditorProgress ep = EditorProgress("first_scan_filesystem", TTR("Project initialization"), 5);
302 HashSet<String> existing_class_names;
303 HashSet<String> extensions;
304
305 if (!first_scan_root_dir) {
306 ep.step(TTR("Scanning file structure..."), 0, true);
307 _load_first_scan_root_dir();
308 }
309
310 // Preloading GDExtensions file extensions to prevent looping on all the resource loaders
311 // for each files in _first_scan_process_scripts.
312 List<String> gdextension_extensions;
313 ResourceLoader::get_recognized_extensions_for_type("GDExtension", &gdextension_extensions);
314
315 // This loads the global class names from the scripts and ensures that even if the
316 // global_script_class_cache.cfg was missing or invalid, the global class names are valid in ScriptServer.
317 // At the same time, to prevent looping multiple times in all files, it looks for extensions.
318 ep.step(TTR("Loading global class names..."), 1, true);
319 _first_scan_process_scripts(first_scan_root_dir, gdextension_extensions, existing_class_names, extensions);
320
321 // Removing invalid global class to prevent having invalid paths in ScriptServer.
322 bool save_scripts = _remove_invalid_global_class_names(existing_class_names);
323
324 // If a global class is found or removed, we sync global_script_class_cache.cfg with the ScriptServer
325 if (!existing_class_names.is_empty() || save_scripts) {
326 EditorNode::get_editor_data().script_class_save_global_classes();
327 }
328
329 // Processing extensions to add new extensions or remove invalid ones.
330 // Important to do it in the first scan so custom types, new class names, custom importers, etc...
331 // from extensions are ready to go before plugins, autoloads and resources validation/importation.
332 // At this point, a restart of the editor should not be needed so we don't use the return value.
333 ep.step(TTR("Verifying GDExtensions..."), 2, true);
334 GDExtensionManager::get_singleton()->ensure_extensions_loaded(extensions);
335
336 // Now that all the global class names should be loaded, create autoloads and plugins.
337 // This is done after loading the global class names because autoloads and plugins can use
338 // global class names.
339 ep.step(TTR("Creating autoload scripts..."), 3, true);
340 ProjectSettingsEditor::get_singleton()->init_autoloads();
341
342 ep.step(TTR("Initializing plugins..."), 4, true);
343 EditorNode::get_singleton()->init_plugins();
344
345 ep.step(TTR("Starting file scan..."), 5, true);
346 }
347
348 void EditorFileSystem::_first_scan_process_scripts(const ScannedDirectory *p_scan_dir, List<String> &p_gdextension_extensions, HashSet<String> &p_existing_class_names, HashSet<String> &p_extensions) {
349 for (ScannedDirectory *scan_sub_dir : p_scan_dir->subdirs) {
350 _first_scan_process_scripts(scan_sub_dir, p_gdextension_extensions, p_existing_class_names, p_extensions);
351 }
352
353 for (const String &scan_file : p_scan_dir->files) {
354 // Optimization to skip the ResourceLoader::get_resource_type for files
355 // that are not scripts. Some loader get_resource_type methods read the file
356 // which can be very slow on large projects.
357 const String ext = scan_file.get_extension().to_lower();
358 bool is_script = false;
359 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
360 if (ScriptServer::get_language(i)->get_extension() == ext) {
361 is_script = true;
362 break;
363 }
364 }
365 if (is_script) {
366 const String path = p_scan_dir->full_path.path_join(scan_file);
367 const String type = ResourceLoader::get_resource_type(path);
368
369 if (ClassDB::is_parent_class(type, SNAME("Script"))) {
370 const ScriptClassInfo &info = _get_global_script_class(type, path);
371 ScriptClassInfoUpdate update(info);
372 update.type = type;
373 _register_global_class_script(path, path, update);
374
375 if (!info.name.is_empty()) {
376 p_existing_class_names.insert(info.name);
377 }
378 }
379 }
380
381 // Check for GDExtensions.
382 if (p_gdextension_extensions.find(ext)) {
383 const String path = p_scan_dir->full_path.path_join(scan_file);
384 const String type = ResourceLoader::get_resource_type(path);
385 if (type == SNAME("GDExtension")) {
386 p_extensions.insert(path);
387 }
388 }
389 }
390 }
391
392 void EditorFileSystem::_scan_filesystem() {
393 // On the first scan, the first_scan_root_dir is created in _first_scan_filesystem.
394 ERR_FAIL_COND(!scanning || new_filesystem || (first_scan && !first_scan_root_dir));
395
396 //read .fscache
397 String cpath;
398
399 sources_changed.clear();
400 file_cache.clear();
401
402 String project = ProjectSettings::get_singleton()->get_resource_path();
403
404 String fscache = EditorPaths::get_singleton()->get_project_settings_dir().path_join(CACHE_FILE_NAME);
405 {
406 Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::READ);
407
408 bool first = true;
409 if (f.is_valid()) {
410 //read the disk cache
411 while (!f->eof_reached()) {
412 String l = f->get_line().strip_edges();
413 if (first) {
414 if (first_scan) {
415 // only use this on first scan, afterwards it gets ignored
416 // this is so on first reimport we synchronize versions, then
417 // we don't care until editor restart. This is for usability mainly so
418 // your workflow is not killed after changing a setting by forceful reimporting
419 // everything there is.
420 filesystem_settings_version_for_import = l.strip_edges();
421 if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) {
422 revalidate_import_files = true;
423 }
424 }
425 first = false;
426 continue;
427 }
428 if (l.is_empty()) {
429 continue;
430 }
431
432 if (l.begins_with("::")) {
433 Vector<String> split = l.split("::");
434 ERR_CONTINUE(split.size() != 3);
435 const String &name = split[1];
436
437 cpath = name;
438
439 } else {
440 // The last section (deps) may contain the same splitter, so limit the maxsplit to 8 to get the complete deps.
441 Vector<String> split = l.split("::", true, 8);
442 ERR_CONTINUE(split.size() < 9);
443 String name = split[0];
444 String file;
445
446 file = name;
447 name = cpath.path_join(name);
448
449 FileCache fc;
450 fc.type = split[1].get_slicec('/', 0);
451 fc.resource_script_class = split[1].get_slicec('/', 1);
452 fc.uid = split[2].to_int();
453 fc.modification_time = split[3].to_int();
454 fc.import_modification_time = split[4].to_int();
455 fc.import_valid = split[5].to_int() != 0;
456 fc.import_group_file = split[6].strip_edges();
457 {
458 const Vector<String> &slices = split[7].split("<>");
459 ERR_CONTINUE(slices.size() < 7);
460 fc.class_info.name = slices[0];
461 fc.class_info.extends = slices[1];
462 fc.class_info.icon_path = slices[2];
463 fc.class_info.is_abstract = slices[3].to_int();
464 fc.class_info.is_tool = slices[4].to_int();
465 fc.import_md5 = slices[5];
466 fc.import_dest_paths = slices[6].split("<*>");
467 }
468 fc.deps = split[8].strip_edges().split("<>", false);
469
470 file_cache[name] = fc;
471 }
472 }
473 }
474 }
475
476 const String update_cache = EditorPaths::get_singleton()->get_project_settings_dir().path_join("filesystem_update4");
477 if (first_scan && FileAccess::exists(update_cache)) {
478 {
479 Ref<FileAccess> f2 = FileAccess::open(update_cache, FileAccess::READ);
480 String l = f2->get_line().strip_edges();
481 while (!l.is_empty()) {
482 dep_update_list.insert(l);
483 file_cache.erase(l); // Erase cache for this, so it gets updated.
484 l = f2->get_line().strip_edges();
485 }
486 }
487
488 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
489 d->remove(update_cache); // Bye bye update cache.
490 }
491
492 EditorProgressBG scan_progress("efs", "ScanFS", 1000);
493 ScanProgress sp;
494 sp.hi = nb_files_total;
495 sp.progress = &scan_progress;
496
497 new_filesystem = memnew(EditorFileSystemDirectory);
498 new_filesystem->parent = nullptr;
499
500 ScannedDirectory *sd;
501 HashSet<String> *processed_files = nullptr;
502 // On the first scan, the first_scan_root_dir is created in _first_scan_filesystem.
503 if (first_scan) {
504 sd = first_scan_root_dir;
505 // Will be updated on scan.
506 ResourceUID::get_singleton()->clear();
507 ResourceUID::scan_for_uid_on_startup = nullptr;
508 processed_files = memnew(HashSet<String>());
509 } else {
510 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
511 sd = memnew(ScannedDirectory);
512 sd->full_path = "res://";
513 nb_files_total = _scan_new_dir(sd, d);
514 }
515
516 _process_file_system(sd, new_filesystem, sp, processed_files);
517
518 if (first_scan) {
519 _process_removed_files(*processed_files);
520 }
521 dep_update_list.clear();
522 file_cache.clear(); //clear caches, no longer needed
523
524 if (first_scan) {
525 memdelete(first_scan_root_dir);
526 first_scan_root_dir = nullptr;
527 memdelete(processed_files);
528 } else {
529 //on the first scan this is done from the main thread after re-importing
530 _save_filesystem_cache();
531 }
532
533 scanning = false;
534 }
535
536 void EditorFileSystem::_save_filesystem_cache() {
537 group_file_cache.clear();
538
539 String fscache = EditorPaths::get_singleton()->get_project_settings_dir().path_join(CACHE_FILE_NAME);
540
541 Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::WRITE);
542 ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + fscache + "'. Check user write permissions.");
543
544 f->store_line(filesystem_settings_version_for_import);
545 _save_filesystem_cache(filesystem, f);
546 }
547
548 void EditorFileSystem::_thread_func(void *_userdata) {
549 EditorFileSystem *sd = (EditorFileSystem *)_userdata;
550 sd->_scan_filesystem();
551 }
552
553 bool EditorFileSystem::_is_test_for_reimport_needed(const String &p_path, uint64_t p_last_modification_time, uint64_t p_modification_time, uint64_t p_last_import_modification_time, uint64_t p_import_modification_time, const Vector<String> &p_import_dest_paths) {
554 // The idea here is to trust the cache. If the last modification times in the cache correspond
555 // to the last modification times of the files on disk, it means the files have not changed since
556 // the last import, and the files in .godot/imported (p_import_dest_paths) should all be valid.
557 if (p_last_modification_time != p_modification_time) {
558 return true;
559 }
560 if (p_last_import_modification_time != p_import_modification_time) {
561 return true;
562 }
563 if (reimport_on_missing_imported_files) {
564 for (const String &path : p_import_dest_paths) {
565 if (!FileAccess::exists(path)) {
566 return true;
567 }
568 }
569 }
570 return false;
571 }
572
573 bool EditorFileSystem::_test_for_reimport(const String &p_path, const String &p_expected_import_md5) {
574 if (p_expected_import_md5.is_empty()) {
575 // Marked as reimportation needed.
576 return true;
577 }
578 String new_md5 = FileAccess::get_md5(p_path + ".import");
579 if (p_expected_import_md5 != new_md5) {
580 return true;
581 }
582
583 Error err;
584 Ref<FileAccess> f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
585
586 if (f.is_null()) { // No import file, reimport.
587 return true;
588 }
589
590 VariantParser::StreamFile stream;
591 stream.f = f;
592
593 String assign;
594 Variant value;
595 VariantParser::Tag next_tag;
596
597 int lines = 0;
598 String error_text;
599
600 Vector<String> to_check;
601
602 String importer_name;
603 String source_file = "";
604 String source_md5 = "";
605 Vector<String> dest_files;
606 String dest_md5 = "";
607 int version = 0;
608 bool found_uid = false;
609 Variant meta;
610
611 while (true) {
612 assign = Variant();
613 next_tag.fields.clear();
614 next_tag.name = String();
615
616 err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
617 if (err == ERR_FILE_EOF) {
618 break;
619 } else if (err != OK) {
620 ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'.");
621 // Parse error, skip and let user attempt manual reimport to avoid reimport loop.
622 return false;
623 }
624
625 if (!assign.is_empty()) {
626 if (assign == "valid" && value.operator bool() == false) {
627 // Invalid import (failed previous import), skip and let user attempt manual reimport to avoid reimport loop.
628 return false;
629 }
630 if (assign.begins_with("path")) {
631 to_check.push_back(value);
632 } else if (assign == "files") {
633 Array fa = value;
634 for (const Variant &check_path : fa) {
635 to_check.push_back(check_path);
636 }
637 } else if (assign == "importer_version") {
638 version = value;
639 } else if (assign == "importer") {
640 importer_name = value;
641 } else if (assign == "uid") {
642 found_uid = true;
643 } else if (assign == "source_file") {
644 source_file = value;
645 } else if (assign == "dest_files") {
646 dest_files = value;
647 } else if (assign == "metadata") {
648 meta = value;
649 }
650
651 } else if (next_tag.name != "remap" && next_tag.name != "deps") {
652 break;
653 }
654 }
655
656 if (importer_name == "keep" || importer_name == "skip") {
657 return false; // Keep mode, do not reimport.
658 }
659
660 if (!found_uid) {
661 return true; // UID not found, old format, reimport.
662 }
663
664 // Imported files are gone, reimport.
665 for (const String &E : to_check) {
666 if (!FileAccess::exists(E)) {
667 return true;
668 }
669 }
670
671 Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
672
673 if (importer.is_null()) {
674 return true; // The importer has possibly changed, try to reimport.
675 }
676
677 if (importer->get_format_version() > version) {
678 return true; // Version changed, reimport.
679 }
680
681 if (!importer->are_import_settings_valid(p_path, meta)) {
682 // Reimport settings are out of sync with project settings, reimport.
683 return true;
684 }
685
686 // Read the md5's from a separate file (so the import parameters aren't dependent on the file version).
687 String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path);
688 Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err);
689 if (md5s.is_null()) { // No md5's stored for this resource.
690 return true;
691 }
692
693 VariantParser::StreamFile md5_stream;
694 md5_stream.f = md5s;
695
696 while (true) {
697 assign = Variant();
698 next_tag.fields.clear();
699 next_tag.name = String();
700
701 err = VariantParser::parse_tag_assign_eof(&md5_stream, lines, error_text, next_tag, assign, value, nullptr, true);
702
703 if (err == ERR_FILE_EOF) {
704 break;
705 } else if (err != OK) {
706 ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import.md5:" + itos(lines) + "' error '" + error_text + "'.");
707 return false; // Parse error.
708 }
709 if (!assign.is_empty()) {
710 if (assign == "source_md5") {
711 source_md5 = value;
712 } else if (assign == "dest_md5") {
713 dest_md5 = value;
714 }
715 }
716 }
717
718 // Check source md5 matching.
719 if (!source_file.is_empty() && source_file != p_path) {
720 return true; // File was moved, reimport.
721 }
722
723 if (source_md5.is_empty()) {
724 return true; // Lacks md5, so just reimport.
725 }
726
727 String md5 = FileAccess::get_md5(p_path);
728 if (md5 != source_md5) {
729 return true;
730 }
731
732 if (!dest_files.is_empty() && !dest_md5.is_empty()) {
733 md5 = FileAccess::get_multiple_md5(dest_files);
734 if (md5 != dest_md5) {
735 return true;
736 }
737 }
738
739 return false; // Nothing changed.
740 }
741
742 Vector<String> EditorFileSystem::_get_import_dest_paths(const String &p_path) {
743 Error err;
744 Ref<FileAccess> f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
745
746 if (f.is_null()) { // No import file, reimport.
747 return Vector<String>();
748 }
749
750 VariantParser::StreamFile stream;
751 stream.f = f;
752
753 String assign;
754 Variant value;
755 VariantParser::Tag next_tag;
756
757 int lines = 0;
758 String error_text;
759
760 Vector<String> dest_paths;
761 String importer_name;
762
763 while (true) {
764 assign = Variant();
765 next_tag.fields.clear();
766 next_tag.name = String();
767
768 err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
769 if (err == ERR_FILE_EOF) {
770 break;
771 } else if (err != OK) {
772 ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'.");
773 // Parse error, skip and let user attempt manual reimport to avoid reimport loop.
774 return Vector<String>();
775 }
776
777 if (!assign.is_empty()) {
778 if (assign == "valid" && value.operator bool() == false) {
779 // Invalid import (failed previous import), skip and let user attempt manual reimport to avoid reimport loop.
780 return Vector<String>();
781 }
782 if (assign.begins_with("path")) {
783 dest_paths.push_back(value);
784 } else if (assign == "files") {
785 Array fa = value;
786 for (const Variant &dest_path : fa) {
787 dest_paths.push_back(dest_path);
788 }
789 } else if (assign == "importer") {
790 importer_name = value;
791 }
792 } else if (next_tag.name != "remap" && next_tag.name != "deps") {
793 break;
794 }
795 }
796
797 if (importer_name == "keep" || importer_name == "skip") {
798 return Vector<String>();
799 }
800
801 return dest_paths;
802 }
803
804 bool EditorFileSystem::_scan_import_support(const Vector<String> &reimports) {
805 if (import_support_queries.is_empty()) {
806 return false;
807 }
808 HashMap<String, int> import_support_test;
809 Vector<bool> import_support_tested;
810 import_support_tested.resize(import_support_queries.size());
811 for (int i = 0; i < import_support_queries.size(); i++) {
812 import_support_tested.write[i] = false;
813 if (import_support_queries[i]->is_active()) {
814 Vector<String> extensions = import_support_queries[i]->get_file_extensions();
815 for (int j = 0; j < extensions.size(); j++) {
816 import_support_test.insert(extensions[j], i);
817 }
818 }
819 }
820
821 if (import_support_test.is_empty()) {
822 return false; //well nothing to do
823 }
824
825 for (int i = 0; i < reimports.size(); i++) {
826 HashMap<String, int>::Iterator E = import_support_test.find(reimports[i].get_extension().to_lower());
827 if (E) {
828 import_support_tested.write[E->value] = true;
829 }
830 }
831
832 for (int i = 0; i < import_support_tested.size(); i++) {
833 if (import_support_tested[i]) {
834 if (import_support_queries.write[i]->query()) {
835 return true;
836 }
837 }
838 }
839
840 return false;
841 }
842
843 bool EditorFileSystem::_update_scan_actions() {
844 sources_changed.clear();
845
846 // We need to update the script global class names before the reimports to be sure that
847 // all the importer classes that depends on class names will work.
848 _update_script_classes();
849
850 bool fs_changed = false;
851
852 Vector<String> reimports;
853 Vector<String> reloads;
854
855 EditorProgress *ep = nullptr;
856 if (scan_actions.size() > 1) {
857 ep = memnew(EditorProgress("_update_scan_actions", TTR("Scanning actions..."), scan_actions.size()));
858 }
859
860 int step_count = 0;
861 for (const ItemAction &ia : scan_actions) {
862 switch (ia.action) {
863 case ItemAction::ACTION_NONE: {
864 } break;
865 case ItemAction::ACTION_DIR_ADD: {
866 int idx = 0;
867 for (int i = 0; i < ia.dir->subdirs.size(); i++) {
868 if (ia.new_dir->name.filenocasecmp_to(ia.dir->subdirs[i]->name) < 0) {
869 break;
870 }
871 idx++;
872 }
873 if (idx == ia.dir->subdirs.size()) {
874 ia.dir->subdirs.push_back(ia.new_dir);
875 } else {
876 ia.dir->subdirs.insert(idx, ia.new_dir);
877 }
878
879 fs_changed = true;
880 } break;
881 case ItemAction::ACTION_DIR_REMOVE: {
882 ERR_CONTINUE(!ia.dir->parent);
883 ia.dir->parent->subdirs.erase(ia.dir);
884 memdelete(ia.dir);
885 fs_changed = true;
886 } break;
887 case ItemAction::ACTION_FILE_ADD: {
888 int idx = 0;
889 for (int i = 0; i < ia.dir->files.size(); i++) {
890 if (ia.new_file->file.filenocasecmp_to(ia.dir->files[i]->file) < 0) {
891 break;
892 }
893 idx++;
894 }
895 if (idx == ia.dir->files.size()) {
896 ia.dir->files.push_back(ia.new_file);
897 } else {
898 ia.dir->files.insert(idx, ia.new_file);
899 }
900
901 fs_changed = true;
902
903 const String new_file_path = ia.dir->get_file_path(idx);
904 const ResourceUID::ID existing_id = ResourceLoader::get_resource_uid(new_file_path);
905 if (existing_id != ResourceUID::INVALID_ID) {
906 const bool id_known = ResourceUID::get_singleton()->has_id(existing_id);
907 const String old_path = id_known ? ResourceUID::get_singleton()->get_id_path(existing_id) : String();
908
909 if (id_known && old_path != new_file_path && FileAccess::exists(old_path)) {
910 const ResourceUID::ID new_id = ResourceUID::get_singleton()->create_id_for_path(new_file_path);
911 ResourceUID::get_singleton()->add_id(new_id, new_file_path);
912 ResourceSaver::set_uid(new_file_path, new_id);
913 WARN_PRINT(vformat("Duplicate UID detected for Resource at \"%s\".\nOld Resource path: \"%s\". The new file UID was changed automatically.", new_file_path, old_path));
914 ia.new_file->uid = new_id;
915 } else {
916 // Re-assign the UID to file, just in case it was pulled from cache.
917 ResourceSaver::set_uid(new_file_path, existing_id);
918
919 if (id_known) {
920 ResourceUID::get_singleton()->set_id(existing_id, new_file_path);
921 } else {
922 ResourceUID::get_singleton()->add_id(existing_id, new_file_path);
923 }
924
925 ia.new_file->uid = existing_id;
926 }
927 } else if (ResourceLoader::should_create_uid_file(new_file_path)) {
928 Ref<FileAccess> f = FileAccess::open(new_file_path + ".uid", FileAccess::WRITE);
929 if (f.is_valid()) {
930 ia.new_file->uid = ResourceUID::get_singleton()->create_id_for_path(new_file_path);
931 f->store_line(ResourceUID::get_singleton()->id_to_text(ia.new_file->uid));
932 }
933 }
934
935 if (ClassDB::is_parent_class(ia.new_file->type, SNAME("Script"))) {
936 _queue_update_script_class(new_file_path, ScriptClassInfoUpdate::from_file_info(ia.new_file));
937 }
938 if (ia.new_file->type == SNAME("PackedScene")) {
939 _queue_update_scene_groups(new_file_path);
940 }
941
942 } break;
943 case ItemAction::ACTION_FILE_REMOVE: {
944 int idx = ia.dir->find_file_index(ia.file);
945 ERR_CONTINUE(idx == -1);
946
947 const String file_path = ia.dir->get_file_path(idx);
948 const String class_name = ia.dir->files[idx]->class_info.name;
949 if (ClassDB::is_parent_class(ia.dir->files[idx]->type, SNAME("Script"))) {
950 _queue_update_script_class(file_path, ScriptClassInfoUpdate());
951 }
952 if (ia.dir->files[idx]->type == SNAME("PackedScene")) {
953 _queue_update_scene_groups(file_path);
954 }
955
956 _delete_internal_files(file_path);
957 memdelete(ia.dir->files[idx]);
958 ia.dir->files.remove_at(idx);
959
960 // Restore another script with the same global class name if it exists.
961 if (!class_name.is_empty()) {
962 EditorFileSystemDirectory::FileInfo *old_fi = nullptr;
963 String old_file = _get_file_by_class_name(filesystem, class_name, old_fi);
964 if (!old_file.is_empty() && old_fi) {
965 _queue_update_script_class(old_file, ScriptClassInfoUpdate::from_file_info(old_fi));
966 }
967 }
968
969 fs_changed = true;
970
971 } break;
972 case ItemAction::ACTION_FILE_TEST_REIMPORT: {
973 int idx = ia.dir->find_file_index(ia.file);
974 ERR_CONTINUE(idx == -1);
975 String full_path = ia.dir->get_file_path(idx);
976
977 bool need_reimport = _test_for_reimport(full_path, ia.dir->files[idx]->import_md5);
978 if (need_reimport) {
979 // Must reimport.
980 reimports.push_back(full_path);
981 Vector<String> dependencies = _get_dependencies(full_path);
982 for (const String &dep : dependencies) {
983 const String &dependency_path = dep.contains("::") ? dep.get_slice("::", 0) : dep;
984 if (_can_import_file(dep)) {
985 reimports.push_back(dependency_path);
986 }
987 }
988 } else {
989 // Must not reimport, all was good.
990 // Update modified times, md5 and destination paths, to avoid reimport.
991 ia.dir->files[idx]->modified_time = FileAccess::get_modified_time(full_path);
992 ia.dir->files[idx]->import_modified_time = FileAccess::get_modified_time(full_path + ".import");
993 if (ia.dir->files[idx]->import_md5.is_empty()) {
994 ia.dir->files[idx]->import_md5 = FileAccess::get_md5(full_path + ".import");
995 }
996 ia.dir->files[idx]->import_dest_paths = _get_import_dest_paths(full_path);
997 }
998
999 fs_changed = true;
1000 } break;
1001 case ItemAction::ACTION_FILE_RELOAD: {
1002 int idx = ia.dir->find_file_index(ia.file);
1003 ERR_CONTINUE(idx == -1);
1004
1005 // Only reloads the resources that are already loaded.
1006 if (ResourceCache::has(ia.dir->get_file_path(idx))) {
1007 reloads.push_back(ia.dir->get_file_path(idx));
1008 }
1009 } break;
1010 }
1011
1012 if (ep) {
1013 ep->step(ia.file, step_count++, false);
1014 }
1015 }
1016
1017 memdelete_notnull(ep);
1018
1019 if (_scan_extensions()) {
1020 //needs editor restart
1021 //extensions also may provide filetypes to be imported, so they must run before importing
1022 if (EditorNode::immediate_confirmation_dialog(TTR("Some extensions need the editor to restart to take effect."), first_scan ? TTR("Restart") : TTR("Save & Restart"), TTR("Continue"))) {
1023 if (!first_scan) {
1024 EditorNode::get_singleton()->save_all_scenes();
1025 }
1026 EditorNode::get_singleton()->restart_editor();
1027 //do not import
1028 return true;
1029 }
1030 }
1031
1032 if (!reimports.is_empty()) {
1033 if (_scan_import_support(reimports)) {
1034 return true;
1035 }
1036
1037 reimport_files(reimports);
1038 } else {
1039 //reimport files will update the uid cache file so if nothing was reimported, update it manually
1040 ResourceUID::get_singleton()->update_cache();
1041 }
1042
1043 if (!reloads.is_empty()) {
1044 // Update global class names, dependencies, etc...
1045 update_files(reloads);
1046 }
1047
1048 if (first_scan) {
1049 //only on first scan this is valid and updated, then settings changed.
1050 revalidate_import_files = false;
1051 filesystem_settings_version_for_import = ResourceFormatImporter::get_singleton()->get_import_settings_hash();
1052 _save_filesystem_cache();
1053 }
1054
1055 // Moving the processing of pending updates before the resources_reload event to be sure all global class names
1056 // are updated. Script.cpp listens on resources_reload and reloads updated scripts.
1057 _process_update_pending();
1058
1059 if (reloads.size()) {
1060 emit_signal(SNAME("resources_reload"), reloads);
1061 }
1062 scan_actions.clear();
1063
1064 return fs_changed;
1065 }
1066
1067 void EditorFileSystem::scan() {
1068 if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/) {
1069 return;
1070 }
1071
1072 if (scanning || scanning_changes || thread.is_started()) {
1073 return;
1074 }
1075
1076 // The first scan must be on the main thread because, after the first scan and update
1077 // of global class names, we load the plugins and autoloads. These need to
1078 // be added on the main thread because they are nodes, and we need to wait for them
1079 // to be loaded to continue the scan and reimportations.
1080 if (first_scan) {
1081 _first_scan_filesystem();
1082 #ifdef ANDROID_ENABLED
1083 // Create a .nomedia file to hide assets from media apps on Android.
1084 // Android 11 has some issues with nomedia files, so it's disabled there. See GH-106479 and GH-105399 for details.
1085 // NOTE: Nomedia file is also handled in project manager. See project_dialog.cpp -> ProjectDialog::ok_pressed().
1086 String sdk_version = OS::get_singleton()->get_version().get_slicec('.', 0);
1087 if (sdk_version != "30") {
1088 const String nomedia_file_path = ProjectSettings::get_singleton()->get_resource_path().path_join(".nomedia");
1089 if (!FileAccess::exists(nomedia_file_path)) {
1090 Ref<FileAccess> f = FileAccess::open(nomedia_file_path, FileAccess::WRITE);
1091 if (f.is_null()) {
1092 // .nomedia isn't so critical.
1093 ERR_PRINT("Couldn't create .nomedia in project path.");
1094 } else {
1095 f->close();
1096 }
1097 }
1098 }
1099 #endif
1100 }
1101
1102 _update_extensions();
1103
1104 if (!use_threads) {
1105 scanning = true;
1106 scan_total = 0;
1107 _scan_filesystem();
1108 if (filesystem) {
1109 memdelete(filesystem);
1110 }
1111 //file_type_cache.clear();
1112 filesystem = new_filesystem;
1113 new_filesystem = nullptr;
1114 _update_scan_actions();
1115 // Update all icons so they are loaded for the FileSystemDock.
1116 _update_files_icon_path();
1117 scanning = false;
1118 // Set first_scan to false before the signals so the function doing_first_scan can return false
1119 // in editor_node to start the export if needed.
1120 first_scan = false;
1121 ResourceImporter::load_on_startup = nullptr;
1122 emit_signal(SNAME("filesystem_changed"));
1123 emit_signal(SNAME("sources_changed"), sources_changed.size() > 0);
1124 } else {
1125 ERR_FAIL_COND(thread.is_started());
1126 set_process(true);
1127 Thread::Settings s;
1128 scanning = true;
1129 scan_total = 0;
1130 s.priority = Thread::PRIORITY_LOW;
1131 thread.start(_thread_func, this, s);
1132 }
1133 }
1134
1135 void EditorFileSystem::ScanProgress::increment() {
1136 current++;
1137 float ratio = current / MAX(hi, 1.0f);
1138 if (progress) {
1139 progress->step(ratio * 1000.0f);
1140 }
1141 EditorFileSystem::singleton->scan_total = ratio;
1142 }
1143
1144 int EditorFileSystem::_scan_new_dir(ScannedDirectory *p_dir, Ref<DirAccess> &da) {
1145 List<String> dirs;
1146 List<String> files;
1147
1148 String cd = da->get_current_dir();
1149
1150 da->list_dir_begin();
1151 while (true) {
1152 String f = da->get_next();
1153 if (f.is_empty()) {
1154 break;
1155 }
1156
1157 if (da->current_is_hidden()) {
1158 continue;
1159 }
1160
1161 if (da->current_is_dir()) {
1162 if (f.begins_with(".")) { // Ignore special and . / ..
1163 continue;
1164 }
1165
1166 if (_should_skip_directory(cd.path_join(f))) {
1167 continue;
1168 }
1169
1170 dirs.push_back(f);
1171
1172 } else {
1173 files.push_back(f);
1174 }
1175 }
1176
1177 da->list_dir_end();
1178
1179 dirs.sort_custom<FileNoCaseComparator>();
1180 files.sort_custom<FileNoCaseComparator>();
1181
1182 int nb_files_total_scan = 0;
1183
1184 for (const String &dir : dirs) {
1185 if (da->change_dir(dir) == OK) {
1186 String d = da->get_current_dir();
1187
1188 if (d == cd || !d.begins_with(cd)) {
1189 da->change_dir(cd); //avoid recursion
1190 } else {
1191 ScannedDirectory *sd = memnew(ScannedDirectory);
1192 sd->name = dir;
1193 sd->full_path = p_dir->full_path.path_join(sd->name);
1194
1195 nb_files_total_scan += _scan_new_dir(sd, da);
1196
1197 p_dir->subdirs.push_back(sd);
1198
1199 da->change_dir("..");
1200 }
1201 } else {
1202 ERR_PRINT("Cannot go into subdir '" + dir + "'.");
1203 }
1204 }
1205
1206 p_dir->files = files;
1207 nb_files_total_scan += files.size();
1208
1209 return nb_files_total_scan;
1210 }
1211
1212 void EditorFileSystem::_process_file_system(const ScannedDirectory *p_scan_dir, EditorFileSystemDirectory *p_dir, ScanProgress &p_progress, HashSet<String> *r_processed_files) {
1213 p_dir->modified_time = FileAccess::get_modified_time(p_scan_dir->full_path);
1214
1215 for (ScannedDirectory *scan_sub_dir : p_scan_dir->subdirs) {
1216 EditorFileSystemDirectory *sub_dir = memnew(EditorFileSystemDirectory);
1217 sub_dir->parent = p_dir;
1218 sub_dir->name = scan_sub_dir->name;
1219 p_dir->subdirs.push_back(sub_dir);
1220 _process_file_system(scan_sub_dir, sub_dir, p_progress, r_processed_files);
1221 }
1222
1223 for (const String &scan_file : p_scan_dir->files) {
1224 String ext = scan_file.get_extension().to_lower();
1225 if (!valid_extensions.has(ext)) {
1226 p_progress.increment();
1227 continue; //invalid
1228 }
1229
1230 String path = p_scan_dir->full_path.path_join(scan_file);
1231
1232 EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
1233 fi->file = scan_file;
1234 p_dir->files.push_back(fi);
1235
1236 if (r_processed_files) {
1237 r_processed_files->insert(path);
1238 }
1239
1240 FileCache *fc = file_cache.getptr(path);
1241 uint64_t mt = FileAccess::get_modified_time(path);
1242
1243 if (_can_import_file(scan_file)) {
1244 //is imported
1245 uint64_t import_mt = FileAccess::get_modified_time(path + ".import");
1246
1247 if (fc) {
1248 fi->type = fc->type;
1249 fi->resource_script_class = fc->resource_script_class;
1250 fi->uid = fc->uid;
1251 fi->deps = fc->deps;
1252 fi->modified_time = mt;
1253 fi->import_modified_time = import_mt;
1254 fi->import_md5 = fc->import_md5;
1255 fi->import_dest_paths = fc->import_dest_paths;
1256 fi->import_valid = fc->import_valid;
1257 fi->import_group_file = fc->import_group_file;
1258 fi->class_info = fc->class_info;
1259
1260 // Ensures backward compatibility when the project is loaded for the first time with the added import_md5
1261 // and import_dest_paths properties in the file cache.
1262 if (fc->import_md5.is_empty()) {
1263 fi->import_md5 = FileAccess::get_md5(path + ".import");
1264 fi->import_dest_paths = _get_import_dest_paths(path);
1265 }
1266
1267 // The method _is_test_for_reimport_needed checks if the files were modified and ensures that
1268 // all the destination files still exist without reading the .import file.
1269 // If something is different, we will queue a test for reimportation that will check
1270 // the md5 of all files and import settings and, if necessary, execute a reimportation.
1271 if (_is_test_for_reimport_needed(path, fc->modification_time, mt, fc->import_modification_time, import_mt, fi->import_dest_paths) ||
1272 (revalidate_import_files && !ResourceFormatImporter::get_singleton()->are_import_settings_valid(path))) {
1273 ItemAction ia;
1274 ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
1275 ia.dir = p_dir;
1276 ia.file = fi->file;
1277 scan_actions.push_back(ia);
1278 }
1279
1280 if (fc->type.is_empty()) {
1281 fi->type = ResourceLoader::get_resource_type(path);
1282 fi->resource_script_class = ResourceLoader::get_resource_script_class(path);
1283 fi->import_group_file = ResourceLoader::get_import_group_file(path);
1284 //there is also the chance that file type changed due to reimport, must probably check this somehow here (or kind of note it for next time in another file?)
1285 //note: I think this should not happen any longer..
1286 }
1287
1288 if (fc->uid == ResourceUID::INVALID_ID) {
1289 // imported files should always have a UID, so attempt to fetch it.
1290 fi->uid = ResourceLoader::get_resource_uid(path);
1291 }
1292
1293 } else {
1294 // Using get_resource_import_info() to prevent calling 3 times ResourceFormatImporter::_get_path_and_type.
1295 ResourceFormatImporter::get_singleton()->get_resource_import_info(path, fi->type, fi->uid, fi->import_group_file);
1296 fi->class_info = _get_global_script_class(fi->type, path);
1297 fi->modified_time = 0;
1298 fi->import_modified_time = 0;
1299 fi->import_md5 = FileAccess::get_md5(path + ".import");
1300 fi->import_dest_paths = Vector<String>();
1301 fi->import_valid = (fi->type == "TextFile" || fi->type == "OtherFile") ? true : ResourceLoader::is_import_valid(path);
1302
1303 ItemAction ia;
1304 ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
1305 ia.dir = p_dir;
1306 ia.file = fi->file;
1307 scan_actions.push_back(ia);
1308 }
1309 } else {
1310 if (fc && fc->modification_time == mt) {
1311 //not imported, so just update type if changed
1312 fi->type = fc->type;
1313 fi->resource_script_class = fc->resource_script_class;
1314 fi->uid = fc->uid;
1315 fi->modified_time = mt;
1316 fi->deps = fc->deps;
1317 fi->import_modified_time = 0;
1318 fi->import_md5 = "";
1319 fi->import_dest_paths = Vector<String>();
1320 fi->import_valid = true;
1321 fi->class_info = fc->class_info;
1322
1323 if (first_scan && ClassDB::is_parent_class(fi->type, SNAME("Script"))) {
1324 bool update_script = false;
1325 String old_class_name = fi->class_info.name;
1326 fi->class_info = _get_global_script_class(fi->type, path);
1327 if (old_class_name != fi->class_info.name) {
1328 update_script = true;
1329 } else if (!fi->class_info.name.is_empty() && (!ScriptServer::is_global_class(fi->class_info.name) || ScriptServer::get_global_class_path(fi->class_info.name) != path)) {
1330 // This script has a class name but is not in the global class names or the path of the class has changed.
1331 update_script = true;
1332 }
1333 if (update_script) {
1334 _queue_update_script_class(path, ScriptClassInfoUpdate::from_file_info(fi));
1335 }
1336 }
1337 } else {
1338 //new or modified time
1339 fi->type = ResourceLoader::get_resource_type(path);
1340 fi->resource_script_class = ResourceLoader::get_resource_script_class(path);
1341 if (fi->type == "" && textfile_extensions.has(ext)) {
1342 fi->type = "TextFile";
1343 }
1344 if (fi->type == "" && other_file_extensions.has(ext)) {
1345 fi->type = "OtherFile";
1346 }
1347 fi->uid = ResourceLoader::get_resource_uid(path);
1348 fi->class_info = _get_global_script_class(fi->type, path);
1349 fi->deps = _get_dependencies(path);
1350 fi->modified_time = mt;
1351 fi->import_modified_time = 0;
1352 fi->import_md5 = "";
1353 fi->import_dest_paths = Vector<String>();
1354 fi->import_valid = true;
1355
1356 // Files in dep_update_list are forced for rescan to update dependencies. They don't need other updates.
1357 if (!dep_update_list.has(path)) {
1358 if (ClassDB::is_parent_class(fi->type, SNAME("Script"))) {
1359 _queue_update_script_class(path, ScriptClassInfoUpdate::from_file_info(fi));
1360 }
1361 if (fi->type == SNAME("PackedScene")) {
1362 _queue_update_scene_groups(path);
1363 }
1364 }
1365 }
1366
1367 if (ResourceLoader::should_create_uid_file(path)) {
1368 // Create a UID file and new UID, if it's invalid.
1369 Ref<FileAccess> f = FileAccess::open(path + ".uid", FileAccess::WRITE);
1370 if (f.is_valid()) {
1371 if (fi->uid == ResourceUID::INVALID_ID) {
1372 fi->uid = ResourceUID::get_singleton()->create_id_for_path(path);
1373 } else {
1374 WARN_PRINT(vformat("Missing .uid file for path \"%s\". The file was re-created from cache.", path));
1375 }
1376 f->store_line(ResourceUID::get_singleton()->id_to_text(fi->uid));
1377 }
1378 }
1379 }
1380
1381 if (fi->uid != ResourceUID::INVALID_ID) {
1382 if (ResourceUID::get_singleton()->has_id(fi->uid)) {
1383 // Restrict UID dupe warning to first-scan since we know there are no file moves going on yet.
1384 if (first_scan) {
1385 // Warn if we detect files with duplicate UIDs.
1386 const String other_path = ResourceUID::get_singleton()->get_id_path(fi->uid);
1387 if (other_path != path) {
1388 WARN_PRINT(vformat("UID duplicate detected between %s and %s.", path, other_path));
1389 }
1390 }
1391 ResourceUID::get_singleton()->set_id(fi->uid, path);
1392 } else {
1393 ResourceUID::get_singleton()->add_id(fi->uid, path);
1394 }
1395 }
1396
1397 p_progress.increment();
1398 }
1399 }
1400
1401 void EditorFileSystem::_process_removed_files(const HashSet<String> &p_processed_files) {
1402 for (const KeyValue<String, EditorFileSystem::FileCache> &kv : file_cache) {
1403 if (!p_processed_files.has(kv.key)) {
1404 if (ClassDB::is_parent_class(kv.value.type, SNAME("Script")) || ClassDB::is_parent_class(kv.value.type, SNAME("PackedScene"))) {
1405 // A script has been removed from disk since the last startup. The documentation needs to be updated.
1406 // There's no need to add the path in update_script_paths since that is exclusively for updating global class names,
1407 // which is handled in _first_scan_filesystem before the full scan to ensure plugins and autoloads can be created.
1408 MutexLock update_script_lock(update_script_mutex);
1409 update_script_paths_documentation.insert(kv.key);
1410 }
1411 }
1412 }
1413 }
1414
1415 void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, ScanProgress &p_progress, bool p_recursive) {
1416 uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path());
1417
1418 bool updated_dir = false;
1419 String cd = p_dir->get_path();
1420 int diff_nb_files = 0;
1421
1422 if (current_mtime != p_dir->modified_time || using_fat32_or_exfat) {
1423 updated_dir = true;
1424 p_dir->modified_time = current_mtime;
1425 //ooooops, dir changed, see what's going on
1426
1427 //first mark everything as verified
1428
1429 for (int i = 0; i < p_dir->files.size(); i++) {
1430 p_dir->files[i]->verified = false;
1431 }
1432
1433 for (int i = 0; i < p_dir->subdirs.size(); i++) {
1434 p_dir->get_subdir(i)->verified = false;
1435 }
1436
1437 diff_nb_files -= p_dir->files.size();
1438
1439 //then scan files and directories and check what's different
1440
1441 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1442
1443 Error ret = da->change_dir(cd);
1444 ERR_FAIL_COND_MSG(ret != OK, "Cannot change to '" + cd + "' folder.");
1445
1446 da->list_dir_begin();
1447 while (true) {
1448 String f = da->get_next();
1449 if (f.is_empty()) {
1450 break;
1451 }
1452
1453 if (da->current_is_hidden()) {
1454 continue;
1455 }
1456
1457 if (da->current_is_dir()) {
1458 if (f.begins_with(".")) { // Ignore special and . / ..
1459 continue;
1460 }
1461
1462 int idx = p_dir->find_dir_index(f);
1463 if (idx == -1) {
1464 String dir_path = cd.path_join(f);
1465 if (_should_skip_directory(dir_path)) {
1466 continue;
1467 }
1468
1469 ScannedDirectory sd;
1470 sd.name = f;
1471 sd.full_path = dir_path;
1472
1473 EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
1474 efd->parent = p_dir;
1475 efd->name = f;
1476
1477 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1478 d->change_dir(dir_path);
1479 int nb_files_dir = _scan_new_dir(&sd, d);
1480 p_progress.hi += nb_files_dir;
1481 diff_nb_files += nb_files_dir;
1482 _process_file_system(&sd, efd, p_progress, nullptr);
1483
1484 ItemAction ia;
1485 ia.action = ItemAction::ACTION_DIR_ADD;
1486 ia.dir = p_dir;
1487 ia.file = f;
1488 ia.new_dir = efd;
1489 scan_actions.push_back(ia);
1490 } else {
1491 p_dir->subdirs[idx]->verified = true;
1492 }
1493
1494 } else {
1495 String ext = f.get_extension().to_lower();
1496 if (!valid_extensions.has(ext)) {
1497 continue; //invalid
1498 }
1499
1500 int idx = p_dir->find_file_index(f);
1501
1502 if (idx == -1) {
1503 //never seen this file, add actition to add it
1504 EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
1505 fi->file = f;
1506
1507 String path = cd.path_join(fi->file);
1508 fi->modified_time = FileAccess::get_modified_time(path);
1509 fi->import_modified_time = 0;
1510 fi->import_md5 = "";
1511 fi->import_dest_paths = Vector<String>();
1512 fi->type = ResourceLoader::get_resource_type(path);
1513 fi->resource_script_class = ResourceLoader::get_resource_script_class(path);
1514 if (fi->type == "" && textfile_extensions.has(ext)) {
1515 fi->type = "TextFile";
1516 }
1517 if (fi->type == "" && other_file_extensions.has(ext)) {
1518 fi->type = "OtherFile";
1519 }
1520 fi->class_info = _get_global_script_class(fi->type, path);
1521 fi->import_valid = (fi->type == "TextFile" || fi->type == "OtherFile") ? true : ResourceLoader::is_import_valid(path);
1522 fi->import_group_file = ResourceLoader::get_import_group_file(path);
1523
1524 {
1525 ItemAction ia;
1526 ia.action = ItemAction::ACTION_FILE_ADD;
1527 ia.dir = p_dir;
1528 ia.file = f;
1529 ia.new_file = fi;
1530 scan_actions.push_back(ia);
1531 }
1532
1533 if (_can_import_file(f)) {
1534 //if it can be imported, and it was added, it needs to be reimported
1535 ItemAction ia;
1536 ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
1537 ia.dir = p_dir;
1538 ia.file = f;
1539 scan_actions.push_back(ia);
1540 }
1541 diff_nb_files++;
1542 } else {
1543 p_dir->files[idx]->verified = true;
1544 }
1545 }
1546 }
1547
1548 da->list_dir_end();
1549 }
1550
1551 for (int i = 0; i < p_dir->files.size(); i++) {
1552 if (updated_dir && !p_dir->files[i]->verified) {
1553 //this file was removed, add action to remove it
1554 ItemAction ia;
1555 ia.action = ItemAction::ACTION_FILE_REMOVE;
1556 ia.dir = p_dir;
1557 ia.file = p_dir->files[i]->file;
1558 scan_actions.push_back(ia);
1559 diff_nb_files--;
1560 continue;
1561 }
1562
1563 String path = cd.path_join(p_dir->files[i]->file);
1564
1565 if (_can_import_file(p_dir->files[i]->file)) {
1566 // Check here if file must be imported or not.
1567 // Same logic as in _process_file_system, the last modifications dates
1568 // needs to be trusted to prevent reading all the .import files and the md5
1569 // each time the user switch back to Godot.
1570 uint64_t mt = FileAccess::get_modified_time(path);
1571 uint64_t import_mt = FileAccess::get_modified_time(path + ".import");
1572 if (_is_test_for_reimport_needed(path, p_dir->files[i]->modified_time, mt, p_dir->files[i]->import_modified_time, import_mt, p_dir->files[i]->import_dest_paths)) {
1573 ItemAction ia;
1574 ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT;
1575 ia.dir = p_dir;
1576 ia.file = p_dir->files[i]->file;
1577 scan_actions.push_back(ia);
1578 }
1579 } else {
1580 uint64_t mt = FileAccess::get_modified_time(path);
1581
1582 if (mt != p_dir->files[i]->modified_time) {
1583 p_dir->files[i]->modified_time = mt; //save new time, but test for reload
1584
1585 ItemAction ia;
1586 ia.action = ItemAction::ACTION_FILE_RELOAD;
1587 ia.dir = p_dir;
1588 ia.file = p_dir->files[i]->file;
1589 scan_actions.push_back(ia);
1590 }
1591 }
1592
1593 p_progress.increment();
1594 }
1595
1596 for (int i = 0; i < p_dir->subdirs.size(); i++) {
1597 if ((updated_dir && !p_dir->subdirs[i]->verified) || _should_skip_directory(p_dir->subdirs[i]->get_path())) {
1598 // Add all the files of the folder to be sure _update_scan_actions process the removed files
1599 // for global class names.
1600 diff_nb_files += _insert_actions_delete_files_directory(p_dir->subdirs[i]);
1601
1602 //this directory was removed or ignored, add action to remove it
1603 ItemAction ia;
1604 ia.action = ItemAction::ACTION_DIR_REMOVE;
1605 ia.dir = p_dir->subdirs[i];
1606 scan_actions.push_back(ia);
1607 continue;
1608 }
1609 if (p_recursive) {
1610 _scan_fs_changes(p_dir->get_subdir(i), p_progress);
1611 }
1612 }
1613
1614 nb_files_total = MAX(nb_files_total + diff_nb_files, 0);
1615 }
1616
1617 void EditorFileSystem::_delete_internal_files(const String &p_file) {
1618 if (FileAccess::exists(p_file + ".import")) {
1619 List<String> paths;
1620 ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths);
1621 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1622 for (const String &E : paths) {
1623 da->remove(E);
1624 }
1625 da->remove(p_file + ".import");
1626 }
1627 if (FileAccess::exists(p_file + ".uid")) {
1628 DirAccess::remove_absolute(p_file + ".uid");
1629 }
1630 }
1631
1632 int EditorFileSystem::_insert_actions_delete_files_directory(EditorFileSystemDirectory *p_dir) {
1633 int nb_files = 0;
1634 for (EditorFileSystemDirectory::FileInfo *fi : p_dir->files) {
1635 ItemAction ia;
1636 ia.action = ItemAction::ACTION_FILE_REMOVE;
1637 ia.dir = p_dir;
1638 ia.file = fi->file;
1639 scan_actions.push_back(ia);
1640 nb_files++;
1641 }
1642
1643 for (EditorFileSystemDirectory *sub_dir : p_dir->subdirs) {
1644 nb_files += _insert_actions_delete_files_directory(sub_dir);
1645 }
1646
1647 return nb_files;
1648 }
1649
1650 void EditorFileSystem::_thread_func_sources(void *_userdata) {
1651 EditorFileSystem *efs = (EditorFileSystem *)_userdata;
1652 if (efs->filesystem) {
1653 EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
1654 ScanProgress sp;
1655 sp.progress = &pr;
1656 sp.hi = efs->nb_files_total;
1657 efs->_scan_fs_changes(efs->filesystem, sp);
1658 }
1659 efs->scanning_changes_done.set();
1660 }
1661
1662 bool EditorFileSystem::_remove_invalid_global_class_names(const HashSet<String> &p_existing_class_names) {
1663 LocalVector<StringName> global_classes;
1664 bool must_save = false;
1665 ScriptServer::get_global_class_list(global_classes);
1666 for (const StringName &class_name : global_classes) {
1667 if (!p_existing_class_names.has(class_name)) {
1668 ScriptServer::remove_global_class(class_name);
1669 must_save = true;
1670 }
1671 }
1672 return must_save;
1673 }
1674
1675 String EditorFileSystem::_get_file_by_class_name(EditorFileSystemDirectory *p_dir, const String &p_class_name, EditorFileSystemDirectory::FileInfo *&r_file_info) {
1676 for (EditorFileSystemDirectory::FileInfo *fi : p_dir->files) {
1677 if (fi->class_info.name == p_class_name) {
1678 r_file_info = fi;
1679 return p_dir->get_path().path_join(fi->file);
1680 }
1681 }
1682
1683 for (EditorFileSystemDirectory *sub_dir : p_dir->subdirs) {
1684 String file = _get_file_by_class_name(sub_dir, p_class_name, r_file_info);
1685 if (!file.is_empty()) {
1686 return file;
1687 }
1688 }
1689 r_file_info = nullptr;
1690 return "";
1691 }
1692
1693 void EditorFileSystem::scan_changes() {
1694 if (first_scan || // Prevent a premature changes scan from inhibiting the first full scan
1695 scanning || scanning_changes || thread.is_started()) {
1696 scan_changes_pending = true;
1697 set_process(true);
1698 return;
1699 }
1700
1701 _update_extensions();
1702 sources_changed.clear();
1703 scanning_changes = true;
1704 scanning_changes_done.clear();
1705
1706 if (!use_threads) {
1707 if (filesystem) {
1708 EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
1709 ScanProgress sp;
1710 sp.progress = &pr;
1711 sp.hi = nb_files_total;
1712 scan_total = 0;
1713 _scan_fs_changes(filesystem, sp);
1714 if (_update_scan_actions()) {
1715 emit_signal(SNAME("filesystem_changed"));
1716 }
1717 }
1718 scanning_changes = false;
1719 scanning_changes_done.set();
1720 emit_signal(SNAME("sources_changed"), sources_changed.size() > 0);
1721 } else {
1722 ERR_FAIL_COND(thread_sources.is_started());
1723 set_process(true);
1724 scan_total = 0;
1725 Thread::Settings s;
1726 s.priority = Thread::PRIORITY_LOW;
1727 thread_sources.start(_thread_func_sources, this, s);
1728 }
1729 }
1730
1731 void EditorFileSystem::_notification(int p_what) {
1732 switch (p_what) {
1733 case NOTIFICATION_EXIT_TREE: {
1734 Thread &active_thread = thread.is_started() ? thread : thread_sources;
1735 if (use_threads && active_thread.is_started()) {
1736 while (scanning) {
1737 OS::get_singleton()->delay_usec(1000);
1738 }
1739 active_thread.wait_to_finish();
1740 WARN_PRINT("Scan thread aborted...");
1741 set_process(false);
1742 }
1743
1744 if (filesystem) {
1745 memdelete(filesystem);
1746 }
1747 if (new_filesystem) {
1748 memdelete(new_filesystem);
1749 }
1750 filesystem = nullptr;
1751 new_filesystem = nullptr;
1752 } break;
1753
1754 case NOTIFICATION_PROCESS: {
1755 if (use_threads) {
1756 /** This hack exists because of the EditorProgress nature
1757 * of processing events recursively. This needs to be rewritten
1758 * at some point entirely, but in the meantime the following
1759 * hack prevents deadlock on import.
1760 */
1761
1762 static bool prevent_recursive_process_hack = false;
1763 if (prevent_recursive_process_hack) {
1764 break;
1765 }
1766
1767 prevent_recursive_process_hack = true;
1768
1769 bool done_importing = false;
1770
1771 if (scanning_changes) {
1772 if (scanning_changes_done.is_set()) {
1773 set_process(false);
1774
1775 if (thread_sources.is_started()) {
1776 thread_sources.wait_to_finish();
1777 }
1778 bool changed = _update_scan_actions();
1779 // Set first_scan to false before the signals so the function doing_first_scan can return false
1780 // in editor_node to start the export if needed.
1781 first_scan = false;
1782 scanning_changes = false;
1783 done_importing = true;
1784 ResourceImporter::load_on_startup = nullptr;
1785 if (changed) {
1786 emit_signal(SNAME("filesystem_changed"));
1787 }
1788 emit_signal(SNAME("sources_changed"), sources_changed.size() > 0);
1789 }
1790 } else if (!scanning && thread.is_started()) {
1791 set_process(false);
1792
1793 if (filesystem) {
1794 memdelete(filesystem);
1795 }
1796 filesystem = new_filesystem;
1797 new_filesystem = nullptr;
1798 thread.wait_to_finish();
1799 _update_scan_actions();
1800 // Update all icons so they are loaded for the FileSystemDock.
1801 _update_files_icon_path();
1802 // Set first_scan to false before the signals so the function doing_first_scan can return false
1803 // in editor_node to start the export if needed.
1804 first_scan = false;
1805 ResourceImporter::load_on_startup = nullptr;
1806 emit_signal(SNAME("filesystem_changed"));
1807 emit_signal(SNAME("sources_changed"), sources_changed.size() > 0);
1808 }
1809
1810 if (done_importing && scan_changes_pending) {
1811 scan_changes_pending = false;
1812 scan_changes();
1813 }
1814
1815 prevent_recursive_process_hack = false;
1816 }
1817 } break;
1818 }
1819 }
1820
1821 bool EditorFileSystem::is_scanning() const {
1822 return scanning || scanning_changes || first_scan;
1823 }
1824
1825 float EditorFileSystem::get_scanning_progress() const {
1826 return scan_total;
1827 }
1828
1829 EditorFileSystemDirectory *EditorFileSystem::get_filesystem() {
1830 return filesystem;
1831 }
1832
1833 void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, Ref<FileAccess> p_file) {
1834 if (!p_dir) {
1835 return; //none
1836 }
1837 p_file->store_line("::" + p_dir->get_path() + "::" + String::num_int64(p_dir->modified_time));
1838
1839 for (int i = 0; i < p_dir->files.size(); i++) {
1840 const EditorFileSystemDirectory::FileInfo *file_info = p_dir->files[i];
1841 if (!file_info->import_group_file.is_empty()) {
1842 group_file_cache.insert(file_info->import_group_file);
1843 }
1844
1845 String type = file_info->type;
1846 if (file_info->resource_script_class) {
1847 type += "/" + String(file_info->resource_script_class);
1848 }
1849
1850 PackedStringArray cache_string;
1851 cache_string.append(file_info->file);
1852 cache_string.append(type);
1853 cache_string.append(itos(file_info->uid));
1854 cache_string.append(itos(file_info->modified_time));
1855 cache_string.append(itos(file_info->import_modified_time));
1856 cache_string.append(itos(file_info->import_valid));
1857 cache_string.append(file_info->import_group_file);
1858 cache_string.append(String("<>").join({ file_info->class_info.name, file_info->class_info.extends, file_info->class_info.icon_path, itos(file_info->class_info.is_abstract), itos(file_info->class_info.is_tool), file_info->import_md5, String("<*>").join(file_info->import_dest_paths) }));
1859 cache_string.append(String("<>").join(file_info->deps));
1860
1861 p_file->store_line(String("::").join(cache_string));
1862 }
1863
1864 for (int i = 0; i < p_dir->subdirs.size(); i++) {
1865 _save_filesystem_cache(p_dir->subdirs[i], p_file);
1866 }
1867 }
1868
1869 bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const {
1870 //todo make faster
1871
1872 if (!filesystem || scanning) {
1873 return false;
1874 }
1875
1876 String f = ProjectSettings::get_singleton()->localize_path(p_file);
1877
1878 // Note: Only checks if base directory is case sensitive.
1879 Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1880 bool fs_case_sensitive = dir->is_case_sensitive("res://");
1881
1882 if (!f.begins_with("res://")) {
1883 return false;
1884 }
1885 f = f.substr(6);
1886 f = f.replace_char('\\', '/');
1887
1888 Vector<String> path = f.split("/");
1889
1890 if (path.is_empty()) {
1891 return false;
1892 }
1893 String file = path[path.size() - 1];
1894 path.resize(path.size() - 1);
1895
1896 EditorFileSystemDirectory *fs = filesystem;
1897
1898 for (int i = 0; i < path.size(); i++) {
1899 if (path[i].begins_with(".")) {
1900 return false;
1901 }
1902
1903 int idx = -1;
1904 for (int j = 0; j < fs->get_subdir_count(); j++) {
1905 if (fs_case_sensitive) {
1906 if (fs->get_subdir(j)->get_name() == path[i]) {
1907 idx = j;
1908 break;
1909 }
1910 } else {
1911 if (fs->get_subdir(j)->get_name().to_lower() == path[i].to_lower()) {
1912 idx = j;
1913 break;
1914 }
1915 }
1916 }
1917
1918 if (idx == -1) {
1919 // Only create a missing directory in memory when it exists on disk.
1920 if (!dir->dir_exists(fs->get_path().path_join(path[i]))) {
1921 return false;
1922 }
1923 EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory);
1924
1925 efsd->name = path[i];
1926 efsd->parent = fs;
1927
1928 int idx2 = 0;
1929 for (int j = 0; j < fs->get_subdir_count(); j++) {
1930 if (efsd->name.filenocasecmp_to(fs->get_subdir(j)->get_name()) < 0) {
1931 break;
1932 }
1933 idx2++;
1934 }
1935
1936 if (idx2 == fs->get_subdir_count()) {
1937 fs->subdirs.push_back(efsd);
1938 } else {
1939 fs->subdirs.insert(idx2, efsd);
1940 }
1941 fs = efsd;
1942 } else {
1943 fs = fs->get_subdir(idx);
1944 }
1945 }
1946
1947 int cpos = -1;
1948 for (int i = 0; i < fs->files.size(); i++) {
1949 if (fs_case_sensitive) {
1950 if (fs->files[i]->file == file) {
1951 cpos = i;
1952 break;
1953 }
1954 } else {
1955 if (fs->files[i]->file.to_lower() == file.to_lower()) {
1956 cpos = i;
1957 break;
1958 }
1959 }
1960 }
1961
1962 r_file_pos = cpos;
1963 *r_d = fs;
1964
1965 return cpos != -1;
1966 }
1967
1968 String EditorFileSystem::get_file_type(const String &p_file) const {
1969 EditorFileSystemDirectory *fs = nullptr;
1970 int cpos = -1;
1971
1972 if (!_find_file(p_file, &fs, cpos)) {
1973 return "";
1974 }
1975
1976 return fs->files[cpos]->type;
1977 }
1978
1979 EditorFileSystemDirectory *EditorFileSystem::find_file(const String &p_file, int *r_index) const {
1980 if (!filesystem || scanning) {
1981 return nullptr;
1982 }
1983
1984 EditorFileSystemDirectory *fs = nullptr;
1985 int cpos = -1;
1986 if (!_find_file(p_file, &fs, cpos)) {
1987 return nullptr;
1988 }
1989
1990 if (r_index) {
1991 *r_index = cpos;
1992 }
1993
1994 return fs;
1995 }
1996
1997 ResourceUID::ID EditorFileSystem::get_file_uid(const String &p_path) const {
1998 int file_idx;
1999 EditorFileSystemDirectory *directory = find_file(p_path, &file_idx);
2000
2001 if (!directory) {
2002 return ResourceUID::INVALID_ID;
2003 }
2004 return directory->files[file_idx]->uid;
2005 }
2006
2007 EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p_path) {
2008 if (!filesystem || scanning) {
2009 return nullptr;
2010 }
2011
2012 String f = ProjectSettings::get_singleton()->localize_path(p_path);
2013
2014 if (!f.begins_with("res://")) {
2015 return nullptr;
2016 }
2017
2018 f = f.substr(6);
2019 f = f.replace_char('\\', '/');
2020 if (f.is_empty()) {
2021 return filesystem;
2022 }
2023
2024 if (f.ends_with("/")) {
2025 f = f.substr(0, f.length() - 1);
2026 }
2027
2028 Vector<String> path = f.split("/");
2029
2030 if (path.is_empty()) {
2031 return nullptr;
2032 }
2033
2034 EditorFileSystemDirectory *fs = filesystem;
2035
2036 for (int i = 0; i < path.size(); i++) {
2037 int idx = -1;
2038 for (int j = 0; j < fs->get_subdir_count(); j++) {
2039 if (fs->get_subdir(j)->get_name() == path[i]) {
2040 idx = j;
2041 break;
2042 }
2043 }
2044
2045 if (idx == -1) {
2046 return nullptr;
2047 } else {
2048 fs = fs->get_subdir(idx);
2049 }
2050 }
2051
2052 return fs;
2053 }
2054
2055 void EditorFileSystem::_save_late_updated_files() {
2056 //files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file
2057 String fscache = EditorPaths::get_singleton()->get_project_settings_dir().path_join("filesystem_update4");
2058 Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::WRITE);
2059 ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + fscache + "'. Check user write permissions.");
2060 for (const String &E : late_update_files) {
2061 f->store_line(E);
2062 }
2063 }
2064
2065 Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) {
2066 // Avoid error spam on first opening of a not yet imported project by treating the following situation
2067 // as a benign one, not letting the file open error happen: the resource is of an importable type but
2068 // it has not been imported yet.
2069 if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
2070 const String &internal_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
2071 if (!internal_path.is_empty() && !FileAccess::exists(internal_path)) { // If path is empty (error), keep the code flow to the error.
2072 return Vector<String>();
2073 }
2074 }
2075
2076 List<String> deps;
2077 ResourceLoader::get_dependencies(p_path, &deps);
2078
2079 Vector<String> ret;
2080 for (const String &E : deps) {
2081 ret.push_back(E);
2082 }
2083
2084 return ret;
2085 }
2086
2087 EditorFileSystem::ScriptClassInfo EditorFileSystem::_get_global_script_class(const String &p_type, const String &p_path) const {
2088 ScriptClassInfo info;
2089 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
2090 if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) {
2091 info.name = ScriptServer::get_language(i)->get_global_class_name(p_path, &info.extends, &info.icon_path, &info.is_abstract, &info.is_tool);
2092 break;
2093 }
2094 }
2095 return info;
2096 }
2097
2098 void EditorFileSystem::_update_file_icon_path(EditorFileSystemDirectory::FileInfo *file_info) {
2099 String icon_path;
2100 if (file_info->resource_script_class != StringName()) {
2101 icon_path = EditorNode::get_editor_data().script_class_get_icon_path(file_info->resource_script_class);
2102 } else if (file_info->class_info.icon_path.is_empty() && !file_info->deps.is_empty()) {
2103 const String &script_dep = file_info->deps[0]; // Assuming the first dependency is a script.
2104 const String &script_path = script_dep.contains("::") ? script_dep.get_slice("::", 2) : script_dep;
2105 if (!script_path.is_empty()) {
2106 String *cached = file_icon_cache.getptr(script_path);
2107 if (cached) {
2108 icon_path = *cached;
2109 } else {
2110 if (ClassDB::is_parent_class(ResourceLoader::get_resource_type(script_path), SNAME("Script"))) {
2111 int script_file;
2112 EditorFileSystemDirectory *efsd = find_file(script_path, &script_file);
2113 if (efsd) {
2114 icon_path = efsd->files[script_file]->class_info.icon_path;
2115 }
2116 }
2117 file_icon_cache.insert(script_path, icon_path);
2118 }
2119 }
2120 }
2121
2122 if (icon_path.is_empty() && !file_info->type.is_empty()) {
2123 Ref<Texture2D> icon = EditorNode::get_singleton()->get_class_icon(file_info->type);
2124 if (icon.is_valid()) {
2125 icon_path = icon->get_path();
2126 }
2127 }
2128
2129 file_info->class_info.icon_path = icon_path;
2130 }
2131
2132 void EditorFileSystem::_update_files_icon_path(EditorFileSystemDirectory *edp) {
2133 if (!edp) {
2134 edp = filesystem;
2135 file_icon_cache.clear();
2136 }
2137 for (EditorFileSystemDirectory *sub_dir : edp->subdirs) {
2138 _update_files_icon_path(sub_dir);
2139 }
2140 for (EditorFileSystemDirectory::FileInfo *fi : edp->files) {
2141 _update_file_icon_path(fi);
2142 }
2143 }
2144
2145 void EditorFileSystem::_update_script_classes() {
2146 if (update_script_paths.is_empty()) {
2147 // Ensure the global class file is always present; it's essential for exports to work.
2148 if (!FileAccess::exists(ProjectSettings::get_singleton()->get_global_class_list_path())) {
2149 ScriptServer::save_global_classes();
2150 }
2151 return;
2152 }
2153
2154 {
2155 MutexLock update_script_lock(update_script_mutex);
2156
2157 EditorProgress *ep = nullptr;
2158 if (update_script_paths.size() > 1) {
2159 if (MessageQueue::get_singleton()->is_flushing()) {
2160 // Use background progress when message queue is flushing.
2161 ep = memnew(EditorProgress("update_scripts_classes", TTR("Registering global classes..."), update_script_paths.size(), false, true));
2162 } else {
2163 ep = memnew(EditorProgress("update_scripts_classes", TTR("Registering global classes..."), update_script_paths.size()));
2164 }
2165 }
2166
2167 int step_count = 0;
2168 for (const KeyValue<String, ScriptClassInfoUpdate> &E : update_script_paths) {
2169 _register_global_class_script(E.key, E.key, E.value);
2170 if (ep) {
2171 ep->step(E.value.name, step_count++, false);
2172 }
2173 }
2174
2175 memdelete_notnull(ep);
2176
2177 update_script_paths.clear();
2178 }
2179
2180 EditorNode::get_editor_data().script_class_save_global_classes();
2181
2182 emit_signal("script_classes_updated");
2183
2184 // Rescan custom loaders and savers.
2185 // Doing the following here because the `filesystem_changed` signal fires multiple times and isn't always followed by script classes update.
2186 // So I thought it's better to do this when script classes really get updated
2187 ResourceLoader::remove_custom_loaders();
2188 ResourceLoader::add_custom_loaders();
2189 ResourceSaver::remove_custom_savers();
2190 ResourceSaver::add_custom_savers();
2191 }
2192
2193 void EditorFileSystem::_update_script_documentation() {
2194 if (update_script_paths_documentation.is_empty()) {
2195 return;
2196 }
2197
2198 MutexLock update_script_lock(update_script_mutex);
2199
2200 EditorProgress *ep = nullptr;
2201 if (update_script_paths_documentation.size() > 1) {
2202 if (MessageQueue::get_singleton()->is_flushing()) {
2203 // Use background progress when message queue is flushing.
2204 ep = memnew(EditorProgress("update_script_paths_documentation", TTR("Updating scripts documentation"), update_script_paths_documentation.size(), false, true));
2205 } else {
2206 ep = memnew(EditorProgress("update_script_paths_documentation", TTR("Updating scripts documentation"), update_script_paths_documentation.size()));
2207 }
2208 }
2209
2210 int step_count = 0;
2211 for (const String &path : update_script_paths_documentation) {
2212 int index = -1;
2213 EditorFileSystemDirectory *efd = find_file(path, &index);
2214
2215 if (!efd || index < 0) {
2216 // The file was removed
2217 EditorHelp::remove_script_doc_by_path(path);
2218 continue;
2219 }
2220
2221 if (path.ends_with(".tscn")) {
2222 Ref<PackedScene> packed_scene = ResourceLoader::load(path);
2223 if (packed_scene.is_valid()) {
2224 Ref<SceneState> state = packed_scene->get_state();
2225 if (state.is_valid()) {
2226 Vector<Ref<Resource>> sub_resources = state->get_sub_resources();
2227 for (Ref<Resource> sub_resource : sub_resources) {
2228 Ref<Script> scr = sub_resource;
2229 if (scr.is_valid()) {
2230 for (const DocData::ClassDoc &cd : scr->get_documentation()) {
2231 EditorHelp::add_doc(cd);
2232 if (!first_scan) {
2233 // Update the documentation in the Script Editor if it is open.
2234 ScriptEditor::get_singleton()->update_doc(cd.name);
2235 }
2236 }
2237 }
2238 }
2239 }
2240 }
2241 continue;
2242 }
2243
2244 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
2245 ScriptLanguage *lang = ScriptServer::get_language(i);
2246 if (lang->supports_documentation() && efd->files[index]->type == lang->get_type()) {
2247 bool should_reload_script = _should_reload_script(path);
2248 Ref<Script> scr = ResourceLoader::load(path);
2249 if (scr.is_null()) {
2250 continue;
2251 }
2252 if (should_reload_script) {
2253 // Reloading the script from disk. Otherwise, the ResourceLoader::load will
2254 // return the last loaded version of the script (without the modifications).
2255 scr->reload_from_file();
2256 }
2257 for (const DocData::ClassDoc &cd : scr->get_documentation()) {
2258 EditorHelp::add_doc(cd);
2259 if (!first_scan) {
2260 // Update the documentation in the Script Editor if it is open.
2261 ScriptEditor::get_singleton()->update_doc(cd.name);
2262 }
2263 }
2264 }
2265 }
2266
2267 if (ep) {
2268 ep->step(efd->files[index]->file, step_count++, false);
2269 }
2270 }
2271
2272 memdelete_notnull(ep);
2273
2274 update_script_paths_documentation.clear();
2275 }
2276
2277 bool EditorFileSystem::_should_reload_script(const String &p_path) {
2278 if (first_scan) {
2279 return false;
2280 }
2281
2282 Ref<Script> scr = ResourceCache::get_ref(p_path);
2283 if (scr.is_null()) {
2284 // Not a script or not already loaded.
2285 return false;
2286 }
2287
2288 // Scripts are reloaded via the script editor if they are currently opened.
2289 if (ScriptEditor::get_singleton()->get_open_scripts().has(scr)) {
2290 return false;
2291 }
2292
2293 return true;
2294 }
2295
2296 void EditorFileSystem::_process_update_pending() {
2297 _update_script_classes();
2298 // Parse documentation second, as it requires the class names to be loaded
2299 // because _update_script_documentation loads the scripts completely.
2300 if (!EditorNode::is_cmdline_mode()) {
2301 _update_script_documentation();
2302 _update_pending_scene_groups();
2303 }
2304 }
2305
2306 void EditorFileSystem::_queue_update_script_class(const String &p_path, const ScriptClassInfoUpdate &p_script_update) {
2307 MutexLock update_script_lock(update_script_mutex);
2308
2309 update_script_paths.insert(p_path, p_script_update);
2310 update_script_paths_documentation.insert(p_path);
2311 }
2312
2313 void EditorFileSystem::_update_scene_groups() {
2314 if (update_scene_paths.is_empty()) {
2315 return;
2316 }
2317
2318 EditorProgress *ep = nullptr;
2319 if (update_scene_paths.size() > 20) {
2320 ep = memnew(EditorProgress("update_scene_groups", TTR("Updating Scene Groups"), update_scene_paths.size()));
2321 }
2322 int step_count = 0;
2323
2324 {
2325 MutexLock update_scene_lock(update_scene_mutex);
2326 for (const String &path : update_scene_paths) {
2327 ProjectSettings::get_singleton()->remove_scene_groups_cache(path);
2328
2329 int index = -1;
2330 EditorFileSystemDirectory *efd = find_file(path, &index);
2331
2332 if (!efd || index < 0) {
2333 // The file was removed.
2334 continue;
2335 }
2336
2337 const HashSet<StringName> scene_groups = PackedScene::get_scene_groups(path);
2338 if (!scene_groups.is_empty()) {
2339 ProjectSettings::get_singleton()->add_scene_groups_cache(path, scene_groups);
2340 }
2341
2342 if (ep) {
2343 ep->step(efd->files[index]->file, step_count++, false);
2344 }
2345 }
2346
2347 memdelete_notnull(ep);
2348 update_scene_paths.clear();
2349 }
2350
2351 ProjectSettings::get_singleton()->save_scene_groups_cache();
2352 }
2353
2354 void EditorFileSystem::_update_pending_scene_groups() {
2355 if (!FileAccess::exists(ProjectSettings::get_singleton()->get_scene_groups_cache_path())) {
2356 _get_all_scenes(get_filesystem(), update_scene_paths);
2357 _update_scene_groups();
2358 } else if (!update_scene_paths.is_empty()) {
2359 _update_scene_groups();
2360 }
2361 }
2362
2363 void EditorFileSystem::_queue_update_scene_groups(const String &p_path) {
2364 MutexLock update_scene_lock(update_scene_mutex);
2365 update_scene_paths.insert(p_path);
2366 }
2367
2368 void EditorFileSystem::_get_all_scenes(EditorFileSystemDirectory *p_dir, HashSet<String> &r_list) {
2369 for (int i = 0; i < p_dir->get_file_count(); i++) {
2370 if (p_dir->get_file_type(i) == SNAME("PackedScene")) {
2371 r_list.insert(p_dir->get_file_path(i));
2372 }
2373 }
2374
2375 for (int i = 0; i < p_dir->get_subdir_count(); i++) {
2376 _get_all_scenes(p_dir->get_subdir(i), r_list);
2377 }
2378 }
2379
2380 void EditorFileSystem::update_file(const String &p_file) {
2381 ERR_FAIL_COND(p_file.is_empty());
2382 update_files({ p_file });
2383 }
2384
2385 void EditorFileSystem::update_files(const Vector<String> &p_script_paths) {
2386 bool updated = false;
2387 bool update_files_icon_cache = false;
2388 Vector<EditorFileSystemDirectory::FileInfo *> files_to_update_icon_path;
2389 for (const String &file : p_script_paths) {
2390 ERR_CONTINUE(file.is_empty());
2391 EditorFileSystemDirectory *fs = nullptr;
2392 int cpos = -1;
2393
2394 if (!_find_file(file, &fs, cpos)) {
2395 if (!fs) {
2396 continue;
2397 }
2398 }
2399
2400 if (!FileAccess::exists(file)) {
2401 //was removed
2402 _delete_internal_files(file);
2403 if (cpos != -1) { // Might've never been part of the editor file system (*.* files deleted in Open dialog).
2404 if (fs->files[cpos]->uid != ResourceUID::INVALID_ID) {
2405 if (ResourceUID::get_singleton()->has_id(fs->files[cpos]->uid)) {
2406 ResourceUID::get_singleton()->remove_id(fs->files[cpos]->uid);
2407 }
2408 }
2409 if (ClassDB::is_parent_class(fs->files[cpos]->type, SNAME("Script"))) {
2410 ScriptClassInfoUpdate update;
2411 update.type = fs->files[cpos]->type;
2412 _queue_update_script_class(file, update);
2413 if (!fs->files[cpos]->class_info.icon_path.is_empty()) {
2414 update_files_icon_cache = true;
2415 }
2416 }
2417 if (fs->files[cpos]->type == SNAME("PackedScene")) {
2418 _queue_update_scene_groups(file);
2419 }
2420
2421 memdelete(fs->files[cpos]);
2422 fs->files.remove_at(cpos);
2423 updated = true;
2424 }
2425 } else {
2426 String type = ResourceLoader::get_resource_type(file);
2427 if (type.is_empty() && textfile_extensions.has(file.get_extension())) {
2428 type = "TextFile";
2429 }
2430 if (type.is_empty() && other_file_extensions.has(file.get_extension())) {
2431 type = "OtherFile";
2432 }
2433 String script_class = ResourceLoader::get_resource_script_class(file);
2434
2435 ResourceUID::ID uid = ResourceLoader::get_resource_uid(file);
2436
2437 if (cpos == -1) {
2438 // The file did not exist, it was added.
2439 int idx = 0;
2440 String file_name = file.get_file();
2441
2442 for (int i = 0; i < fs->files.size(); i++) {
2443 if (file.filenocasecmp_to(fs->files[i]->file) < 0) {
2444 break;
2445 }
2446 idx++;
2447 }
2448
2449 EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
2450 fi->file = file_name;
2451 fi->import_modified_time = 0;
2452 fi->import_valid = (type == "TextFile" || type == "OtherFile") ? true : ResourceLoader::is_import_valid(file);
2453 fi->import_md5 = "";
2454 fi->import_dest_paths = Vector<String>();
2455
2456 if (idx == fs->files.size()) {
2457 fs->files.push_back(fi);
2458 } else {
2459 fs->files.insert(idx, fi);
2460 }
2461 cpos = idx;
2462 } else {
2463 //the file exists and it was updated, and was not added in this step.
2464 //this means we must force upon next restart to scan it again, to get proper type and dependencies
2465 late_update_files.insert(file);
2466 _save_late_updated_files(); //files need to be updated in the re-scan
2467 }
2468
2469 EditorFileSystemDirectory::FileInfo *fi = fs->files[cpos];
2470 const String old_script_class_icon_path = fi->class_info.icon_path;
2471 const String old_class_name = fi->class_info.name;
2472 fi->type = type;
2473 fi->resource_script_class = script_class;
2474 fi->uid = uid;
2475 fi->class_info = _get_global_script_class(type, file);
2476 fi->import_group_file = ResourceLoader::get_import_group_file(file);
2477 fi->modified_time = FileAccess::get_modified_time(file);
2478 fi->deps = _get_dependencies(file);
2479 fi->import_valid = (type == "TextFile" || type == "OtherFile") ? true : ResourceLoader::is_import_valid(file);
2480
2481 if (uid != ResourceUID::INVALID_ID) {
2482 if (ResourceUID::get_singleton()->has_id(uid)) {
2483 ResourceUID::get_singleton()->set_id(uid, file);
2484 } else {
2485 ResourceUID::get_singleton()->add_id(uid, file);
2486 }
2487
2488 ResourceUID::get_singleton()->update_cache();
2489 } else {
2490 if (ResourceLoader::should_create_uid_file(file)) {
2491 Ref<FileAccess> f = FileAccess::open(file + ".uid", FileAccess::WRITE);
2492 if (f.is_valid()) {
2493 const ResourceUID::ID id = ResourceUID::get_singleton()->create_id_for_path(file);
2494 ResourceUID::get_singleton()->add_id(id, file);
2495 f->store_line(ResourceUID::get_singleton()->id_to_text(id));
2496 fi->uid = id;
2497 }
2498 }
2499 }
2500
2501 // Update preview
2502 EditorResourcePreview::get_singleton()->check_for_invalidation(file);
2503
2504 if (ClassDB::is_parent_class(fi->type, SNAME("Script"))) {
2505 _queue_update_script_class(file, ScriptClassInfoUpdate::from_file_info(fi));
2506 }
2507 if (fi->type == SNAME("PackedScene")) {
2508 _queue_update_scene_groups(file);
2509 }
2510
2511 if (ClassDB::is_parent_class(fi->type, SNAME("Resource"))) {
2512 files_to_update_icon_path.push_back(fi);
2513 } else if (old_script_class_icon_path != fi->class_info.icon_path) {
2514 update_files_icon_cache = true;
2515 }
2516
2517 // Restore another script as the global class name if multiple scripts had the same old class name.
2518 if (!old_class_name.is_empty() && fi->class_info.name != old_class_name && ClassDB::is_parent_class(type, SNAME("Script"))) {
2519 EditorFileSystemDirectory::FileInfo *old_fi = nullptr;
2520 String old_file = _get_file_by_class_name(filesystem, old_class_name, old_fi);
2521 if (!old_file.is_empty() && old_fi) {
2522 _queue_update_script_class(old_file, ScriptClassInfoUpdate::from_file_info(old_fi));
2523 }
2524 }
2525 updated = true;
2526 }
2527 }
2528
2529 if (updated) {
2530 if (update_files_icon_cache) {
2531 _update_files_icon_path();
2532 } else {
2533 for (EditorFileSystemDirectory::FileInfo *fi : files_to_update_icon_path) {
2534 _update_file_icon_path(fi);
2535 }
2536 }
2537 if (!is_scanning()) {
2538 _process_update_pending();
2539 }
2540 if (!filesystem_changed_queued) {
2541 filesystem_changed_queued = true;
2542 callable_mp(this, &EditorFileSystem::_notify_filesystem_changed).call_deferred();
2543 }
2544 }
2545 }
2546
2547 void EditorFileSystem::_notify_filesystem_changed() {
2548 emit_signal("filesystem_changed");
2549 filesystem_changed_queued = false;
2550 }
2551
2552 HashSet<String> EditorFileSystem::get_valid_extensions() const {
2553 return valid_extensions;
2554 }
2555
2556 void EditorFileSystem::_register_global_class_script(const String &p_search_path, const String &p_target_path, const ScriptClassInfoUpdate &p_script_update) {
2557 ScriptServer::remove_global_class_by_path(p_search_path); // First remove, just in case it changed
2558
2559 if (p_script_update.name.is_empty()) {
2560 return;
2561 }
2562
2563 String lang;
2564 for (int j = 0; j < ScriptServer::get_language_count(); j++) {
2565 if (ScriptServer::get_language(j)->handles_global_class_type(p_script_update.type)) {
2566 lang = ScriptServer::get_language(j)->get_name();
2567 break;
2568 }
2569 }
2570 if (lang.is_empty()) {
2571 return; // No lang found that can handle this global class
2572 }
2573
2574 ScriptServer::add_global_class(p_script_update.name, p_script_update.extends, lang, p_target_path, p_script_update.is_abstract, p_script_update.is_tool);
2575 EditorNode::get_editor_data().script_class_set_icon_path(p_script_update.name, p_script_update.icon_path);
2576 EditorNode::get_editor_data().script_class_set_name(p_target_path, p_script_update.name);
2577 }
2578
2579 void EditorFileSystem::register_global_class_script(const String &p_search_path, const String &p_target_path) {
2580 int index_file;
2581 EditorFileSystemDirectory *efsd = find_file(p_search_path, &index_file);
2582 if (efsd) {
2583 const EditorFileSystemDirectory::FileInfo *fi = efsd->files[index_file];
2584 EditorFileSystem::get_singleton()->_register_global_class_script(p_search_path, p_target_path, ScriptClassInfoUpdate::from_file_info(fi));
2585 } else {
2586 ScriptServer::remove_global_class_by_path(p_search_path);
2587 }
2588 }
2589
2590 Error EditorFileSystem::_reimport_group(const String &p_group_file, const Vector<String> &p_files) {
2591 String importer_name;
2592
2593 HashMap<String, HashMap<StringName, Variant>> source_file_options;
2594 HashMap<String, ResourceUID::ID> uids;
2595 HashMap<String, String> base_paths;
2596 for (int i = 0; i < p_files.size(); i++) {
2597 Ref<ConfigFile> config;
2598 config.instantiate();
2599 Error err = config->load(p_files[i] + ".import");
2600 ERR_CONTINUE(err != OK);
2601 ERR_CONTINUE(!config->has_section_key("remap", "importer"));
2602 String file_importer_name = config->get_value("remap", "importer");
2603 ERR_CONTINUE(file_importer_name.is_empty());
2604
2605 if (!importer_name.is_empty() && importer_name != file_importer_name) {
2606 EditorNode::get_singleton()->show_warning(vformat(TTR("There are multiple importers for different types pointing to file %s, import aborted"), p_group_file));
2607 ERR_FAIL_V(ERR_FILE_CORRUPT);
2608 }
2609
2610 ResourceUID::ID uid = ResourceUID::INVALID_ID;
2611
2612 if (config->has_section_key("remap", "uid")) {
2613 String uidt = config->get_value("remap", "uid");
2614 uid = ResourceUID::get_singleton()->text_to_id(uidt);
2615 }
2616
2617 uids[p_files[i]] = uid;
2618
2619 source_file_options[p_files[i]] = HashMap<StringName, Variant>();
2620 importer_name = file_importer_name;
2621
2622 if (importer_name == "keep" || importer_name == "skip") {
2623 continue; //do nothing
2624 }
2625
2626 Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
2627 ERR_FAIL_COND_V(importer.is_null(), ERR_FILE_CORRUPT);
2628 List<ResourceImporter::ImportOption> options;
2629 importer->get_import_options(p_files[i], &options);
2630 //set default values
2631 for (const ResourceImporter::ImportOption &E : options) {
2632 source_file_options[p_files[i]][E.option.name] = E.default_value;
2633 }
2634
2635 if (config->has_section("params")) {
2636 Vector<String> sk = config->get_section_keys("params");
2637 for (const String &param : sk) {
2638 Variant value = config->get_value("params", param);
2639 //override with whatever is in file
2640 source_file_options[p_files[i]][param] = value;
2641 }
2642 }
2643
2644 base_paths[p_files[i]] = ResourceFormatImporter::get_singleton()->get_import_base_path(p_files[i]);
2645 }
2646
2647 if (importer_name == "keep" || importer_name == "skip") {
2648 return OK; // (do nothing)
2649 }
2650
2651 ERR_FAIL_COND_V(importer_name.is_empty(), ERR_UNCONFIGURED);
2652
2653 Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
2654
2655 Error err = importer->import_group_file(p_group_file, source_file_options, base_paths);
2656
2657 //all went well, overwrite config files with proper remaps and md5s
2658 for (const KeyValue<String, HashMap<StringName, Variant>> &E : source_file_options) {
2659 const String &file = E.key;
2660 String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file);
2661 Vector<String> dest_paths;
2662 ResourceUID::ID uid = uids[file];
2663 {
2664 Ref<FileAccess> f = FileAccess::open(file + ".import", FileAccess::WRITE);
2665 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'.");
2666
2667 //write manually, as order matters ([remap] has to go first for performance).
2668 f->store_line("[remap]");
2669 f->store_line("");
2670 f->store_line("importer=\"" + importer->get_importer_name() + "\"");
2671 int version = importer->get_format_version();
2672 if (version > 0) {
2673 f->store_line("importer_version=" + itos(version));
2674 }
2675 if (!importer->get_resource_type().is_empty()) {
2676 f->store_line("type=\"" + importer->get_resource_type() + "\"");
2677 }
2678
2679 if (uid == ResourceUID::INVALID_ID) {
2680 uid = ResourceUID::get_singleton()->create_id_for_path(file);
2681 }
2682
2683 f->store_line("uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\""); // Store in readable format.
2684
2685 if (err == OK) {
2686 String path = base_path + "." + importer->get_save_extension();
2687 f->store_line("path=\"" + path + "\"");
2688 dest_paths.push_back(path);
2689 }
2690
2691 f->store_line("group_file=" + Variant(p_group_file).get_construct_string());
2692
2693 if (err == OK) {
2694 f->store_line("valid=true");
2695 } else {
2696 f->store_line("valid=false");
2697 }
2698 f->store_line("[deps]\n");
2699
2700 f->store_line("");
2701
2702 f->store_line("source_file=" + Variant(file).get_construct_string());
2703 if (dest_paths.size()) {
2704 Array dp;
2705 for (int i = 0; i < dest_paths.size(); i++) {
2706 dp.push_back(dest_paths[i]);
2707 }
2708 f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n");
2709 }
2710 f->store_line("[params]");
2711 f->store_line("");
2712
2713 //store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
2714
2715 List<ResourceImporter::ImportOption> options;
2716 importer->get_import_options(file, &options);
2717 //set default values
2718 for (const ResourceImporter::ImportOption &F : options) {
2719 String base = F.option.name;
2720 Variant v = F.default_value;
2721 if (source_file_options[file].has(base)) {
2722 v = source_file_options[file][base];
2723 }
2724 String value;
2725 VariantWriter::write_to_string(v, value);
2726 f->store_line(base + "=" + value);
2727 }
2728 }
2729
2730 // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
2731 {
2732 Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
2733 ERR_FAIL_COND_V_MSG(md5s.is_null(), ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'.");
2734
2735 md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\"");
2736 if (dest_paths.size()) {
2737 md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
2738 }
2739 }
2740
2741 EditorFileSystemDirectory *fs = nullptr;
2742 int cpos = -1;
2743 bool found = _find_file(file, &fs, cpos);
2744 ERR_FAIL_COND_V_MSG(!found, ERR_UNCONFIGURED, vformat("Can't find file '%s' during group reimport.", file));
2745
2746 //update modified times, to avoid reimport
2747 fs->files[cpos]->modified_time = FileAccess::get_modified_time(file);
2748 fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(file + ".import");
2749 fs->files[cpos]->import_md5 = FileAccess::get_md5(file + ".import");
2750 fs->files[cpos]->import_dest_paths = dest_paths;
2751 fs->files[cpos]->deps = _get_dependencies(file);
2752 fs->files[cpos]->uid = uid;
2753 fs->files[cpos]->type = importer->get_resource_type();
2754 if (fs->files[cpos]->type == "" && textfile_extensions.has(file.get_extension())) {
2755 fs->files[cpos]->type = "TextFile";
2756 }
2757 if (fs->files[cpos]->type == "" && other_file_extensions.has(file.get_extension())) {
2758 fs->files[cpos]->type = "OtherFile";
2759 }
2760 fs->files[cpos]->import_valid = err == OK;
2761
2762 if (ResourceUID::get_singleton()->has_id(uid)) {
2763 ResourceUID::get_singleton()->set_id(uid, file);
2764 } else {
2765 ResourceUID::get_singleton()->add_id(uid, file);
2766 }
2767
2768 //if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
2769 //to reload properly
2770 Ref<Resource> r = ResourceCache::get_ref(file);
2771
2772 if (r.is_valid()) {
2773 if (!r->get_import_path().is_empty()) {
2774 String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(file);
2775 r->set_import_path(dst_path);
2776 r->set_import_last_modified_time(0);
2777 }
2778 }
2779
2780 EditorResourcePreview::get_singleton()->check_for_invalidation(file);
2781 }
2782
2783 return err;
2784 }
2785
2786 Error EditorFileSystem::_reimport_file(const String &p_file, const HashMap<StringName, Variant> &p_custom_options, const String &p_custom_importer, Variant *p_generator_parameters, bool p_update_file_system) {
2787 print_verbose(vformat("EditorFileSystem: Importing file: %s", p_file));
2788 uint64_t start_time = OS::get_singleton()->get_ticks_msec();
2789
2790 EditorFileSystemDirectory *fs = nullptr;
2791 int cpos = -1;
2792 if (p_update_file_system) {
2793 bool found = _find_file(p_file, &fs, cpos);
2794 ERR_FAIL_COND_V_MSG(!found, ERR_FILE_NOT_FOUND, vformat("Can't find file '%s' during file reimport.", p_file));
2795 }
2796
2797 //try to obtain existing params
2798
2799 HashMap<StringName, Variant> params = p_custom_options;
2800 String importer_name; //empty by default though
2801
2802 if (!p_custom_importer.is_empty()) {
2803 importer_name = p_custom_importer;
2804 }
2805
2806 ResourceUID::ID uid = ResourceUID::INVALID_ID;
2807 Variant generator_parameters;
2808 String group_file;
2809 if (p_generator_parameters) {
2810 generator_parameters = *p_generator_parameters;
2811 }
2812
2813 if (FileAccess::exists(p_file + ".import")) {
2814 //use existing
2815 Ref<ConfigFile> cf;
2816 cf.instantiate();
2817 Error err = cf->load(p_file + ".import");
2818 if (err == OK) {
2819 if (cf->has_section("params")) {
2820 Vector<String> sk = cf->get_section_keys("params");
2821 for (const String &E : sk) {
2822 if (!params.has(E)) {
2823 params[E] = cf->get_value("params", E);
2824 }
2825 }
2826 }
2827
2828 if (cf->has_section("remap")) {
2829 if (p_custom_importer.is_empty()) {
2830 importer_name = cf->get_value("remap", "importer");
2831 }
2832
2833 if (cf->has_section_key("remap", "uid")) {
2834 String uidt = cf->get_value("remap", "uid");
2835 uid = ResourceUID::get_singleton()->text_to_id(uidt);
2836 }
2837
2838 if (cf->has_section_key("remap", "group_file")) {
2839 group_file = cf->get_value("remap", "group_file");
2840 }
2841
2842 if (!p_generator_parameters) {
2843 if (cf->has_section_key("remap", "generator_parameters")) {
2844 generator_parameters = cf->get_value("remap", "generator_parameters");
2845 }
2846 }
2847 }
2848 }
2849 }
2850
2851 if (importer_name == "keep" || importer_name == "skip") {
2852 //keep files, do nothing.
2853 if (p_update_file_system) {
2854 fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
2855 fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
2856 fs->files[cpos]->import_md5 = FileAccess::get_md5(p_file + ".import");
2857 fs->files[cpos]->import_dest_paths = Vector<String>();
2858 fs->files[cpos]->deps.clear();
2859 fs->files[cpos]->type = "";
2860 fs->files[cpos]->import_valid = false;
2861 EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
2862 }
2863 return OK;
2864 }
2865 Ref<ResourceImporter> importer;
2866 bool load_default = false;
2867 //find the importer
2868 if (!importer_name.is_empty()) {
2869 importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
2870 }
2871
2872 if (importer.is_null()) {
2873 //not found by name, find by extension
2874 importer = ResourceFormatImporter::get_singleton()->get_importer_by_file(p_file);
2875 load_default = true;
2876 if (importer.is_null()) {
2877 ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, "BUG: File queued for import, but can't be imported, importer for type '" + importer_name + "' not found.");
2878 }
2879 }
2880
2881 if (FileAccess::exists(p_file + ".import")) {
2882 // We only want to handle compat for existing files, not new ones.
2883 importer->handle_compatibility_options(params);
2884 }
2885
2886 //mix with default params, in case a parameter is missing
2887
2888 List<ResourceImporter::ImportOption> opts;
2889 importer->get_import_options(p_file, &opts);
2890 for (const ResourceImporter::ImportOption &E : opts) {
2891 if (!params.has(E.option.name)) { //this one is not present
2892 params[E.option.name] = E.default_value;
2893 }
2894 }
2895
2896 if (load_default && ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) {
2897 //use defaults if exist
2898 Dictionary d = GLOBAL_GET("importer_defaults/" + importer->get_importer_name());
2899
2900 for (const KeyValue<Variant, Variant> &kv : d) {
2901 params[kv.key] = kv.value;
2902 }
2903 }
2904
2905 if (uid == ResourceUID::INVALID_ID) {
2906 uid = ResourceUID::get_singleton()->create_id_for_path(p_file);
2907 }
2908
2909 //finally, perform import!!
2910 String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file);
2911
2912 List<String> import_variants;
2913 List<String> gen_files;
2914 Variant meta;
2915 Error err = importer->import(uid, p_file, base_path, params, &import_variants, &gen_files, &meta);
2916
2917 // As import is complete, save the .import file.
2918
2919 Vector<String> dest_paths;
2920 {
2921 Ref<FileAccess> f = FileAccess::open(p_file + ".import", FileAccess::WRITE);
2922 ERR_FAIL_COND_V_MSG(f.is_null(), ERR_FILE_CANT_OPEN, "Cannot open file from path '" + p_file + ".import'.");
2923
2924 // Write manually, as order matters ([remap] has to go first for performance).
2925 f->store_line("[remap]");
2926 f->store_line("");
2927 f->store_line("importer=\"" + importer->get_importer_name() + "\"");
2928 int version = importer->get_format_version();
2929 if (version > 0) {
2930 f->store_line("importer_version=" + itos(version));
2931 }
2932 if (!importer->get_resource_type().is_empty()) {
2933 f->store_line("type=\"" + importer->get_resource_type() + "\"");
2934 }
2935
2936 f->store_line("uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\""); // Store in readable format.
2937 if (!group_file.is_empty()) {
2938 f->store_line("group_file=\"" + group_file + "\"");
2939 }
2940
2941 if (err == OK) {
2942 if (importer->get_save_extension().is_empty()) {
2943 //no path
2944 } else if (import_variants.size()) {
2945 //import with variants
2946 for (const String &E : import_variants) {
2947 String path = base_path.c_escape() + "." + E + "." + importer->get_save_extension();
2948
2949 f->store_line("path." + E + "=\"" + path + "\"");
2950 dest_paths.push_back(path);
2951 }
2952 } else {
2953 String path = base_path + "." + importer->get_save_extension();
2954 f->store_line("path=\"" + path + "\"");
2955 dest_paths.push_back(path);
2956 }
2957
2958 } else {
2959 f->store_line("valid=false");
2960 }
2961
2962 if (meta != Variant()) {
2963 f->store_line("metadata=" + meta.get_construct_string());
2964 }
2965
2966 if (generator_parameters != Variant()) {
2967 f->store_line("generator_parameters=" + generator_parameters.get_construct_string());
2968 }
2969
2970 f->store_line("");
2971
2972 f->store_line("[deps]\n");
2973
2974 if (gen_files.size()) {
2975 Array genf;
2976 for (const String &E : gen_files) {
2977 genf.push_back(E);
2978 dest_paths.push_back(E);
2979 }
2980
2981 String value;
2982 VariantWriter::write_to_string(genf, value);
2983 f->store_line("files=" + value);
2984 f->store_line("");
2985 }
2986
2987 f->store_line("source_file=" + Variant(p_file).get_construct_string());
2988
2989 if (dest_paths.size()) {
2990 Array dp;
2991 for (int i = 0; i < dest_paths.size(); i++) {
2992 dp.push_back(dest_paths[i]);
2993 }
2994 f->store_line("dest_files=" + Variant(dp).get_construct_string());
2995 }
2996 f->store_line("");
2997
2998 f->store_line("[params]");
2999 f->store_line("");
3000
3001 // Store options in provided order, to avoid file changing. Order is also important because first match is accepted first.
3002
3003 for (const ResourceImporter::ImportOption &E : opts) {
3004 String base = E.option.name;
3005 String value;
3006 VariantWriter::write_to_string(params[base], value);
3007 f->store_line(base + "=" + value);
3008 }
3009 }
3010
3011 // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled.
3012 {
3013 Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE);
3014 ERR_FAIL_COND_V_MSG(md5s.is_null(), ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'.");
3015
3016 md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\"");
3017 if (dest_paths.size()) {
3018 md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n");
3019 }
3020 }
3021
3022 if (p_update_file_system) {
3023 // Update cpos, newly created files could've changed the index of the reimported p_file.
3024 _find_file(p_file, &fs, cpos);
3025
3026 // Update modified times, to avoid reimport.
3027 fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
3028 fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
3029 fs->files[cpos]->import_md5 = FileAccess::get_md5(p_file + ".import");
3030 fs->files[cpos]->import_dest_paths = dest_paths;
3031 fs->files[cpos]->deps = _get_dependencies(p_file);
3032 fs->files[cpos]->type = importer->get_resource_type();
3033 fs->files[cpos]->uid = uid;
3034 fs->files[cpos]->import_valid = fs->files[cpos]->type == "TextFile" ? true : ResourceLoader::is_import_valid(p_file);
3035 }
3036
3037 for (const String &path : gen_files) {
3038 Ref<Resource> cached = ResourceCache::get_ref(path);
3039 if (cached.is_valid()) {
3040 cached->reload_from_file();
3041 }
3042 }
3043
3044 if (ResourceUID::get_singleton()->has_id(uid)) {
3045 ResourceUID::get_singleton()->set_id(uid, p_file);
3046 } else {
3047 ResourceUID::get_singleton()->add_id(uid, p_file);
3048 }
3049
3050 // If file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
3051 // to reload properly.
3052 Ref<Resource> r = ResourceCache::get_ref(p_file);
3053 if (r.is_valid()) {
3054 if (!r->get_import_path().is_empty()) {
3055 String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file);
3056 r->set_import_path(dst_path);
3057 r->set_import_last_modified_time(0);
3058 }
3059 }
3060
3061 EditorResourcePreview::get_singleton()->check_for_invalidation(p_file);
3062
3063 print_verbose(vformat("EditorFileSystem: \"%s\" import took %d ms.", p_file, OS::get_singleton()->get_ticks_msec() - start_time));
3064
3065 ERR_FAIL_COND_V_MSG(err != OK, ERR_FILE_UNRECOGNIZED, "Error importing '" + p_file + "'.");
3066 return OK;
3067 }
3068
3069 void EditorFileSystem::_find_group_files(EditorFileSystemDirectory *efd, HashMap<String, Vector<String>> &group_files, HashSet<String> &groups_to_reimport) {
3070 int fc = efd->files.size();
3071 const EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptr();
3072 for (int i = 0; i < fc; i++) {
3073 if (groups_to_reimport.has(files[i]->import_group_file)) {
3074 if (!group_files.has(files[i]->import_group_file)) {
3075 group_files[files[i]->import_group_file] = Vector<String>();
3076 }
3077 group_files[files[i]->import_group_file].push_back(efd->get_file_path(i));
3078 }
3079 }
3080
3081 for (int i = 0; i < efd->get_subdir_count(); i++) {
3082 _find_group_files(efd->get_subdir(i), group_files, groups_to_reimport);
3083 }
3084 }
3085
3086 void EditorFileSystem::reimport_file_with_custom_parameters(const String &p_file, const String &p_importer, const HashMap<StringName, Variant> &p_custom_params) {
3087 Vector<String> reloads;
3088 reloads.append(p_file);
3089
3090 // Emit the resource_reimporting signal for the single file before the actual importation.
3091 emit_signal(SNAME("resources_reimporting"), reloads);
3092
3093 _reimport_file(p_file, p_custom_params, p_importer);
3094
3095 // Emit the resource_reimported signal for the single file we just reimported.
3096 emit_signal(SNAME("resources_reimported"), reloads);
3097 }
3098
3099 Error EditorFileSystem::_copy_file(const String &p_from, const String &p_to) {
3100 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
3101 if (FileAccess::exists(p_from + ".import")) {
3102 Error err = da->copy(p_from, p_to);
3103 if (err != OK) {
3104 return err;
3105 }
3106
3107 // Save the new .import file
3108 Ref<ConfigFile> cfg;
3109 cfg.instantiate();
3110 cfg->load(p_from + ".import");
3111 String importer_name = cfg->get_value("remap", "importer");
3112
3113 if (importer_name == "keep" || importer_name == "skip") {
3114 err = da->copy(p_from + ".import", p_to + ".import");
3115 return err;
3116 }
3117
3118 // Roll a new uid for this copied .import file to avoid conflict.
3119 ResourceUID::ID res_uid = ResourceUID::get_singleton()->create_id_for_path(p_to);
3120 cfg->set_value("remap", "uid", ResourceUID::get_singleton()->id_to_text(res_uid));
3121 err = cfg->save(p_to + ".import");
3122 if (err != OK) {
3123 return err;
3124 }
3125
3126 // Make sure it's immediately added to the map so we can remap dependencies if we want to after this.
3127 ResourceUID::get_singleton()->add_id(res_uid, p_to);
3128 } else if (ResourceLoader::get_resource_uid(p_from) == ResourceUID::INVALID_ID) {
3129 // Files which do not use an uid can just be copied.
3130 Error err = da->copy(p_from, p_to);
3131 if (err != OK) {
3132 return err;
3133 }
3134 } else {
3135 // Load the resource and save it again in the new location (this generates a new UID).
3136 Error err = OK;
3137 Ref<Resource> res = ResourceCache::get_ref(p_from);
3138 if (res.is_null()) {
3139 res = ResourceLoader::load(p_from, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
3140 } else {
3141 bool edited = false;
3142 List<Ref<Resource>> cached;
3143 ResourceCache::get_cached_resources(&cached);
3144 for (Ref<Resource> &resource : cached) {
3145 if (!resource->is_edited()) {
3146 continue;
3147 }
3148 if (!resource->get_path().begins_with(p_from)) {
3149 continue;
3150 }
3151 // The resource or one of its built-in resources is edited.
3152 edited = true;
3153 resource->set_edited(false);
3154 }
3155
3156 if (edited) {
3157 // Save cached resources to prevent changes from being lost and to prevent discrepancies.
3158 EditorNode::get_singleton()->save_resource(res);
3159 }
3160 }
3161 if (err == OK && res.is_valid()) {
3162 err = ResourceSaver::save(res, p_to, ResourceSaver::FLAG_COMPRESS);
3163 if (err != OK) {
3164 return err;
3165 }
3166 } else if (err != OK) {
3167 // When loading files like text files the error is OK but the resource is still null.
3168 // We can ignore such files.
3169 return err;
3170 }
3171 }
3172 return OK;
3173 }
3174
3175 bool EditorFileSystem::_copy_directory(const String &p_from, const String &p_to, HashMap<String, String> *p_files) {
3176 Ref<DirAccess> old_dir = DirAccess::open(p_from);
3177 ERR_FAIL_COND_V(old_dir.is_null(), false);
3178
3179 Error err = make_dir_recursive(p_to);
3180 if (err != OK && err != ERR_ALREADY_EXISTS) {
3181 return false;
3182 }
3183
3184 bool success = true;
3185 old_dir->set_include_navigational(false);
3186 old_dir->list_dir_begin();
3187
3188 for (String F = old_dir->_get_next(); !F.is_empty(); F = old_dir->_get_next()) {
3189 if (old_dir->current_is_dir()) {
3190 success = _copy_directory(p_from.path_join(F), p_to.path_join(F), p_files) && success;
3191 } else if (F.get_extension() != "import" && F.get_extension() != "uid") {
3192 (*p_files)[p_from.path_join(F)] = p_to.path_join(F);
3193 }
3194 }
3195 return success;
3196 }
3197
3198 void EditorFileSystem::_queue_refresh_filesystem() {
3199 if (refresh_queued) {
3200 return;
3201 }
3202 refresh_queued = true;
3203 get_tree()->connect(SNAME("process_frame"), callable_mp(this, &EditorFileSystem::_refresh_filesystem), CONNECT_ONE_SHOT);
3204 }
3205
3206 void EditorFileSystem::_refresh_filesystem() {
3207 for (const ObjectID &id : folders_to_sort) {
3208 EditorFileSystemDirectory *dir = ObjectDB::get_instance<EditorFileSystemDirectory>(id);
3209 if (dir) {
3210 dir->subdirs.sort_custom<DirectoryComparator>();
3211 }
3212 }
3213 folders_to_sort.clear();
3214
3215 _update_scan_actions();
3216
3217 emit_signal(SNAME("filesystem_changed"));
3218 refresh_queued = false;
3219 }
3220
3221 void EditorFileSystem::_reimport_thread(uint32_t p_index, ImportThreadData *p_import_data) {
3222 ResourceLoader::set_is_import_thread(true);
3223 int file_idx = p_import_data->reimport_from + int(p_index);
3224 _reimport_file(p_import_data->reimport_files[file_idx].path);
3225 ResourceLoader::set_is_import_thread(false);
3226
3227 p_import_data->imported_sem->post();
3228 }
3229
3230 void EditorFileSystem::reimport_files(const Vector<String> &p_files) {
3231 ERR_FAIL_COND_MSG(importing, "Attempted to call reimport_files() recursively, this is not allowed.");
3232 importing = true;
3233
3234 Vector<String> reloads;
3235
3236 EditorProgress *ep = memnew(EditorProgress("reimport", TTR("(Re)Importing Assets"), p_files.size()));
3237
3238 // The method reimport_files runs on the main thread, and if VSync is enabled
3239 // or Update Continuously is disabled, Main::Iteration takes longer each frame.
3240 // Each EditorProgress::step can trigger a redraw, and when there are many files to import,
3241 // this could lead to a slow import process, especially when the editor is unfocused.
3242 // Temporarily disabling VSync and low_processor_usage_mode while reimporting fixes this.
3243 const bool old_low_processor_usage_mode = OS::get_singleton()->is_in_low_processor_usage_mode();
3244 const DisplayServer::VSyncMode old_vsync_mode = DisplayServer::get_singleton()->window_get_vsync_mode(DisplayServer::MAIN_WINDOW_ID);
3245 OS::get_singleton()->set_low_processor_usage_mode(false);
3246 DisplayServer::get_singleton()->window_set_vsync_mode(DisplayServer::VSyncMode::VSYNC_DISABLED);
3247
3248 Vector<ImportFile> reimport_files;
3249
3250 HashSet<String> groups_to_reimport;
3251
3252 for (int i = 0; i < p_files.size(); i++) {
3253 ep->step(TTR("Preparing files to reimport..."), i, false);
3254
3255 String file = p_files[i];
3256
3257 ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(file);
3258 if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
3259 file = ResourceUID::get_singleton()->get_id_path(uid);
3260 }
3261
3262 String group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(file);
3263
3264 if (group_file_cache.has(file)) {
3265 // Maybe the file itself is a group!
3266 groups_to_reimport.insert(file);
3267 // Groups do not belong to groups.
3268 group_file = String();
3269 } else if (groups_to_reimport.has(file)) {
3270 // Groups do not belong to groups.
3271 group_file = String();
3272 } else if (!group_file.is_empty()) {
3273 // It's a group file, add group to import and skip this file.
3274 groups_to_reimport.insert(group_file);
3275 } else {
3276 // It's a regular file.
3277 ImportFile ifile;
3278 ifile.path = file;
3279 ResourceFormatImporter::get_singleton()->get_import_order_threads_and_importer(file, ifile.order, ifile.threaded, ifile.importer);
3280 reloads.push_back(file);
3281 reimport_files.push_back(ifile);
3282 }
3283
3284 // Group may have changed, so also update group reference.
3285 EditorFileSystemDirectory *fs = nullptr;
3286 int cpos = -1;
3287 if (_find_file(file, &fs, cpos)) {
3288 fs->files.write[cpos]->import_group_file = group_file;
3289 }
3290 }
3291
3292 reimport_files.sort();
3293
3294 ep->step(TTR("Executing pre-reimport operations..."), 0, true);
3295
3296 // Emit the resource_reimporting signal for the single file before the actual importation.
3297 emit_signal(SNAME("resources_reimporting"), reloads);
3298
3299 #ifdef WEB_ENABLED
3300 // On web, busy-wait loops on the main thread block the JavaScript event loop,
3301 // causing the browser tab to appear frozen. Disable threaded imports entirely.
3302 // See GH-112072 for details.
3303 bool use_multiple_threads = false;
3304 #elif defined(THREADS_ENABLED)
3305 bool use_multiple_threads = GLOBAL_GET("editor/import/use_multiple_threads");
3306 #else
3307 bool use_multiple_threads = false;
3308 #endif
3309
3310 int from = 0;
3311 Semaphore imported_sem;
3312 for (int i = 0; i < reimport_files.size(); i++) {
3313 if (groups_to_reimport.has(reimport_files[i].path)) {
3314 from = i + 1;
3315 continue;
3316 }
3317
3318 if (use_multiple_threads && reimport_files[i].threaded) {
3319 if (i + 1 == reimport_files.size() || reimport_files[i + 1].importer != reimport_files[from].importer || groups_to_reimport.has(reimport_files[i + 1].path)) {
3320 if (from - i == 0) {
3321 // Single file, do not use threads.
3322 ep->step(reimport_files[i].path.get_file(), i, false);
3323 _reimport_file(reimport_files[i].path);
3324 } else {
3325 Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(reimport_files[from].importer);
3326 if (importer.is_null()) {
3327 ERR_PRINT(vformat("Invalid importer for \"%s\".", reimport_files[from].importer));
3328 from = i + 1;
3329 continue;
3330 }
3331
3332 importer->import_threaded_begin();
3333
3334 ImportThreadData tdata;
3335 tdata.reimport_from = from;
3336 tdata.reimport_files = reimport_files.ptr();
3337 tdata.imported_sem = &imported_sem;
3338
3339 int item_count = i - from + 1;
3340 WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &EditorFileSystem::_reimport_thread, &tdata, item_count, -1, false, vformat(TTR("Import resources of type: %s"), reimport_files[from].importer));
3341
3342 int imported_count = 0;
3343 while (true) {
3344 while (true) {
3345 ep->step(reimport_files[imported_count].path.get_file(), from + imported_count, false);
3346 if (imported_sem.try_wait()) {
3347 imported_count++;
3348 break;
3349 }
3350 }
3351 if (imported_count == item_count) {
3352 break;
3353 }
3354 }
3355
3356 WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
3357 DEV_ASSERT(!imported_sem.try_wait());
3358
3359 importer->import_threaded_end();
3360 }
3361
3362 from = i + 1;
3363 }
3364
3365 } else {
3366 ep->step(reimport_files[i].path.get_file(), i, false);
3367 _reimport_file(reimport_files[i].path);
3368
3369 // We need to increment the counter, maybe the next file is multithreaded
3370 // and doesn't have the same importer.
3371 from = i + 1;
3372 }
3373 }
3374
3375 // Reimport groups.
3376
3377 from = reimport_files.size();
3378
3379 if (groups_to_reimport.size()) {
3380 HashMap<String, Vector<String>> group_files;
3381 _find_group_files(filesystem, group_files, groups_to_reimport);
3382 for (const KeyValue<String, Vector<String>> &E : group_files) {
3383 ep->step(E.key.get_file(), from++, false);
3384 Error err = _reimport_group(E.key, E.value);
3385 reloads.push_back(E.key);
3386 reloads.append_array(E.value);
3387 if (err == OK) {
3388 _reimport_file(E.key);
3389 }
3390 }
3391 }
3392 ep->step(TTR("Finalizing Asset Import..."), p_files.size());
3393
3394 ResourceUID::get_singleton()->update_cache(); // After reimporting, update the cache.
3395 _save_filesystem_cache();
3396
3397 memdelete_notnull(ep);
3398
3399 _process_update_pending();
3400
3401 // Revert to previous values to restore editor settings for VSync and Update Continuously.
3402 OS::get_singleton()->set_low_processor_usage_mode(old_low_processor_usage_mode);
3403 DisplayServer::get_singleton()->window_set_vsync_mode(old_vsync_mode);
3404
3405 importing = false;
3406
3407 ep = memnew(EditorProgress("reimport", TTR("(Re)Importing Assets"), p_files.size()));
3408 ep->step(TTR("Executing post-reimport operations..."), 0, true);
3409 if (!is_scanning()) {
3410 emit_signal(SNAME("filesystem_changed"));
3411 }
3412 emit_signal(SNAME("resources_reimported"), reloads);
3413 memdelete_notnull(ep);
3414 }
3415
3416 Error EditorFileSystem::reimport_append(const String &p_file, const HashMap<StringName, Variant> &p_custom_options, const String &p_custom_importer, Variant p_generator_parameters) {
3417 Vector<String> reloads;
3418 reloads.append(p_file);
3419
3420 // Emit the resource_reimporting signal for the single file before the actual importation.
3421 emit_signal(SNAME("resources_reimporting"), reloads);
3422
3423 Error ret = _reimport_file(p_file, p_custom_options, p_custom_importer, &p_generator_parameters);
3424
3425 // Emit the resource_reimported signal for the single file we just reimported.
3426 emit_signal(SNAME("resources_reimported"), reloads);
3427 return ret;
3428 }
3429
3430 Error EditorFileSystem::_resource_import(const String &p_path) {
3431 Vector<String> files;
3432 files.push_back(p_path);
3433
3434 singleton->update_file(p_path);
3435 singleton->reimport_files(files);
3436
3437 return OK;
3438 }
3439
3440 Ref<Resource> EditorFileSystem::_load_resource_on_startup(ResourceFormatImporter *p_importer, const String &p_path, Error *r_error, bool p_use_sub_threads, float *r_progress, ResourceFormatLoader::CacheMode p_cache_mode) {
3441 ERR_FAIL_NULL_V(p_importer, Ref<Resource>());
3442
3443 if (!FileAccess::exists(p_path)) {
3444 ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Failed loading resource: %s. The file doesn't seem to exist.", p_path));
3445 }
3446
3447 // Fail silently. Hopefully the resource is not yet imported.
3448 Ref<Resource> res = p_importer->load_internal(p_path, r_error, p_use_sub_threads, r_progress, p_cache_mode, true);
3449 if (res.is_valid()) {
3450 return res;
3451 }
3452
3453 // Retry after importing the resource.
3454 if (singleton->_reimport_file(p_path, HashMap<StringName, Variant>(), "", nullptr, false) != OK) {
3455 return Ref<Resource>();
3456 }
3457 return p_importer->load_internal(p_path, r_error, p_use_sub_threads, r_progress, p_cache_mode, false);
3458 }
3459
3460 bool EditorFileSystem::_should_skip_directory(const String &p_path) {
3461 String project_data_path = ProjectSettings::get_singleton()->get_project_data_path();
3462 if (p_path == project_data_path || p_path.begins_with(project_data_path + "/")) {
3463 return true;
3464 }
3465
3466 if (FileAccess::exists(p_path.path_join("project.godot"))) {
3467 // Skip if another project inside this.
3468 if (EditorFileSystem::get_singleton() == nullptr || EditorFileSystem::get_singleton()->first_scan) {
3469 WARN_PRINT_ONCE(vformat("Detected another project.godot at %s. The folder will be ignored.", p_path));
3470 }
3471 return true;
3472 }
3473
3474 if (FileAccess::exists(p_path.path_join(".gdignore"))) {
3475 // Skip if a `.gdignore` file is inside this.
3476 return true;
3477 }
3478
3479 return false;
3480 }
3481
3482 bool EditorFileSystem::is_group_file(const String &p_path) const {
3483 return group_file_cache.has(p_path);
3484 }
3485
3486 void EditorFileSystem::_move_group_files(EditorFileSystemDirectory *efd, const String &p_group_file, const String &p_new_location) {
3487 int fc = efd->files.size();
3488 EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptrw();
3489 for (int i = 0; i < fc; i++) {
3490 if (files[i]->import_group_file == p_group_file) {
3491 files[i]->import_group_file = p_new_location;
3492
3493 Ref<ConfigFile> config;
3494 config.instantiate();
3495 String path = efd->get_file_path(i) + ".import";
3496 Error err = config->load(path);
3497 if (err != OK) {
3498 continue;
3499 }
3500 if (config->has_section_key("remap", "group_file")) {
3501 config->set_value("remap", "group_file", p_new_location);
3502 }
3503
3504 Vector<String> sk = config->get_section_keys("params");
3505 for (const String &param : sk) {
3506 //not very clean, but should work
3507 String value = config->get_value("params", param);
3508 if (value == p_group_file) {
3509 config->set_value("params", param, p_new_location);
3510 }
3511 }
3512
3513 config->save(path);
3514 }
3515 }
3516
3517 for (int i = 0; i < efd->get_subdir_count(); i++) {
3518 _move_group_files(efd->get_subdir(i), p_group_file, p_new_location);
3519 }
3520 }
3521
3522 void EditorFileSystem::move_group_file(const String &p_path, const String &p_new_path) {
3523 if (get_filesystem()) {
3524 _move_group_files(get_filesystem(), p_path, p_new_path);
3525 if (group_file_cache.has(p_path)) {
3526 group_file_cache.erase(p_path);
3527 group_file_cache.insert(p_new_path);
3528 }
3529 }
3530 }
3531
3532 Error EditorFileSystem::make_dir_recursive(const String &p_path, const String &p_base_path) {
3533 Error err;
3534 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
3535 if (!p_base_path.is_empty()) {
3536 err = da->change_dir(p_base_path);
3537 ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open base directory '" + p_base_path + "'.");
3538 }
3539
3540 if (da->dir_exists(p_path)) {
3541 return ERR_ALREADY_EXISTS;
3542 }
3543
3544 err = da->make_dir_recursive(p_path);
3545 if (err != OK) {
3546 return err;
3547 }
3548
3549 const String path = da->get_current_dir();
3550 EditorFileSystemDirectory *parent = get_filesystem_path(path);
3551 ERR_FAIL_NULL_V(parent, ERR_FILE_NOT_FOUND);
3552 folders_to_sort.insert(parent->get_instance_id());
3553
3554 const PackedStringArray folders = p_path.trim_prefix(path).split("/", false);
3555 for (const String &folder : folders) {
3556 const int current = parent->find_dir_index(folder);
3557 if (current > -1) {
3558 parent = parent->get_subdir(current);
3559 continue;
3560 }
3561
3562 EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
3563 efd->parent = parent;
3564 efd->name = folder;
3565 parent->subdirs.push_back(efd);
3566 parent = efd;
3567 }
3568
3569 _queue_refresh_filesystem();
3570 return OK;
3571 }
3572
3573 Error EditorFileSystem::copy_file(const String &p_from, const String &p_to) {
3574 Error err = _copy_file(p_from, p_to);
3575 if (err != OK) {
3576 return err;
3577 }
3578
3579 EditorFileSystemDirectory *parent = get_filesystem_path(p_to.get_base_dir());
3580 ERR_FAIL_NULL_V(parent, ERR_FILE_NOT_FOUND);
3581
3582 ScanProgress sp;
3583 _scan_fs_changes(parent, sp, false);
3584
3585 _queue_refresh_filesystem();
3586 return OK;
3587 }
3588
3589 Error EditorFileSystem::copy_directory(const String &p_from, const String &p_to) {
3590 // Recursively copy directories and build a map of files to copy.
3591 HashMap<String, String> files;
3592 bool success = _copy_directory(p_from, p_to, &files);
3593
3594 // Copy the files themselves
3595 if (success) {
3596 EditorProgress *ep = nullptr;
3597 if (files.size() > 10) {
3598 ep = memnew(EditorProgress("copy_directory", TTR("Copying files..."), files.size()));
3599 }
3600 int i = 0;
3601 for (const KeyValue<String, String> &tuple : files) {
3602 if (_copy_file(tuple.key, tuple.value) != OK) {
3603 success = false;
3604 }
3605 if (ep) {
3606 ep->step(tuple.key.get_file(), i++, false);
3607 }
3608 }
3609 memdelete_notnull(ep);
3610 }
3611
3612 // Now remap any internal dependencies (within the folder) to use the new files.
3613 if (success) {
3614 EditorProgress *ep = nullptr;
3615 if (files.size() > 10) {
3616 ep = memnew(EditorProgress("copy_directory", TTR("Remapping dependencies..."), files.size()));
3617 }
3618 int i = 0;
3619 for (const KeyValue<String, String> &tuple : files) {
3620 if (ResourceLoader::rename_dependencies(tuple.value, files) != OK) {
3621 success = false;
3622 }
3623 update_file(tuple.value);
3624 if (ep) {
3625 ep->step(tuple.key.get_file(), i++, false);
3626 }
3627 }
3628 memdelete_notnull(ep);
3629 }
3630
3631 EditorFileSystemDirectory *efd = get_filesystem_path(p_to);
3632 ERR_FAIL_NULL_V(efd, FAILED);
3633 ERR_FAIL_NULL_V(efd->get_parent(), FAILED);
3634
3635 folders_to_sort.insert(efd->get_parent()->get_instance_id());
3636
3637 ScanProgress sp;
3638 _scan_fs_changes(efd, sp);
3639
3640 _queue_refresh_filesystem();
3641 return success ? OK : FAILED;
3642 }
3643
3644 ResourceUID::ID EditorFileSystem::_resource_saver_get_resource_id_for_path(const String &p_path, bool p_generate) {
3645 if (!p_path.is_resource_file() || p_path.begins_with(ProjectSettings::get_singleton()->get_project_data_path())) {
3646 // Saved externally (configuration file) or internal file, do not assign an ID.
3647 return ResourceUID::INVALID_ID;
3648 }
3649
3650 EditorFileSystemDirectory *fs = nullptr;
3651 int cpos = -1;
3652
3653 if (!singleton->_find_file(p_path, &fs, cpos)) {
3654 // Fallback to ResourceLoader if filesystem cache fails (can happen during scanning etc.).
3655 ResourceUID::ID fallback = ResourceLoader::get_resource_uid(p_path);
3656 if (fallback != ResourceUID::INVALID_ID) {
3657 return fallback;
3658 }
3659
3660 if (p_generate) {
3661 return ResourceUID::get_singleton()->create_id_for_path(p_path); // Just create a new one, we will be notified of save anyway and fetch the right UID at that time, to keep things simple.
3662 } else {
3663 return ResourceUID::INVALID_ID;
3664 }
3665 } else if (fs->files[cpos]->uid != ResourceUID::INVALID_ID) {
3666 return fs->files[cpos]->uid;
3667 } else if (p_generate) {
3668 return ResourceUID::get_singleton()->create_id_for_path(p_path); // Just create a new one, we will be notified of save anyway and fetch the right UID at that time, to keep things simple.
3669 } else {
3670 return ResourceUID::INVALID_ID;
3671 }
3672 }
3673
3674 static void _scan_extensions_dir(EditorFileSystemDirectory *d, HashSet<String> &extensions) {
3675 int fc = d->get_file_count();
3676 for (int i = 0; i < fc; i++) {
3677 if (d->get_file_type(i) == SNAME("GDExtension")) {
3678 extensions.insert(d->get_file_path(i));
3679 }
3680 }
3681 int dc = d->get_subdir_count();
3682 for (int i = 0; i < dc; i++) {
3683 _scan_extensions_dir(d->get_subdir(i), extensions);
3684 }
3685 }
3686 bool EditorFileSystem::_scan_extensions() {
3687 EditorFileSystemDirectory *d = get_filesystem();
3688 HashSet<String> extensions;
3689
3690 _scan_extensions_dir(d, extensions);
3691
3692 return GDExtensionManager::get_singleton()->ensure_extensions_loaded(extensions);
3693 }
3694
3695 void EditorFileSystem::_bind_methods() {
3696 ClassDB::bind_method(D_METHOD("get_filesystem"), &EditorFileSystem::get_filesystem);
3697 ClassDB::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning);
3698 ClassDB::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress);
3699 ClassDB::bind_method(D_METHOD("scan"), &EditorFileSystem::scan);
3700 ClassDB::bind_method(D_METHOD("scan_sources"), &EditorFileSystem::scan_changes);
3701 ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file);
3702 ClassDB::bind_method(D_METHOD("get_filesystem_path", "path"), &EditorFileSystem::get_filesystem_path);
3703 ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type);
3704 ClassDB::bind_method(D_METHOD("reimport_files", "files"), &EditorFileSystem::reimport_files);
3705
3706 ADD_SIGNAL(MethodInfo("filesystem_changed"));
3707 ADD_SIGNAL(MethodInfo("script_classes_updated"));
3708 ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist")));
3709 ADD_SIGNAL(MethodInfo("resources_reimporting", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
3710 ADD_SIGNAL(MethodInfo("resources_reimported", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
3711 ADD_SIGNAL(MethodInfo("resources_reload", PropertyInfo(Variant::PACKED_STRING_ARRAY, "resources")));
3712 }
3713
3714 void EditorFileSystem::_update_extensions() {
3715 valid_extensions.clear();
3716 import_extensions.clear();
3717 textfile_extensions.clear();
3718 other_file_extensions.clear();
3719
3720 List<String> extensionsl;
3721 ResourceLoader::get_recognized_extensions_for_type("", &extensionsl);
3722 for (const String &E : extensionsl) {
3723 valid_extensions.insert(E);
3724 }
3725
3726 const Vector<String> textfile_ext = ((String)(EDITOR_GET("docks/filesystem/textfile_extensions"))).split(",", false);
3727 for (const String &E : textfile_ext) {
3728 if (valid_extensions.has(E)) {
3729 continue;
3730 }
3731 valid_extensions.insert(E);
3732 textfile_extensions.insert(E);
3733 }
3734 const Vector<String> other_file_ext = ((String)(EDITOR_GET("docks/filesystem/other_file_extensions"))).split(",", false);
3735 for (const String &E : other_file_ext) {
3736 if (valid_extensions.has(E)) {
3737 continue;
3738 }
3739 valid_extensions.insert(E);
3740 other_file_extensions.insert(E);
3741 }
3742
3743 extensionsl.clear();
3744 ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl);
3745 for (const String &E : extensionsl) {
3746 import_extensions.insert(!E.begins_with(".") ? "." + E : E);
3747 }
3748 }
3749
3750 bool EditorFileSystem::_can_import_file(const String &p_file) {
3751 for (const String &F : import_extensions) {
3752 if (p_file.right(F.length()).nocasecmp_to(F) == 0) {
3753 return true;
3754 }
3755 }
3756
3757 return false;
3758 }
3759
3760 void EditorFileSystem::add_import_format_support_query(Ref<EditorFileSystemImportFormatSupportQuery> p_query) {
3761 ERR_FAIL_COND(import_support_queries.has(p_query));
3762 import_support_queries.push_back(p_query);
3763 }
3764 void EditorFileSystem::remove_import_format_support_query(Ref<EditorFileSystemImportFormatSupportQuery> p_query) {
3765 import_support_queries.erase(p_query);
3766 }
3767
3768 EditorFileSystem::EditorFileSystem() {
3769 #if defined(THREADS_ENABLED) && !defined(WEB_ENABLED)
3770 // On web, threaded scanning blocks the browser's event loop, causing freezes.
3771 // See GH-112072 for details.
3772 use_threads = true;
3773 #endif
3774
3775 ResourceLoader::import = _resource_import;
3776 reimport_on_missing_imported_files = GLOBAL_GET("editor/import/reimport_missing_imported_files");
3777 singleton = this;
3778 filesystem = memnew(EditorFileSystemDirectory); //like, empty
3779 filesystem->parent = nullptr;
3780
3781 new_filesystem = nullptr;
3782
3783 // This should probably also work on Unix and use the string it returns for FAT32 or exFAT
3784 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
3785 using_fat32_or_exfat = (da->get_filesystem_type() == "FAT32" || da->get_filesystem_type() == "EXFAT");
3786
3787 scan_total = 0;
3788 ResourceSaver::set_get_resource_id_for_path(_resource_saver_get_resource_id_for_path);
3789
3790 // Set the callback method that the ResourceFormatImporter will use
3791 // if resources are loaded during the first scan.
3792 ResourceImporter::load_on_startup = _load_resource_on_startup;
3793 }
3794
3795 EditorFileSystem::~EditorFileSystem() {
3796 if (filesystem) {
3797 memdelete(filesystem);
3798 }
3799 filesystem = nullptr;
3800 ResourceSaver::set_get_resource_id_for_path(nullptr);
3801 }