FileHelperBPLibrary.cpp 37 KB

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