editor_file_system.cpp 122 KB

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