CDirectory.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "common.h"
  2. #include <sys/stat.h>
  3. #include <utility>
  4. #include "CDirectory.h"
  5. #include "CAssetLoadException.h"
  6. using namespace WallpaperEngine::Assets;
  7. CDirectory::CDirectory (std::filesystem::path basepath) :
  8. m_basepath (std::move(basepath))
  9. {
  10. // ensure the specified path exists
  11. struct stat buffer {};
  12. if (stat (this->m_basepath.c_str (), &buffer) != 0)
  13. sLog.exception ("Cannot find ", this->m_basepath, ". This folder is required for wallpaper engine to work");
  14. if (!S_ISDIR(buffer.st_mode))
  15. sLog.exception ("Cannot find ", this->m_basepath, ". There's an assets file in it's place");
  16. }
  17. CDirectory::~CDirectory ()
  18. = default;
  19. std::filesystem::path CDirectory::resolveRealFile (std::string filename) const
  20. {
  21. return std::filesystem::path (this->m_basepath) / filename;
  22. }
  23. const void* CDirectory::readFile (std::string filename, uint32_t* length) const
  24. {
  25. std::filesystem::path final = std::filesystem::path (this->m_basepath) / filename;
  26. // first check the cache, if the file is there already just return the data in there
  27. auto it = this->m_cache.find (final);
  28. if (it != this->m_cache.end ())
  29. {
  30. if (length != nullptr)
  31. *length = (*it).second.length;
  32. return (*it).second.address;
  33. }
  34. FILE* fp = fopen (final.c_str (), "rb");
  35. if (fp == nullptr)
  36. throw CAssetLoadException(filename, "Cannot find file");
  37. // go to the end, get the position and return to the beginning
  38. fseek (fp, 0, SEEK_END);
  39. long size = ftell (fp);
  40. fseek (fp, 0, SEEK_SET);
  41. // now read the whole file
  42. char* contents = new char[size];
  43. if (fread (contents, size, 1, fp) != 1)
  44. {
  45. delete[] contents;
  46. throw CAssetLoadException (filename, "Unexpected error when reading the file");
  47. }
  48. if (length != nullptr)
  49. *length = size;
  50. return contents;
  51. }