FileHelperBPLibrary.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. // Copyright 2023 RLoris
  2. #include "FileHelperBPLibrary.h"
  3. #include "HAL/PlatformFileManager.h"
  4. #include "HAL/FileManager.h"
  5. #include "Misc/FileHelper.h"
  6. #include "Misc/Base64.h"
  7. #include "Math/Color.h"
  8. #include "Misc/ConfigCacheIni.h"
  9. #include "Engine/DataTable.h"
  10. #include "Internationalization/Regex.h"
  11. #include "Serialization/Csv/CsvParser.h"
  12. #include "UObject/TextProperty.h"
  13. class FCustomFileVisitor : public IPlatformFile::FDirectoryVisitor
  14. {
  15. public:
  16. FString BasePath;
  17. TArray<FString>& Nodes;
  18. FString Filter;
  19. FRegexPattern CustomPattern;
  20. bool bFile = true;
  21. bool bDirectory = true;
  22. FCustomFileVisitor(FString& Path, TArray<FString>& Paths, const FString& Pattern, bool File, bool Directory) : BasePath(Path), Nodes(Paths), Filter(Pattern), CustomPattern(Pattern), bFile(File), bDirectory(Directory) {};
  23. virtual bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory);
  24. };
  25. FEnginePath UFileHelperBPLibrary::GetEngineDirectories()
  26. {
  27. FEnginePath P;
  28. P.Directory = FPaths::ConvertRelativePathToFull(FPaths::EngineDir());
  29. P.Config = FPaths::ConvertRelativePathToFull(FPaths::EngineConfigDir());
  30. P.Content = FPaths::ConvertRelativePathToFull(FPaths::EngineContentDir());
  31. P.Intermediate = FPaths::ConvertRelativePathToFull(FPaths::EngineIntermediateDir());
  32. P.Plugins = FPaths::ConvertRelativePathToFull(FPaths::EnginePluginsDir());
  33. P.Saved =FPaths::ConvertRelativePathToFull( FPaths::EngineSavedDir());
  34. P.User = FPaths::ConvertRelativePathToFull(FPaths::EngineUserDir());
  35. P.DefaultLayout = FPaths::ConvertRelativePathToFull(FPaths::EngineDefaultLayoutDir());
  36. P.PlatformExtensions = FPaths::ConvertRelativePathToFull(FPaths::EnginePlatformExtensionsDir());
  37. P.UserLayout = FPaths::ConvertRelativePathToFull(FPaths::EngineUserLayoutDir());
  38. return P;
  39. }
  40. FProjectPath UFileHelperBPLibrary::GetProjectDirectories()
  41. {
  42. FProjectPath P;
  43. P.Directory = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir());
  44. P.Config = FPaths::ConvertRelativePathToFull(FPaths::ProjectConfigDir());
  45. P.Content = FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir());
  46. P.Intermediate = FPaths::ConvertRelativePathToFull(FPaths::ProjectIntermediateDir());
  47. P.Log = FPaths::ConvertRelativePathToFull(FPaths::ProjectLogDir());
  48. P.Mods = FPaths::ConvertRelativePathToFull(FPaths::ProjectModsDir());
  49. P.Plugins = FPaths::ConvertRelativePathToFull(FPaths::ProjectPluginsDir());
  50. P.Saved = FPaths::ConvertRelativePathToFull(FPaths::ProjectSavedDir());
  51. P.User = FPaths::ConvertRelativePathToFull(FPaths::ProjectUserDir());
  52. P.PersistentDownload = FPaths::ConvertRelativePathToFull(FPaths::ProjectPersistentDownloadDir());
  53. P.PlatformExtensions = FPaths::ConvertRelativePathToFull(FPaths::ProjectPlatformExtensionsDir());
  54. return P;
  55. }
  56. bool UFileHelperBPLibrary::ReadText(FString Path, FString& Output)
  57. {
  58. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  59. if (FileManager.FileExists(*Path))
  60. {
  61. return FFileHelper::LoadFileToString(Output, *Path);
  62. }
  63. return false;
  64. }
  65. bool UFileHelperBPLibrary::SaveText(FString Path, FString Text, FString& Error, bool Append, bool Force)
  66. {
  67. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  68. FText ErrorFilename;
  69. if (!FFileHelper::IsFilenameValidForSaving(Path, ErrorFilename))
  70. {
  71. Error = FString("Filename is not valid");
  72. return false;
  73. }
  74. if (!FileManager.FileExists(*Path) || Append || Force)
  75. {
  76. return FFileHelper::SaveStringToFile(Text, *Path, FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), Append ? FILEWRITE_Append : FILEWRITE_None);
  77. }
  78. else
  79. {
  80. Error = FString("File already exists");
  81. }
  82. return false;
  83. }
  84. bool UFileHelperBPLibrary::SaveCSV(FString Path, TArray<FString> Headers, TArray<FString> Data, int32& Total, bool Force)
  85. {
  86. FString Output;
  87. if (!UFileHelperBPLibrary::CSVToString(Output, Headers, Data, Total))
  88. {
  89. return false;
  90. }
  91. FString Error;
  92. return UFileHelperBPLibrary::SaveText(Path, Output, Error, false, Force);
  93. }
  94. bool UFileHelperBPLibrary::ReadCSV(FString Path, TArray<FString>& Headers, TArray<FString>& Data, int32& Total, bool HeaderFirst)
  95. {
  96. Total = 0;
  97. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  98. if (!FileManager.FileExists(*Path))
  99. {
  100. return false;
  101. }
  102. FString Result;
  103. if (!FFileHelper::LoadFileToString(Result, *Path))
  104. {
  105. return false;
  106. }
  107. return UFileHelperBPLibrary::StringToCSV(Result, Headers, Data, Total, HeaderFirst);
  108. // return UFileHelperBPLibrary::StringArrayToCSV(Result, Headers, Data, Total, ",", HeaderFirst);
  109. }
  110. bool UFileHelperBPLibrary::ReadLine(FString Path, FString Pattern, TArray<FString>& Lines)
  111. {
  112. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  113. if (!FileManager.FileExists(*Path))
  114. {
  115. return false;
  116. }
  117. if (!Pattern.IsEmpty())
  118. {
  119. FRegexPattern CustomPattern(Pattern);
  120. return FFileHelper::LoadFileToStringArrayWithPredicate(Lines, *Path, [CustomPattern](const FString& Line) {
  121. FRegexMatcher CustomMatcher(CustomPattern, Line);
  122. return CustomMatcher.FindNext();
  123. });
  124. }
  125. return FFileHelper::LoadFileToStringArray(Lines, *Path);
  126. }
  127. bool UFileHelperBPLibrary::ReadLineRange(FString Path, TArray<FString>& Lines, int32 StartIdx, int32 EndIdx)
  128. {
  129. if (EndIdx != INDEX_NONE && EndIdx < StartIdx)
  130. {
  131. return false;
  132. }
  133. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  134. if (!FileManager.FileExists(*Path))
  135. {
  136. return false;
  137. }
  138. int32 LineCount = 0;
  139. return FFileHelper::LoadFileToStringArrayWithPredicate(Lines, *Path, [&LineCount, StartIdx, EndIdx](const FString& Line)->bool{
  140. const bool bRangeStart = LineCount >= StartIdx;
  141. const bool bRangeEnd = EndIdx == INDEX_NONE || LineCount < EndIdx;
  142. LineCount++;
  143. return bRangeStart && bRangeEnd;
  144. });
  145. }
  146. bool UFileHelperBPLibrary::SaveLine(FString Path, const TArray<FString>& Text, FString& Error, bool Append, bool Force)
  147. {
  148. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  149. FText ErrorFilename;
  150. if (!FFileHelper::IsFilenameValidForSaving(Path, ErrorFilename))
  151. {
  152. Error = FString("Filename is not valid");
  153. return false;
  154. }
  155. if (!FileManager.FileExists(*Path) || Append || Force)
  156. {
  157. return FFileHelper::SaveStringArrayToFile(Text, *Path, FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), Append ? FILEWRITE_Append : FILEWRITE_None);
  158. }
  159. else
  160. {
  161. Error = FString("File already exists");
  162. }
  163. return false;
  164. }
  165. bool UFileHelperBPLibrary::ReadByte(FString Path, TArray<uint8>& Bytes)
  166. {
  167. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  168. if (!FileManager.FileExists(*Path))
  169. {
  170. return false;
  171. }
  172. return FFileHelper::LoadFileToArray(Bytes, *Path);
  173. }
  174. FString UFileHelperBPLibrary::BytesToBase64(const TArray<uint8> Bytes)
  175. {
  176. return FBase64::Encode(Bytes);
  177. }
  178. bool UFileHelperBPLibrary::BytesFromBase64(const FString Source, TArray<uint8>& Out)
  179. {
  180. return FBase64::Decode(Source, Out);
  181. }
  182. bool UFileHelperBPLibrary::SaveByte(FString Path, const TArray<uint8>& Bytes, FString& Error, bool Append, bool Force)
  183. {
  184. IPlatformFile& file = FPlatformFileManager::Get().GetPlatformFile();
  185. FText ErrorFilename;
  186. if (!FFileHelper::IsFilenameValidForSaving(Path, ErrorFilename))
  187. {
  188. Error = FString("Filename is not valid");
  189. return false;
  190. }
  191. if (!file.FileExists(*Path) || Append || Force)
  192. {
  193. return FFileHelper::SaveArrayToFile(Bytes, *Path, &IFileManager::Get(), Append ? FILEWRITE_Append : FILEWRITE_None);
  194. }
  195. else
  196. {
  197. Error = FString("File already exists");
  198. }
  199. return false;
  200. }
  201. bool UFileHelperBPLibrary::StringToCSV(FString Content, TArray<FString>& Headers, TArray<FString>& Data, int32& Total, bool HeaderFirst)
  202. {
  203. const FCsvParser Parser(Content);
  204. TArray<TArray<const TCHAR*>> Rows = Parser.GetRows();
  205. for (TArray<const TCHAR*> Row : Rows)
  206. {
  207. Total++;
  208. for (FString Col : Row)
  209. {
  210. if (Total == 1 && HeaderFirst)
  211. {
  212. Headers.Add(Col);
  213. }
  214. else
  215. {
  216. Data.Add(Col);
  217. }
  218. }
  219. }
  220. return true;
  221. // auto Result = SplitString(Content, LINE_TERMINATOR, ESearchCase::Type::IgnoreCase);
  222. // return UFileHelperBPLibrary::StringArrayToCSV(Result, Headers, Data, Total, HeaderFirst);
  223. }
  224. bool UFileHelperBPLibrary::CSVToString(FString& Output, TArray<FString> Headers, TArray<FString> Data, int32& Total)
  225. {
  226. Total = 0;
  227. FString Delimiter = ",";
  228. if (Headers.Num() == 0)
  229. {
  230. return false;
  231. }
  232. if (Data.Num() % Headers.Num() != 0)
  233. {
  234. return false;
  235. }
  236. Output = TEXT("");
  237. // Header row
  238. for (FString Col : Headers)
  239. {
  240. if (Output.Len() > 0)
  241. {
  242. Output += Delimiter;
  243. }
  244. Output += (TEXT("\"") + Col.Replace(TEXT("\""), TEXT("\"\"")) + TEXT("\""));
  245. }
  246. Output += LINE_TERMINATOR;
  247. FString Row = TEXT("");
  248. int32 Count = 0;
  249. // Data row
  250. for (FString Col : Data)
  251. {
  252. Count++;
  253. if (Row.Len() > 0)
  254. {
  255. Row += Delimiter;
  256. }
  257. Row += (TEXT("\"") + Col.Replace(TEXT("\""), TEXT("\"\"")) + TEXT("\""));
  258. if (Count % Headers.Num() == 0)
  259. {
  260. Row += LINE_TERMINATOR;
  261. Output += Row;
  262. Row = "";
  263. }
  264. }
  265. Total = (Data.Num() / Headers.Num()) + 1;
  266. return true;
  267. }
  268. bool UFileHelperBPLibrary::StringArrayToCSV(TArray<FString> Lines, TArray<FString>& Headers, TArray<FString>& Data, int32& Total, FString Delimiter, bool HeaderFirst)
  269. {
  270. for (auto Line : Lines)
  271. {
  272. Total++;
  273. if (!Line.Contains(TEXT("\"") + Delimiter + TEXT("\"")))
  274. {
  275. continue;
  276. }
  277. if (Total == 1 && HeaderFirst)
  278. {
  279. for (FString Col : UFileHelperBPLibrary::SplitString(Line, TEXT("\"") + Delimiter + TEXT("\""), ESearchCase::CaseSensitive))
  280. {
  281. Col.TrimQuotesInline();
  282. Col.ReplaceInline(TEXT("\"\""), TEXT("\""));
  283. Headers.Add(Col);
  284. }
  285. }
  286. else
  287. {
  288. for (FString Col : UFileHelperBPLibrary::SplitString(Line, TEXT("\"") + Delimiter + TEXT("\""), ESearchCase::CaseSensitive))
  289. {
  290. Col.TrimQuotesInline();
  291. Col.ReplaceInline(TEXT("\"\""), TEXT("\""));
  292. Data.Add(Col);
  293. }
  294. }
  295. }
  296. return true;
  297. }
  298. bool UFileHelperBPLibrary::IsFile(FString Path)
  299. {
  300. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  301. return FileManager.FileExists(*Path);
  302. }
  303. bool UFileHelperBPLibrary::IsDirectory(FString Path)
  304. {
  305. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  306. return FileManager.DirectoryExists(*Path);
  307. }
  308. bool UFileHelperBPLibrary::IsValidFilename(FString Filename)
  309. {
  310. FText Error;
  311. return FFileHelper::IsFilenameValidForSaving(*Filename, Error);
  312. }
  313. bool UFileHelperBPLibrary::IsValidPath(FString Path)
  314. {
  315. return FPaths::ValidatePath(Path);
  316. }
  317. bool UFileHelperBPLibrary::ValidateFilename(FString Filename, FString& ValidName)
  318. {
  319. ValidName = FPaths::MakeValidFileName(Filename);
  320. return IsValidFilename(ValidName);
  321. }
  322. bool UFileHelperBPLibrary::SetReadOnlyFlag(FString FilePath, bool Flag)
  323. {
  324. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  325. return FileManager.SetReadOnly(*FilePath, Flag);
  326. }
  327. bool UFileHelperBPLibrary::GetReadOnlyFlag(FString FilePath)
  328. {
  329. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  330. return FileManager.IsReadOnly(*FilePath);
  331. }
  332. int64 UFileHelperBPLibrary::GetFileSize(FString FilePath)
  333. {
  334. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  335. return FileManager.FileSize(*FilePath);
  336. }
  337. bool FCustomFileVisitor::Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory)
  338. {
  339. if ((bFile && !bIsDirectory) || (bDirectory && bIsDirectory))
  340. {
  341. FString RelativePath = FString(FilenameOrDirectory);
  342. FPaths::MakePathRelativeTo(RelativePath, *BasePath);
  343. if (!Filter.IsEmpty())
  344. {
  345. FRegexMatcher CustomMatcher(CustomPattern, RelativePath);
  346. if (CustomMatcher.FindNext())
  347. {
  348. Nodes.Add(RelativePath);
  349. }
  350. }
  351. else
  352. {
  353. Nodes.Add(RelativePath);
  354. }
  355. }
  356. return true;
  357. }
  358. bool UFileHelperBPLibrary::ListDirectory(FString Path, FString Pattern, TArray<FString>& Nodes, bool ShowFile, bool ShowDirectory, bool Recursive)
  359. {
  360. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  361. if (!FileManager.DirectoryExists(*Path))
  362. {
  363. return false;
  364. }
  365. if (!ShowDirectory && !ShowFile)
  366. {
  367. return true;
  368. }
  369. FString BasePath = FPaths::Combine(Path, TEXT("/"));
  370. FCustomFileVisitor CustomFileVisitor(BasePath, Nodes, Pattern, ShowFile, ShowDirectory);
  371. if (Recursive)
  372. {
  373. return FileManager.IterateDirectoryRecursively(*Path, CustomFileVisitor);
  374. }
  375. else
  376. {
  377. return FileManager.IterateDirectory(*Path, CustomFileVisitor);
  378. }
  379. }
  380. bool UFileHelperBPLibrary::MakeDirectory(FString Path, bool Recursive)
  381. {
  382. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  383. if (FileManager.DirectoryExists(*Path))
  384. {
  385. return true;
  386. }
  387. if (Recursive)
  388. {
  389. return FileManager.CreateDirectoryTree(*Path);
  390. }
  391. else
  392. {
  393. return FileManager.CreateDirectory(*Path);
  394. }
  395. }
  396. bool UFileHelperBPLibrary::RemoveDirectory(FString Path, bool Recursive)
  397. {
  398. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  399. if (!FileManager.DirectoryExists(*Path))
  400. {
  401. return true;
  402. }
  403. if (Recursive)
  404. {
  405. return FileManager.DeleteDirectoryRecursively(*Path);
  406. }
  407. else
  408. {
  409. return FileManager.DeleteDirectory(*Path);
  410. }
  411. }
  412. bool UFileHelperBPLibrary::CopyDirectory(FString Source, FString Dest) // bool Force = false
  413. {
  414. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  415. FPaths::NormalizeDirectoryName(Dest);
  416. if (!FileManager.DirectoryExists(*Source) && !FileManager.FileExists(*Source))
  417. {
  418. return false;
  419. }
  420. if (!FileManager.DirectoryExists(*Dest))
  421. {
  422. return false;
  423. }
  424. return FileManager.CopyDirectoryTree(*Dest, *Source, true);
  425. }
  426. bool UFileHelperBPLibrary::MoveDirectory(FString Source, FString Dest) // bool Force = false
  427. {
  428. FPaths::NormalizeDirectoryName(Source);
  429. FPaths::NormalizeDirectoryName(Dest);
  430. if (Dest.Equals(Source))
  431. {
  432. return true;
  433. }
  434. if (!UFileHelperBPLibrary::CopyDirectory(Source, Dest))
  435. {
  436. return false;
  437. }
  438. return UFileHelperBPLibrary::RemoveDirectory(Source, true);
  439. }
  440. bool UFileHelperBPLibrary::NodeStats(FString Path, FCustomNodeStat& Stats)
  441. {
  442. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  443. if (!FileManager.DirectoryExists(*Path) && !FileManager.FileExists(*Path))
  444. {
  445. return false;
  446. }
  447. const FFileStatData Data = FileManager.GetStatData(*Path);
  448. if (!Data.bIsValid)
  449. {
  450. return false;
  451. }
  452. Stats.CreationTime = Data.CreationTime;
  453. Stats.FileSize = Data.FileSize;
  454. Stats.IsDirectory = Data.bIsDirectory;
  455. Stats.IsReadOnly = Data.bIsReadOnly;
  456. Stats.LastAccessTime = Data.AccessTime;
  457. Stats.ModificationTime = Data.ModificationTime;
  458. return true;
  459. }
  460. bool UFileHelperBPLibrary::RemoveFile(FString Path)
  461. {
  462. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  463. if (FileManager.DirectoryExists(*Path))
  464. {
  465. return false;
  466. }
  467. if (!FileManager.FileExists(*Path))
  468. {
  469. return true;
  470. }
  471. return FileManager.DeleteFile(*Path);
  472. }
  473. bool UFileHelperBPLibrary::CopyFile(FString Source, FString Dest, bool Force)
  474. {
  475. FPaths::NormalizeFilename(Source);
  476. FPaths::NormalizeFilename(Dest);
  477. if (Dest.Equals(Source))
  478. {
  479. return true;
  480. }
  481. FText Error;
  482. if (!FFileHelper::IsFilenameValidForSaving(*Dest, Error))
  483. {
  484. return false;
  485. }
  486. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  487. if (!FileManager.FileExists(*Source))
  488. {
  489. return false;
  490. }
  491. if (!Force && FileManager.FileExists(*Dest))
  492. {
  493. return false;
  494. }
  495. UFileHelperBPLibrary::RemoveFile(Dest);
  496. return FileManager.CopyFile(*Dest, *Source);
  497. }
  498. bool UFileHelperBPLibrary::MoveFile(FString Source, FString Dest, bool Force)
  499. {
  500. FPaths::NormalizeFilename(Source);
  501. FPaths::NormalizeFilename(Dest);
  502. if (Dest.Equals(Source))
  503. {
  504. return true;
  505. }
  506. FText Error;
  507. if (!FFileHelper::IsFilenameValidForSaving(*Dest, Error))
  508. {
  509. return false;
  510. }
  511. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  512. if (!FileManager.FileExists(*Source))
  513. {
  514. return false;
  515. }
  516. if (!Force && FileManager.FileExists(*Dest))
  517. {
  518. return false;
  519. }
  520. UFileHelperBPLibrary::RemoveFile(Dest);
  521. return FileManager.MoveFile(*Dest, *Source);
  522. }
  523. bool UFileHelperBPLibrary::RenameFile(FString Path, FString NewName)
  524. {
  525. FText Error;
  526. if (!FFileHelper::IsFilenameValidForSaving(*NewName, Error))
  527. {
  528. return false;
  529. }
  530. IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
  531. if (!FileManager.FileExists(*Path))
  532. {
  533. return false;
  534. }
  535. FString Clean = FPaths::GetCleanFilename(NewName);
  536. FString Base = FPaths::GetPath(Path);
  537. FString Output = FPaths::Combine(*Base, *Clean);
  538. if (FileManager.FileExists(*Output) || FileManager.DirectoryExists(*Output))
  539. {
  540. return false;
  541. }
  542. return FileManager.MoveFile(*Output, *Path);
  543. }
  544. void UFileHelperBPLibrary::GetPathParts(FString Path, FString& PathPart, FString& BasePart, FString& ExtensionPart, FString& FileName)
  545. {
  546. PathPart = FPaths::GetPath(Path);
  547. BasePart = FPaths::GetBaseFilename(Path);
  548. ExtensionPart = FPaths::GetExtension(Path);
  549. FileName = FPaths::GetCleanFilename(Path);
  550. }
  551. bool UFileHelperBPLibrary::DatatableToCSV(UDataTable* Table, FString& Output)
  552. {
  553. if (Table == nullptr || !Table->RowStruct)
  554. {
  555. return false;
  556. }
  557. // See Table->GetTableAsCSV
  558. return UFileHelperBPLibrary::WriteTableToCSV(*Table, Output);
  559. }
  560. bool UFileHelperBPLibrary::DataTableToJSON(UDataTable* Table, FString& Output)
  561. {
  562. if (Table == nullptr || !Table->RowStruct)
  563. {
  564. return false;
  565. }
  566. // See Table->GetTableAsJSON
  567. return UFileHelperBPLibrary::WriteTableToJSON(*Table, Output);
  568. }
  569. UDataTable* UFileHelperBPLibrary::CSVToDataTable(FString CSV, UScriptStruct* Struct, bool& Success)
  570. {
  571. Success = false;
  572. if (Struct == nullptr)
  573. {
  574. return nullptr;
  575. }
  576. UDataTable* DataTable = NewObject<UDataTable>();
  577. DataTable->RowStruct = Struct;
  578. auto Result = DataTable->CreateTableFromCSVString(CSV);
  579. if (Result.Num() == 0)
  580. {
  581. Success = true;
  582. }
  583. return DataTable;
  584. }
  585. UDataTable* UFileHelperBPLibrary::JSONToDataTable(FString JSON, UScriptStruct* Struct, bool& Success)
  586. {
  587. Success = false;
  588. if (Struct == nullptr)
  589. {
  590. return nullptr;
  591. }
  592. UDataTable* DataTable = NewObject<UDataTable>();
  593. DataTable->RowStruct = Struct;
  594. auto Result = DataTable->CreateTableFromJSONString(JSON);
  595. if (Result.Num() == 0)
  596. {
  597. Success = true;
  598. }
  599. return DataTable;
  600. }
  601. void UFileHelperBPLibrary::ReadConfig(FString FilePath, FString Section, FString Key, bool& Success, bool SingleLineArrayRead, UStruct*& OutValue, bool bLoadFromDisk)
  602. {
  603. checkNoEntry();
  604. }
  605. TArray<FString> UFileHelperBPLibrary::SplitString(FString String, FString Separator, ESearchCase::Type SearchCase)
  606. {
  607. FString LeftString;
  608. FString RightString;
  609. TArray<FString> Array;
  610. bool Split = false;
  611. do
  612. {
  613. Split = String.Split(Separator, &LeftString, &RightString, SearchCase);
  614. if (Split)
  615. {
  616. Array.Add(LeftString);
  617. }
  618. else
  619. {
  620. Array.Add(String);
  621. }
  622. String = RightString;
  623. } while (Split);
  624. return Array;
  625. }
  626. bool UFileHelperBPLibrary::WriteConfigFile(FString Filename, FString Section, FString Key, FProperty* Type, void* Value, bool SingleLineArray, bool bWriteToDisk)
  627. {
  628. if (!GConfig)
  629. {
  630. return false;
  631. }
  632. if (FBoolProperty* BoolProperty = CastField<FBoolProperty>(Type))
  633. {
  634. GConfig->SetBool(*Section, *Key, *(static_cast<bool*>(Value)), Filename);
  635. }
  636. else if (FIntProperty* IntProperty = CastField<FIntProperty>(Type))
  637. {
  638. GConfig->SetInt(*Section, *Key, *(static_cast<int32*>(Value)), Filename);
  639. }
  640. else if (FStrProperty* StrProperty = CastField<FStrProperty>(Type))
  641. {
  642. GConfig->SetString(*Section, *Key, **(static_cast<FString*>(Value)), Filename);
  643. }
  644. else if (FFloatProperty* FloatProperty = CastField<FFloatProperty>(Type))
  645. {
  646. GConfig->SetFloat(*Section, *Key, *(static_cast<float*>(Value)), Filename);
  647. }
  648. else if (FDoubleProperty* DoubleProperty = CastField<FDoubleProperty>(Type))
  649. {
  650. GConfig->SetDouble(*Section, *Key, *(static_cast<double*>(Value)), Filename);
  651. }
  652. else if (FArrayProperty* ArrayProperty = CastField<FArrayProperty>(Type))
  653. {
  654. if (FStrProperty* ArrayInnerProperty = CastField<FStrProperty>(ArrayProperty->Inner))
  655. {
  656. TArray<FString>* Arr = (static_cast<TArray<FString>*>(Value));
  657. if (SingleLineArray)
  658. {
  659. GConfig->SetSingleLineArray(*Section, *Key, *Arr, Filename);
  660. }
  661. else
  662. {
  663. GConfig->SetArray(*Section, *Key, *Arr, Filename);
  664. }
  665. }
  666. else
  667. {
  668. return false;
  669. }
  670. }
  671. else if (FTextProperty* TextProperty = CastField<FTextProperty>(Type))
  672. {
  673. GConfig->SetText(*Section, *Key, *(static_cast<FText*>(Value)), Filename);
  674. }
  675. else if (FStructProperty* StructProperty = CastField<FStructProperty>(Type))
  676. {
  677. if (StructProperty->Struct->IsNative())
  678. {
  679. static const FName RotatorType = TEXT("Rotator");
  680. static const FName VectorType = TEXT("Vector");
  681. static const FName LinearColorType = TEXT("LinearColor");
  682. static const FName Vector4Type = TEXT("Vector4");
  683. static const FName Vector2DType = TEXT("Vector2D");
  684. const FName TypeName = StructProperty->Struct->GetFName();
  685. if (TypeName == RotatorType)
  686. {
  687. GConfig->SetRotator(*Section, *Key, *(static_cast<FRotator*>(Value)), *Filename);
  688. }
  689. else if (TypeName == VectorType)
  690. {
  691. GConfig->SetVector(*Section, *Key, *(static_cast<FVector*>(Value)), *Filename);
  692. }
  693. else if (TypeName == LinearColorType)
  694. {
  695. GConfig->SetColor(*Section, *Key, *(static_cast<FColor*>(Value)), *Filename);
  696. }
  697. else if (TypeName == Vector4Type)
  698. {
  699. GConfig->SetVector4(*Section, *Key, *(static_cast<FVector4*>(Value)), *Filename);
  700. }
  701. else if (TypeName == Vector2DType)
  702. {
  703. GConfig->SetVector2D(*Section, *Key, *(static_cast<FVector2D*>(Value)), *Filename);
  704. }
  705. else
  706. {
  707. return false;
  708. }
  709. }
  710. else
  711. {
  712. return false;
  713. }
  714. }
  715. else
  716. {
  717. return false;
  718. }
  719. if (bWriteToDisk)
  720. {
  721. GConfig->Flush(false, Filename);
  722. }
  723. return true;
  724. }
  725. bool UFileHelperBPLibrary::ReadConfigFile(FString Filename, FString Section, FString Key, FProperty* Type, void* Value, bool SingleLineArray, bool bLoadFromDisk)
  726. {
  727. if (!GConfig)
  728. {
  729. return false;
  730. }
  731. if (bLoadFromDisk)
  732. {
  733. FConfigFile* ConfigFile = GConfig->FindConfigFile(Filename);
  734. if (!ConfigFile)
  735. {
  736. return false;
  737. }
  738. ConfigFile->Read(Filename);
  739. }
  740. bool Success = false;
  741. if (FBoolProperty* BoolProperty = CastField<FBoolProperty>(Type))
  742. {
  743. Success = GConfig->GetBool(*Section, *Key, *(static_cast<bool*>(Value)), Filename);
  744. }
  745. else if (FIntProperty* IntProperty = CastField<FIntProperty>(Type))
  746. {
  747. Success = GConfig->GetInt(*Section, *Key, *(static_cast<int32*>(Value)), Filename);
  748. }
  749. else if (FStrProperty* StrProperty = CastField<FStrProperty>(Type))
  750. {
  751. Success = GConfig->GetString(*Section, *Key, *(static_cast<FString*>(Value)), Filename);
  752. }
  753. else if (FFloatProperty* FloatProperty = CastField<FFloatProperty>(Type))
  754. {
  755. Success = GConfig->GetFloat(*Section, *Key, *(static_cast<float*>(Value)), Filename);
  756. }
  757. else if (FDoubleProperty* DoubleProperty = CastField<FDoubleProperty>(Type))
  758. {
  759. Success = GConfig->GetDouble(*Section, *Key, *(static_cast<double*>(Value)), Filename);
  760. }
  761. else if (FArrayProperty* ArrayProperty = CastField<FArrayProperty>(Type))
  762. {
  763. if (FStrProperty* ArrayInnerProperty = CastField<FStrProperty>(ArrayProperty->Inner))
  764. {
  765. TArray<FString>* Arr = (static_cast<TArray<FString>*>(Value));
  766. if (SingleLineArray)
  767. {
  768. Success = (GConfig->GetSingleLineArray(*Section, *Key, *Arr, Filename) != 0);
  769. }
  770. else
  771. {
  772. Success = (GConfig->GetArray(*Section, *Key, *Arr, Filename) != 0);
  773. }
  774. }
  775. }
  776. else if (FTextProperty* TextProperty = CastField<FTextProperty>(Type))
  777. {
  778. Success = GConfig->GetText(*Section, *Key, *(static_cast<FText*>(Value)), Filename);
  779. }
  780. else if (FStructProperty* StructProperty = CastField<FStructProperty>(Type))
  781. {
  782. if (StructProperty->Struct->IsNative())
  783. {
  784. static const FName RotatorType = TEXT("Rotator");
  785. static const FName VectorType = TEXT("Vector");
  786. static const FName LinearColorType = TEXT("LinearColor");
  787. static const FName Vector4Type = TEXT("Vector4");
  788. static const FName Vector2DType = TEXT("Vector2D");
  789. const FName TypeName = StructProperty->Struct->GetFName();
  790. if (TypeName == RotatorType)
  791. {
  792. Success = GConfig->GetRotator(*Section, *Key, *(static_cast<FRotator*>(Value)), *Filename);
  793. }
  794. else if (TypeName == VectorType)
  795. {
  796. Success = GConfig->GetVector(*Section, *Key, *(static_cast<FVector*>(Value)), *Filename);
  797. }
  798. else if (TypeName == LinearColorType)
  799. {
  800. Success = GConfig->GetColor(*Section, *Key, *(static_cast<FColor*>(Value)), *Filename);
  801. }
  802. else if (TypeName == Vector4Type)
  803. {
  804. Success = GConfig->GetVector4(*Section, *Key, *(static_cast<FVector4*>(Value)), *Filename);
  805. }
  806. else if (TypeName == Vector2DType)
  807. {
  808. Success = GConfig->GetVector2D(*Section, *Key, *(static_cast<FVector2D*>(Value)), *Filename);
  809. }
  810. }
  811. }
  812. return Success;
  813. }
  814. void UFileHelperBPLibrary::WriteConfig(FString FilePath, FString Section, FString Key, bool& Success, bool SingleLineArrayWrite, const UStruct* Value, bool bWriteToDisk)
  815. {
  816. checkNoEntry();
  817. }
  818. bool UFileHelperBPLibrary::RemoveConfig(FString FilePath, FString Section, FString Key, bool bWriteToDisk)
  819. {
  820. if (!GConfig)
  821. {
  822. return false;
  823. }
  824. if (!GConfig->RemoveKey(*Section, *Key, *FilePath))
  825. {
  826. return false;
  827. }
  828. if (bWriteToDisk)
  829. {
  830. GConfig->Flush(false, FilePath);
  831. }
  832. return true;
  833. }
  834. // equivalent GetTableAsCSV()
  835. bool UFileHelperBPLibrary::WriteTableToCSV(const UDataTable& InDataTable, FString& ExportedText)
  836. {
  837. if (!InDataTable.RowStruct)
  838. {
  839. return false;
  840. }
  841. // Write the header (column titles)
  842. FString ImportKeyField;
  843. if (!InDataTable.ImportKeyField.IsEmpty())
  844. {
  845. // Write actual name if we have it
  846. ImportKeyField = InDataTable.ImportKeyField;
  847. ExportedText += ImportKeyField;
  848. }
  849. else
  850. {
  851. ExportedText += TEXT("---");
  852. }
  853. FProperty* SkipProperty = nullptr;
  854. for (TFieldIterator<FProperty> It(InDataTable.RowStruct); It; ++It)
  855. {
  856. FProperty* BaseProp = *It;
  857. check(BaseProp);
  858. FString ColumnHeader = DataTableUtils::GetPropertyExportName(BaseProp, EDataTableExportFlags::None);
  859. if (ColumnHeader == ImportKeyField)
  860. {
  861. // Don't write header again if this is the name field, and save for skipping later
  862. SkipProperty = BaseProp;
  863. continue;
  864. }
  865. ExportedText += TEXT(",");
  866. ExportedText += ColumnHeader;
  867. }
  868. ExportedText += TEXT("\n");
  869. // Write each row
  870. for (auto RowIt = InDataTable.GetRowMap().CreateConstIterator(); RowIt; ++RowIt)
  871. {
  872. FName RowName = RowIt.Key();
  873. ExportedText += RowName.ToString();
  874. uint8* RowData = RowIt.Value();
  875. UFileHelperBPLibrary::WriteRowToCSV(InDataTable.RowStruct, RowData, ExportedText);
  876. ExportedText += TEXT("\n");
  877. }
  878. return true;
  879. }
  880. bool UFileHelperBPLibrary::WriteRowToCSV(const UScriptStruct* InRowStruct, const void* InRowData, FString& ExportedText)
  881. {
  882. if (!InRowStruct)
  883. {
  884. return false;
  885. }
  886. for (TFieldIterator<FProperty> It(InRowStruct); It; ++It)
  887. {
  888. FProperty* BaseProp = *It;
  889. check(BaseProp);
  890. const void* Data = BaseProp->ContainerPtrToValuePtr<void>(InRowData, 0);
  891. UFileHelperBPLibrary::WriteStructEntryToCSV(InRowData, BaseProp, Data, ExportedText);
  892. }
  893. return true;
  894. }
  895. bool UFileHelperBPLibrary::WriteStructEntryToCSV(const void* InRowData, FProperty* InProperty, const void* InPropertyData, FString& ExportedText)
  896. {
  897. ExportedText += TEXT(",");
  898. const FString PropertyValue = DataTableUtils::GetPropertyValueAsString(InProperty, (uint8*)InRowData, EDataTableExportFlags::None);
  899. ExportedText += TEXT("\"");
  900. ExportedText += PropertyValue.Replace(TEXT("\""), TEXT("\"\""));
  901. ExportedText += TEXT("\"");
  902. return true;
  903. }
  904. // equivalent GetTableAsJSON()
  905. FString UFileHelperBPLibrary::GetKeyFieldName(const UDataTable& InDataTable)
  906. {
  907. FString ExplicitString = InDataTable.ImportKeyField;
  908. if (ExplicitString.IsEmpty())
  909. {
  910. return TEXT("Name");
  911. }
  912. else
  913. {
  914. return ExplicitString;
  915. }
  916. }
  917. bool UFileHelperBPLibrary::WriteTableToJSON(const UDataTable& InDataTable, FString& OutExportText)
  918. {
  919. if (!InDataTable.RowStruct)
  920. {
  921. return false;
  922. }
  923. TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&OutExportText);
  924. FString KeyField = UFileHelperBPLibrary::GetKeyFieldName(InDataTable);
  925. JsonWriter->WriteArrayStart();
  926. // Iterate over rows
  927. for (auto RowIt = InDataTable.GetRowMap().CreateConstIterator(); RowIt; ++RowIt)
  928. {
  929. JsonWriter->WriteObjectStart();
  930. {
  931. // RowName
  932. const FName RowName = RowIt.Key();
  933. JsonWriter->WriteValue(KeyField, RowName.ToString());
  934. // Now the values
  935. uint8* RowData = RowIt.Value();
  936. UFileHelperBPLibrary::WriteRowToJSON(InDataTable.RowStruct, RowData, JsonWriter);
  937. }
  938. JsonWriter->WriteObjectEnd();
  939. }
  940. JsonWriter->WriteArrayEnd();
  941. JsonWriter->Close();
  942. return true;
  943. }
  944. bool UFileHelperBPLibrary::WriteTableAsObjectToJSON(const UDataTable& InDataTable, TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter)
  945. {
  946. if (!InDataTable.RowStruct)
  947. {
  948. return false;
  949. }
  950. JsonWriter->WriteObjectStart(InDataTable.GetName());
  951. // Iterate over rows
  952. for (auto RowIt = InDataTable.GetRowMap().CreateConstIterator(); RowIt; ++RowIt)
  953. {
  954. // RowName
  955. const FName RowName = RowIt.Key();
  956. JsonWriter->WriteObjectStart(RowName.ToString());
  957. {
  958. // Now the values
  959. uint8* RowData = RowIt.Value();
  960. UFileHelperBPLibrary::WriteRowToJSON(InDataTable.RowStruct, RowData, JsonWriter);
  961. }
  962. JsonWriter->WriteObjectEnd();
  963. }
  964. JsonWriter->WriteObjectEnd();
  965. return true;
  966. }
  967. bool UFileHelperBPLibrary::WriteRowToJSON(const UScriptStruct* InRowStruct, const void* InRowData, TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter)
  968. {
  969. if (!InRowStruct)
  970. {
  971. return false;
  972. }
  973. return UFileHelperBPLibrary::WriteStructToJSON(InRowStruct, InRowData, JsonWriter);
  974. }
  975. bool UFileHelperBPLibrary::WriteStructToJSON(const UScriptStruct* InStruct, const void* InStructData, TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter)
  976. {
  977. for (TFieldIterator<const FProperty> It(InStruct); It; ++It)
  978. {
  979. const FProperty* BaseProp = *It;
  980. check(BaseProp);
  981. const FString Identifier = DataTableUtils::GetPropertyExportName(BaseProp, EDataTableExportFlags::UseJsonObjectsForStructs);
  982. if (BaseProp->ArrayDim == 1)
  983. {
  984. const void* Data = BaseProp->ContainerPtrToValuePtr<void>(InStructData, 0);
  985. UFileHelperBPLibrary::WriteStructEntryToJSON(InStructData, BaseProp, Data, JsonWriter);
  986. }
  987. else
  988. {
  989. JsonWriter->WriteArrayStart(Identifier);
  990. for (int32 ArrayEntryIndex = 0; ArrayEntryIndex < BaseProp->ArrayDim; ++ArrayEntryIndex)
  991. {
  992. const void* Data = BaseProp->ContainerPtrToValuePtr<void>(InStructData, ArrayEntryIndex);
  993. UFileHelperBPLibrary::WriteContainerEntryToJSON(BaseProp, Data, &Identifier, JsonWriter);
  994. }
  995. JsonWriter->WriteArrayEnd();
  996. }
  997. }
  998. return true;
  999. }
  1000. bool UFileHelperBPLibrary::WriteStructEntryToJSON(const void* InRowData, const FProperty* InProperty, const void* InPropertyData, TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter)
  1001. {
  1002. const FString Identifier = DataTableUtils::GetPropertyExportName(InProperty, EDataTableExportFlags::UseJsonObjectsForStructs);
  1003. if (const FEnumProperty* EnumProp = CastField<const FEnumProperty>(InProperty))
  1004. {
  1005. const FString PropertyValue = DataTableUtils::GetPropertyValueAsString(EnumProp, (uint8*)InRowData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1006. JsonWriter->WriteValue(Identifier, PropertyValue);
  1007. }
  1008. else if (const FNumericProperty* NumProp = CastField<const FNumericProperty>(InProperty))
  1009. {
  1010. if (NumProp->IsEnum())
  1011. {
  1012. const FString PropertyValue = DataTableUtils::GetPropertyValueAsString(InProperty, (uint8*)InRowData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1013. JsonWriter->WriteValue(Identifier, PropertyValue);
  1014. }
  1015. else if (NumProp->IsInteger())
  1016. {
  1017. const int64 PropertyValue = NumProp->GetSignedIntPropertyValue(InPropertyData);
  1018. JsonWriter->WriteValue(Identifier, PropertyValue);
  1019. }
  1020. else
  1021. {
  1022. const double PropertyValue = NumProp->GetFloatingPointPropertyValue(InPropertyData);
  1023. JsonWriter->WriteValue(Identifier, PropertyValue);
  1024. }
  1025. }
  1026. else if (const FBoolProperty* BoolProp = CastField<const FBoolProperty>(InProperty))
  1027. {
  1028. const bool PropertyValue = BoolProp->GetPropertyValue(InPropertyData);
  1029. JsonWriter->WriteValue(Identifier, PropertyValue);
  1030. }
  1031. else if (const FArrayProperty* ArrayProp = CastField<const FArrayProperty>(InProperty))
  1032. {
  1033. JsonWriter->WriteArrayStart(Identifier);
  1034. FScriptArrayHelper ArrayHelper(ArrayProp, InPropertyData);
  1035. for (int32 ArrayEntryIndex = 0; ArrayEntryIndex < ArrayHelper.Num(); ++ArrayEntryIndex)
  1036. {
  1037. const uint8* ArrayEntryData = ArrayHelper.GetRawPtr(ArrayEntryIndex);
  1038. UFileHelperBPLibrary::WriteContainerEntryToJSON(ArrayProp->Inner, ArrayEntryData, &Identifier, JsonWriter);
  1039. }
  1040. JsonWriter->WriteArrayEnd();
  1041. }
  1042. else if (const FSetProperty* SetProp = CastField<const FSetProperty>(InProperty))
  1043. {
  1044. JsonWriter->WriteArrayStart(Identifier);
  1045. FScriptSetHelper SetHelper(SetProp, InPropertyData);
  1046. for (int32 SetSparseIndex = 0; SetSparseIndex < SetHelper.GetMaxIndex(); ++SetSparseIndex)
  1047. {
  1048. if (SetHelper.IsValidIndex(SetSparseIndex))
  1049. {
  1050. const uint8* SetEntryData = SetHelper.GetElementPtr(SetSparseIndex);
  1051. UFileHelperBPLibrary::WriteContainerEntryToJSON(SetHelper.GetElementProperty(), SetEntryData, &Identifier, JsonWriter);
  1052. }
  1053. }
  1054. JsonWriter->WriteArrayEnd();
  1055. }
  1056. else if (const FMapProperty* MapProp = CastField<const FMapProperty>(InProperty))
  1057. {
  1058. JsonWriter->WriteObjectStart(Identifier);
  1059. FScriptMapHelper MapHelper(MapProp, InPropertyData);
  1060. for (int32 MapSparseIndex = 0; MapSparseIndex < MapHelper.GetMaxIndex(); ++MapSparseIndex)
  1061. {
  1062. if (MapHelper.IsValidIndex(MapSparseIndex))
  1063. {
  1064. const uint8* MapKeyData = MapHelper.GetKeyPtr(MapSparseIndex);
  1065. const uint8* MapValueData = MapHelper.GetValuePtr(MapSparseIndex);
  1066. // JSON object keys must always be strings
  1067. const FString KeyValue = DataTableUtils::GetPropertyValueAsStringDirect(MapHelper.GetKeyProperty(), (uint8*)MapKeyData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1068. UFileHelperBPLibrary::WriteContainerEntryToJSON(MapHelper.GetValueProperty(), MapValueData, &KeyValue, JsonWriter);
  1069. }
  1070. }
  1071. JsonWriter->WriteObjectEnd();
  1072. }
  1073. else if (const FStructProperty* StructProp = CastField<const FStructProperty>(InProperty))
  1074. {
  1075. JsonWriter->WriteObjectStart(Identifier);
  1076. UFileHelperBPLibrary::WriteStructToJSON(StructProp->Struct, InPropertyData, JsonWriter);
  1077. JsonWriter->WriteObjectEnd();
  1078. }
  1079. else
  1080. {
  1081. const FString PropertyValue = DataTableUtils::GetPropertyValueAsString(InProperty, (uint8*)InRowData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1082. JsonWriter->WriteValue(Identifier, PropertyValue);
  1083. }
  1084. return true;
  1085. }
  1086. bool UFileHelperBPLibrary::WriteContainerEntryToJSON(const FProperty* InProperty, const void* InPropertyData, const FString* InIdentifier, TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter)
  1087. {
  1088. if (const FEnumProperty* EnumProp = CastField<const FEnumProperty>(InProperty))
  1089. {
  1090. const FString PropertyValue = DataTableUtils::GetPropertyValueAsStringDirect(InProperty, (uint8*)InPropertyData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1091. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *PropertyValue);
  1092. }
  1093. else if (const FNumericProperty* NumProp = CastField<const FNumericProperty>(InProperty))
  1094. {
  1095. if (NumProp->IsEnum())
  1096. {
  1097. const FString PropertyValue = DataTableUtils::GetPropertyValueAsStringDirect(InProperty, (uint8*)InPropertyData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1098. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *PropertyValue);
  1099. }
  1100. else if (NumProp->IsInteger())
  1101. {
  1102. const int64 PropertyValue = NumProp->GetSignedIntPropertyValue(InPropertyData);
  1103. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *FString::FromInt(PropertyValue));
  1104. }
  1105. else
  1106. {
  1107. const double PropertyValue = NumProp->GetFloatingPointPropertyValue(InPropertyData);
  1108. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *FString::SanitizeFloat(PropertyValue));
  1109. }
  1110. }
  1111. else if (const FBoolProperty* BoolProp = CastField<const FBoolProperty>(InProperty))
  1112. {
  1113. const bool PropertyValue = BoolProp->GetPropertyValue(InPropertyData);
  1114. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *(PropertyValue ? FString("true") : FString("false")));
  1115. }
  1116. else if (const FStructProperty* StructProp = CastField<const FStructProperty>(InProperty))
  1117. {
  1118. UFileHelperBPLibrary::WriteJSONObjectStartWithOptionalIdentifier(JsonWriter, InIdentifier);
  1119. UFileHelperBPLibrary::WriteStructToJSON(StructProp->Struct, InPropertyData, JsonWriter);
  1120. JsonWriter->WriteObjectEnd();
  1121. }
  1122. else if (const FArrayProperty* ArrayProp = CastField<const FArrayProperty>(InProperty))
  1123. {
  1124. // Cannot nest arrays
  1125. return false;
  1126. }
  1127. else if (const FSetProperty* SetProp = CastField<const FSetProperty>(InProperty))
  1128. {
  1129. // Cannot nest sets
  1130. return false;
  1131. }
  1132. else if (const FMapProperty* MapProp = CastField<const FMapProperty>(InProperty))
  1133. {
  1134. // Cannot nest maps
  1135. return false;
  1136. }
  1137. else
  1138. {
  1139. const FString PropertyValue = DataTableUtils::GetPropertyValueAsStringDirect(InProperty, (uint8*)InPropertyData, EDataTableExportFlags::UseJsonObjectsForStructs);
  1140. UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(JsonWriter, InIdentifier, *PropertyValue);
  1141. }
  1142. return true;
  1143. }
  1144. void UFileHelperBPLibrary::WriteJSONObjectStartWithOptionalIdentifier(TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter, const FString* InIdentifier)
  1145. {
  1146. if (InIdentifier)
  1147. {
  1148. JsonWriter->WriteObjectStart(*InIdentifier);
  1149. }
  1150. else
  1151. {
  1152. JsonWriter->WriteObjectStart();
  1153. }
  1154. }
  1155. void UFileHelperBPLibrary::WriteJSONValueWithOptionalIdentifier(TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> JsonWriter, const FString* InIdentifier, const TCHAR* InValue)
  1156. {
  1157. if (InIdentifier)
  1158. {
  1159. JsonWriter->WriteValue(*InIdentifier, InValue);
  1160. }
  1161. else
  1162. {
  1163. JsonWriter->WriteValue(InValue);
  1164. }
  1165. }