axmol/core/platform/FileUtils.cpp

1403 lines
40 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
2023-01-04 23:21:24 +08:00
Copyright (c) 2021-2023 Bytedance Inc.
2019-11-23 20:27:39 +08:00
2022-10-01 16:24:52 +08:00
https://axmolengine.github.io/
2019-11-23 20:27:39 +08:00
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/FileUtils.h"
2019-11-23 20:27:39 +08:00
#include <stack>
#include <sstream>
#include <algorithm>
2019-11-23 20:27:39 +08:00
#include "base/Data.h"
#include "base/Macros.h"
#include "base/Director.h"
#include "platform/SAXParser.h"
2023-08-25 16:46:32 +08:00
#include "platform/PosixFileStream.h"
2019-11-23 20:27:39 +08:00
#ifdef MINIZIP_FROM_SYSTEM
2021-12-25 10:04:45 +08:00
# include <minizip/unzip.h>
#else // from our embedded sources
# include "unzip.h"
2019-11-23 20:27:39 +08:00
#endif
#include <sys/stat.h>
#if defined(_WIN32)
# include "ntcvt/ntcvt.hpp"
2023-06-24 21:18:27 +08:00
# include "yasio/string_view.hpp"
#endif
#include "pugixml/pugixml.hpp"
2019-11-24 23:15:56 +08:00
#define DECLARE_GUARD (void)0
2019-11-23 20:27:39 +08:00
#include "base/filesystem.h"
2022-10-07 21:36:38 +08:00
#if defined(_WIN32)
inline stdfs::path toFspath(const std::string_view& pathSV)
{
return stdfs::path{ntcvt::from_chars(pathSV)};
}
2022-10-07 21:36:38 +08:00
#else
inline stdfs::path toFspath(const std::string_view& pathSV)
{
return stdfs::path{pathSV};
}
2022-10-07 21:36:38 +08:00
#endif
NS_AX_BEGIN
2021-12-30 17:47:48 +08:00
2019-11-23 20:27:39 +08:00
// Implement DictMaker
typedef enum
{
SAX_NONE = 0,
SAX_KEY,
SAX_DICT,
SAX_INT,
SAX_REAL,
SAX_STRING,
SAX_ARRAY
2021-12-25 10:04:45 +08:00
} SAXState;
2019-11-23 20:27:39 +08:00
typedef enum
{
SAX_RESULT_NONE = 0,
SAX_RESULT_DICT,
SAX_RESULT_ARRAY
2021-12-25 10:04:45 +08:00
} SAXResult;
2019-11-23 20:27:39 +08:00
class DictMaker : public SAXDelegator
{
public:
SAXResult _resultType;
ValueMap _rootDict;
ValueVector _rootArray;
2021-12-25 10:04:45 +08:00
std::string _curKey; ///< parsed key
std::string _curValue; // parsed value
2019-11-23 20:27:39 +08:00
SAXState _state;
2021-12-25 10:04:45 +08:00
ValueMap* _curDict;
2019-11-23 20:27:39 +08:00
ValueVector* _curArray;
std::stack<ValueMap*> _dictStack;
std::stack<ValueVector*> _arrayStack;
2021-12-25 10:04:45 +08:00
std::stack<SAXState> _stateStack;
2019-11-23 20:27:39 +08:00
public:
2021-12-25 10:04:45 +08:00
DictMaker() : _resultType(SAX_RESULT_NONE), _state(SAX_NONE), _curDict(nullptr), _curArray(nullptr) {}
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
~DictMaker() {}
2019-11-23 20:27:39 +08:00
ValueMap dictionaryWithContentsOfFile(std::string_view fileName)
2019-11-23 20:27:39 +08:00
{
_resultType = SAX_RESULT_DICT;
SAXParser parser;
2022-07-16 10:43:05 +08:00
AXASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
2019-11-23 20:27:39 +08:00
parser.setDelegator(this);
parser.parse(fileName);
return _rootDict;
}
ValueMap dictionaryWithDataOfFile(const char* filedata, int filesize)
{
_resultType = SAX_RESULT_DICT;
SAXParser parser;
2022-07-16 10:43:05 +08:00
AXASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
2019-11-23 20:27:39 +08:00
parser.setDelegator(this);
parser.parse(filedata, filesize);
return _rootDict;
}
ValueVector arrayWithContentsOfFile(std::string_view fileName)
2019-11-23 20:27:39 +08:00
{
_resultType = SAX_RESULT_ARRAY;
SAXParser parser;
2022-07-16 10:43:05 +08:00
AXASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
2019-11-23 20:27:39 +08:00
parser.setDelegator(this);
parser.parse(fileName);
return _rootArray;
}
2021-12-25 10:04:45 +08:00
void startElement(void* ctx, const char* name, const char** atts) override
2019-11-23 20:27:39 +08:00
{
const std::string sName(name);
if (sName == "dict"sv)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (_resultType == SAX_RESULT_DICT && _rootDict.empty())
2019-11-23 20:27:39 +08:00
{
_curDict = &_rootDict;
}
_state = SAX_DICT;
SAXState preState = SAX_NONE;
2021-12-25 10:04:45 +08:00
if (!_stateStack.empty())
2019-11-23 20:27:39 +08:00
{
preState = _stateStack.top();
}
if (SAX_ARRAY == preState)
{
// add a new dictionary into the array
_curArray->emplace_back(Value(ValueMap()));
2019-11-23 20:27:39 +08:00
_curDict = &(_curArray->rbegin())->asValueMap();
}
else if (SAX_DICT == preState)
{
// add a new dictionary into the pre dictionary
2022-07-16 10:43:05 +08:00
AXASSERT(!_dictStack.empty(), "The state is wrong!");
ValueMap* preDict = _dictStack.top();
auto& curVal = hlookup::set_item(*preDict, _curKey, Value(ValueMap()))->second;
_curDict = &curVal.asValueMap();
2019-11-23 20:27:39 +08:00
}
// record the dict state
_stateStack.push(_state);
_dictStack.push(_curDict);
}
else if (sName == "key"sv)
2019-11-23 20:27:39 +08:00
{
_state = SAX_KEY;
}
else if (sName == "integer"sv)
2019-11-23 20:27:39 +08:00
{
_state = SAX_INT;
}
else if (sName == "real"sv)
2019-11-23 20:27:39 +08:00
{
_state = SAX_REAL;
}
else if (sName == "string"sv)
2019-11-23 20:27:39 +08:00
{
_state = SAX_STRING;
}
else if (sName == "array"sv)
2019-11-23 20:27:39 +08:00
{
_state = SAX_ARRAY;
if (_resultType == SAX_RESULT_ARRAY && _rootArray.empty())
{
_curArray = &_rootArray;
}
SAXState preState = SAX_NONE;
2021-12-25 10:04:45 +08:00
if (!_stateStack.empty())
2019-11-23 20:27:39 +08:00
{
preState = _stateStack.top();
}
if (preState == SAX_DICT)
{
(*_curDict)[_curKey] = Value(ValueVector());
2021-12-25 10:04:45 +08:00
_curArray = &(*_curDict)[_curKey].asValueVector();
2019-11-23 20:27:39 +08:00
}
else if (preState == SAX_ARRAY)
{
2022-07-16 10:43:05 +08:00
AXASSERT(!_arrayStack.empty(), "The state is wrong!");
2019-11-23 20:27:39 +08:00
ValueVector* preArray = _arrayStack.top();
preArray->emplace_back(Value(ValueVector()));
2019-11-23 20:27:39 +08:00
_curArray = &(_curArray->rbegin())->asValueVector();
}
// record the array state
_stateStack.push(_state);
_arrayStack.push(_curArray);
}
else
{
_state = SAX_NONE;
}
}
2021-12-25 10:04:45 +08:00
void endElement(void* ctx, const char* name) override
2019-11-23 20:27:39 +08:00
{
SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
const std::string sName((char*)name);
if (sName == "dict"sv)
2019-11-23 20:27:39 +08:00
{
_stateStack.pop();
_dictStack.pop();
2021-12-25 10:04:45 +08:00
if (!_dictStack.empty())
2019-11-23 20:27:39 +08:00
{
_curDict = _dictStack.top();
}
}
else if (sName == "array"sv)
2019-11-23 20:27:39 +08:00
{
_stateStack.pop();
_arrayStack.pop();
2021-12-25 10:04:45 +08:00
if (!_arrayStack.empty())
2019-11-23 20:27:39 +08:00
{
_curArray = _arrayStack.top();
}
}
else if (sName == "true"sv)
2019-11-23 20:27:39 +08:00
{
if (SAX_ARRAY == curState)
{
_curArray->emplace_back(Value(true));
2019-11-23 20:27:39 +08:00
}
else if (SAX_DICT == curState)
{
(*_curDict)[_curKey] = Value(true);
}
}
else if (sName == "false"sv)
2019-11-23 20:27:39 +08:00
{
if (SAX_ARRAY == curState)
{
_curArray->emplace_back(Value(false));
2019-11-23 20:27:39 +08:00
}
else if (SAX_DICT == curState)
{
(*_curDict)[_curKey] = Value(false);
}
}
else if (sName == "string"sv || sName == "integer"sv || sName == "real"sv)
2019-11-23 20:27:39 +08:00
{
if (SAX_ARRAY == curState)
{
if (sName == "string"sv)
_curArray->emplace_back(Value(_curValue));
else if (sName == "integer"sv)
_curArray->emplace_back(Value(atoi(_curValue.c_str())));
2019-11-23 20:27:39 +08:00
else
_curArray->emplace_back(Value(std::atof(_curValue.c_str())));
2019-11-23 20:27:39 +08:00
}
else if (SAX_DICT == curState)
{
if (sName == "string"sv)
2019-11-23 20:27:39 +08:00
(*_curDict)[_curKey] = Value(_curValue);
else if (sName == "integer"sv)
2019-11-23 20:27:39 +08:00
(*_curDict)[_curKey] = Value(atoi(_curValue.c_str()));
else
(*_curDict)[_curKey] = Value(std::atof(_curValue.c_str()));
}
_curValue.clear();
}
_state = SAX_NONE;
}
2021-12-25 10:04:45 +08:00
void textHandler(void* ctx, const char* ch, size_t len) override
2019-11-23 20:27:39 +08:00
{
if (_state == SAX_NONE)
{
return;
}
2021-12-25 10:04:45 +08:00
SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
const std::string text = std::string((char*)ch, len);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
switch (_state)
2019-11-23 20:27:39 +08:00
{
case SAX_KEY:
_curKey = text;
break;
case SAX_INT:
case SAX_REAL:
case SAX_STRING:
2021-12-25 10:04:45 +08:00
{
if (curState == SAX_DICT)
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!_curKey.empty(), "key not found : <integer/real>");
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
_curValue.append(text);
}
break;
2019-11-23 20:27:39 +08:00
default:
break;
}
}
};
ValueMap FileUtils::getValueMapFromFile(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
const std::string fullPath = fullPathForFilename(filename);
DictMaker tMaker;
return tMaker.dictionaryWithContentsOfFile(fullPath);
}
ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize) const
{
DictMaker tMaker;
return tMaker.dictionaryWithDataOfFile(filedata, filesize);
}
ValueVector FileUtils::getValueVectorFromFile(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
const std::string fullPath = fullPathForFilename(filename);
DictMaker tMaker;
return tMaker.arrayWithContentsOfFile(fullPath);
}
/*
* forward statement
*/
static void generateElementForArray(const ValueVector& array, pugi::xml_node& parent);
2019-11-24 23:15:56 +08:00
static void generateElementForDict(const ValueMap& dict, pugi::xml_node& innerDict);
2019-11-23 20:27:39 +08:00
/*
2019-11-24 23:15:56 +08:00
* Use pugixml to write plist files
2019-11-23 20:27:39 +08:00
*/
bool FileUtils::writeToFile(const ValueMap& dict, std::string_view fullPath) const
2019-11-23 20:27:39 +08:00
{
return writeValueMapToFile(dict, fullPath);
}
bool FileUtils::writeValueMapToFile(const ValueMap& dict, std::string_view fullPath) const
2019-11-23 20:27:39 +08:00
{
2019-11-24 23:15:56 +08:00
pugi::xml_document doc;
2021-12-25 10:04:45 +08:00
doc.load_string(R"(<?xml version="1.0" encoding="UTF-8" ?>
2019-11-24 23:15:56 +08:00
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2021-12-25 10:04:45 +08:00
<plist />)",
pugi::parse_full);
auto rootEle = doc.document_element();
2019-11-23 20:27:39 +08:00
generateElementForDict(dict, rootEle);
std::stringstream ss;
doc.save(ss, " ");
return writeStringToFile(ss.str(), fullPath);
2019-11-23 20:27:39 +08:00
}
bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, std::string_view fullPath) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
pugi::xml_document doc;
doc.load_string(R"(<?xml version="1.0" encoding="UTF-8" ?>
2019-11-24 23:15:56 +08:00
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2021-12-25 10:04:45 +08:00
<plist />)",
pugi::parse_full);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
auto rootEle = doc.document_element();
generateElementForArray(vecData, rootEle);
std::stringstream ss;
doc.save(ss, " ");
return writeStringToFile(ss.str(), fullPath);
2019-11-23 20:27:39 +08:00
}
2019-11-24 23:15:56 +08:00
static void generateElementForObject(const Value& value, pugi::xml_node& parent)
2019-11-23 20:27:39 +08:00
{
// object is String
if (value.getType() == Value::Type::STRING)
{
auto node = parent.append_child("string"sv);
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString());
2019-11-23 20:27:39 +08:00
}
// object is integer
2019-11-24 23:15:56 +08:00
else if (value.getType() == Value::Type::INTEGER)
2019-11-23 20:27:39 +08:00
{
auto node = parent.append_child("integer"sv);
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString());
2019-11-23 20:27:39 +08:00
}
// object is real
2019-11-24 23:15:56 +08:00
else if (value.getType() == Value::Type::FLOAT || value.getType() == Value::Type::DOUBLE)
2019-11-23 20:27:39 +08:00
{
auto node = parent.append_child("real"sv);
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString());
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
// object is bool
else if (value.getType() == Value::Type::BOOLEAN)
{
parent.append_child(value.asString());
2019-11-23 20:27:39 +08:00
}
// object is Array
2019-11-24 23:15:56 +08:00
else if (value.getType() == Value::Type::VECTOR)
generateElementForArray(value.asValueVector(), parent);
2019-11-23 20:27:39 +08:00
// object is Dictionary
2019-11-24 23:15:56 +08:00
else if (value.getType() == Value::Type::MAP)
generateElementForDict(value.asValueMap(), parent);
2019-11-23 20:27:39 +08:00
}
static void generateElementForDict(const ValueMap& dict, pugi::xml_node& parent)
2019-11-23 20:27:39 +08:00
{
auto dictDS = parent.append_child("dict"sv);
2021-12-25 10:04:45 +08:00
for (const auto& iter : dict)
2019-11-23 20:27:39 +08:00
{
auto key = dictDS.append_child("key"sv);
key.append_child(pugi::xml_node_type::node_pcdata).set_value(iter.first);
2019-11-24 23:15:56 +08:00
generateElementForObject(iter.second, dictDS);
2019-11-23 20:27:39 +08:00
}
}
static void generateElementForArray(const ValueVector& array, pugi::xml_node& parent)
2019-11-23 20:27:39 +08:00
{
auto arrayDS = parent.append_child("array"sv);
2021-12-25 10:04:45 +08:00
for (const auto& value : array)
{
generateElementForObject(value, arrayDS);
2019-11-23 20:27:39 +08:00
}
}
// Implement FileUtils
FileUtils* FileUtils::s_sharedFileUtils = nullptr;
void FileUtils::destroyInstance()
{
2022-07-16 10:43:05 +08:00
AX_SAFE_DELETE(s_sharedFileUtils);
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::setDelegate(FileUtils* delegate)
2019-11-23 20:27:39 +08:00
{
if (s_sharedFileUtils)
delete s_sharedFileUtils;
s_sharedFileUtils = delegate;
}
2023-08-25 16:46:32 +08:00
FileUtils::FileUtils() : _writablePath("") {}
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
FileUtils::~FileUtils() {}
2019-11-23 20:27:39 +08:00
bool FileUtils::writeStringToFile(std::string_view dataStr, std::string_view fullPath) const
2019-11-23 20:27:39 +08:00
{
return FileUtils::writeBinaryToFile(dataStr.data(), dataStr.size(), fullPath);
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::writeStringToFile(std::string dataStr,
std::string_view fullPath,
2021-12-25 10:04:45 +08:00
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}](std::string_view dataStrIn) -> bool {
return FileUtils::getInstance()->writeStringToFile(dataStrIn, path);
2021-12-25 10:04:45 +08:00
},
std::move(callback), std::move(dataStr));
2019-11-23 20:27:39 +08:00
}
bool FileUtils::writeDataToFile(const Data& data, std::string_view fullPath) const
2019-11-23 20:27:39 +08:00
{
return FileUtils::writeBinaryToFile(data.getBytes(), data.getSize(), fullPath);
}
void FileUtils::writeDataToFile(Data data, std::string_view fullPath, std::function<void(bool)> callback) const
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}](const Data& dataIn) -> bool {
return FileUtils::getInstance()->writeDataToFile(dataIn, path);
},
2021-12-25 10:04:45 +08:00
std::move(callback), std::move(data));
}
bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, std::string_view fullPath)
{
2022-07-16 10:43:05 +08:00
AXASSERT(!fullPath.empty() && dataSize > 0, "Invalid parameters.");
2019-11-23 20:27:39 +08:00
auto* fileUtils = FileUtils::getInstance();
2019-11-23 20:27:39 +08:00
do
{
2023-08-25 16:46:32 +08:00
auto fileStream = fileUtils->openFileStream(fullPath, FileStream::Mode::WRITE);
2019-11-23 20:27:39 +08:00
// Read the file from hardware
2022-07-16 10:43:05 +08:00
AX_BREAK_IF(!fileStream);
2019-11-23 20:27:39 +08:00
2023-08-25 16:46:32 +08:00
fileStream->write(data, static_cast<unsigned int>(dataSize));
return true;
2019-11-23 20:27:39 +08:00
} while (0);
return false;
}
bool FileUtils::init()
{
DECLARE_GUARD;
_searchPathArray.emplace_back(_defaultResRootPath);
2019-11-23 20:27:39 +08:00
return true;
}
void FileUtils::purgeCachedEntries()
{
DECLARE_GUARD;
_fullPathCache.clear();
_fullPathCacheDir.clear();
}
std::string FileUtils::getStringFromFile(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
std::string s;
getContents(filename, &s);
return s;
}
void FileUtils::getStringFromFile(std::string_view path, std::function<void(std::string)> callback) const
2019-11-23 20:27:39 +08:00
{
// Get the full path on the main thread, to avoid the issue that FileUtil's is not
// thread safe, and accessing the fullPath cache and searching the search paths is not thread safe
auto fullPath = fullPathForFilename(path);
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}]() -> std::string { return FileUtils::getInstance()->getStringFromFile(path); },
2021-12-25 10:04:45 +08:00
std::move(callback));
2019-11-23 20:27:39 +08:00
}
Data FileUtils::getDataFromFile(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
Data d;
getContents(filename, &d);
return d;
}
void FileUtils::getDataFromFile(std::string_view filename, std::function<void(Data)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filename);
performOperationOffthread(
[path = std::string{fullPath}]() -> Data { return FileUtils::getInstance()->getDataFromFile(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
FileUtils::Status FileUtils::getContents(std::string_view filename, ResizableBuffer* buffer) const
2019-11-23 20:27:39 +08:00
{
if (filename.empty())
return Status::NotExists;
auto fileUtils = FileUtils::getInstance();
2019-11-23 20:27:39 +08:00
const auto fullPath = fileUtils->fullPathForFilename(filename);
2019-11-23 20:27:39 +08:00
2023-08-25 16:46:32 +08:00
auto fileStream = fileUtils->openFileStream(fullPath, FileStream::Mode::READ);
if (!fileStream)
2020-08-05 13:10:37 +08:00
return Status::OpenFailed;
2023-08-25 16:46:32 +08:00
const auto size = fileStream->size();
if (size < 0)
{
return Status::ObtainSizeFailed;
}
if (size > ULONG_MAX)
{
return Status::TooLarge;
}
2021-04-25 16:36:20 +08:00
buffer->resize((size_t)size);
2023-08-25 16:46:32 +08:00
fileStream->seek(0, SEEK_SET);
const auto sizeRead = fileStream->read(buffer->buffer(), (unsigned)size);
2021-12-25 10:04:45 +08:00
if (sizeRead < size)
{
buffer->resize(sizeRead);
2019-11-23 20:27:39 +08:00
return Status::ReadFailed;
}
return Status::OK;
}
void FileUtils::writeValueMapToFile(ValueMap dict, std::string_view fullPath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}](const ValueMap& dictIn) -> bool {
return FileUtils::getInstance()->writeValueMapToFile(dictIn, path);
2021-12-25 10:04:45 +08:00
},
std::move(callback), std::move(dict));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::writeValueVectorToFile(ValueVector vecData,
std::string_view fullPath,
2021-12-25 10:04:45 +08:00
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}](const ValueVector& vecDataIn) -> bool {
return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, path);
2021-12-25 10:04:45 +08:00
},
std::move(callback), std::move(vecData));
2019-11-23 20:27:39 +08:00
}
2023-08-25 16:46:32 +08:00
std::string FileUtils::getPathForFilename(std::string_view filename,
std::string_view searchPath) const
2019-11-23 20:27:39 +08:00
{
auto file = filename;
std::string_view file_path = hlookup::empty_sv;
size_t pos = filename.find_last_of('/');
2019-11-23 20:27:39 +08:00
if (pos != std::string::npos)
{
2021-12-25 10:04:45 +08:00
file_path = filename.substr(0, pos + 1);
file = filename.substr(pos + 1);
2019-11-23 20:27:39 +08:00
}
// searchPath + file_path + resourceDirectory
std::string path{searchPath};
2019-11-23 20:27:39 +08:00
path += file_path;
path = getFullPathForFilenameWithinDirectory(path, file);
return path;
}
2023-08-25 16:46:32 +08:00
std::string FileUtils::getPathForDirectory(std::string_view dir,
std::string_view searchPath) const
2019-11-23 20:27:39 +08:00
{
2022-11-01 06:47:36 +08:00
return std::string{searchPath}.append(dir);
2019-11-23 20:27:39 +08:00
}
std::string FileUtils::fullPathForFilename(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
DECLARE_GUARD;
if (filename.empty())
{
return "";
}
2020-08-18 14:29:09 +08:00
/*
2021-12-25 10:04:45 +08:00
* As we know, this function 'fullPathForFilename' will be calling when load any file, how to ensure this thread
* safe Step: a. call this function at main-thread always b. use the really fullPath to call
* getStringFromFile/getDataFromFile at sub-thread c. then this function will call again with really fullPath d.
* then isAbsolutePath avoid to access _fullPathCache _fullPathCache concurrent
*/
2019-11-23 20:27:39 +08:00
if (isAbsolutePath(filename))
{
return std::string{filename};
2019-11-23 20:27:39 +08:00
}
// Already Cached ?
auto cacheIter = _fullPathCache.find(filename);
2021-12-25 10:04:45 +08:00
if (cacheIter != _fullPathCache.end())
2019-11-23 20:27:39 +08:00
{
return cacheIter->second;
}
std::string fullpath;
for (const auto& searchIt : _searchPathArray)
{
2022-11-01 06:47:36 +08:00
fullpath = this->getPathForFilename(filename, searchIt);
2022-10-31 14:30:33 +08:00
2022-11-01 06:47:36 +08:00
if (!fullpath.empty())
{
// Using the filename passed in as key.
_fullPathCache.emplace(filename, fullpath);
return fullpath;
2019-11-23 20:27:39 +08:00
}
}
2021-12-25 10:04:45 +08:00
if (isPopupNotify())
{
2022-10-01 16:24:52 +08:00
AXLOG("axmol: fullPathForFilename: No file found at %s. Possible missing file.", filename.data());
2019-11-23 20:27:39 +08:00
}
// The file wasn't found, return empty string.
return std::string{};
2019-11-23 20:27:39 +08:00
}
std::string FileUtils::fullPathForDirectory(std::string_view dir) const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
if (dir.empty())
{
return "";
}
if (isAbsolutePath(dir))
{
return std::string{dir};
2019-11-23 20:27:39 +08:00
}
// Already Cached ?
auto cacheIter = _fullPathCacheDir.find(dir);
2021-12-25 10:04:45 +08:00
if (cacheIter != _fullPathCacheDir.end())
2019-11-23 20:27:39 +08:00
{
return cacheIter->second;
}
std::string longdir{dir};
2019-11-23 20:27:39 +08:00
std::string fullpath;
2021-12-25 10:04:45 +08:00
if (longdir[longdir.length() - 1] != '/')
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
longdir += "/";
2019-11-23 20:27:39 +08:00
}
for (const auto& searchIt : _searchPathArray)
{
2022-11-01 06:47:36 +08:00
fullpath = this->getPathForDirectory(longdir, searchIt);
if (!fullpath.empty() && isDirectoryExistInternal(fullpath))
2019-11-23 20:27:39 +08:00
{
2022-11-01 06:47:36 +08:00
// Using the filename passed in as key.
_fullPathCacheDir.emplace(dir, fullpath);
return fullpath;
2019-11-23 20:27:39 +08:00
}
}
2021-12-25 10:04:45 +08:00
if (isPopupNotify())
{
2022-10-01 16:24:52 +08:00
AXLOG("axmol: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.data());
2019-11-23 20:27:39 +08:00
}
// The file wasn't found, return empty string.
return "";
}
std::string FileUtils::fullPathFromRelativeFile(std::string_view filename, std::string_view relativeFile) const
2019-11-23 20:27:39 +08:00
{
return std::string{relativeFile.substr(0, relativeFile.rfind('/') + 1)}.append(filename);
2019-11-23 20:27:39 +08:00
}
const std::vector<std::string>& FileUtils::getSearchPaths() const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
return _searchPathArray;
}
const std::vector<std::string>& FileUtils::getOriginalSearchPaths() const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
return _originalSearchPaths;
}
void FileUtils::setWritablePath(std::string_view writablePath)
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
_writablePath = writablePath;
}
const std::string& FileUtils::getDefaultResourceRootPath() const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
return _defaultResRootPath;
}
void FileUtils::setDefaultResourceRootPath(std::string_view path)
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
if (_defaultResRootPath != path)
{
_fullPathCache.clear();
_fullPathCacheDir.clear();
_defaultResRootPath = path;
2021-12-25 10:04:45 +08:00
if (!_defaultResRootPath.empty() && _defaultResRootPath[_defaultResRootPath.length() - 1] != '/')
2019-11-23 20:27:39 +08:00
{
_defaultResRootPath += '/';
}
// Updates search paths
setSearchPaths(_originalSearchPaths);
}
}
void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
{
DECLARE_GUARD;
bool existDefaultRootPath = false;
2021-12-25 10:04:45 +08:00
_originalSearchPaths = searchPaths;
2019-11-23 20:27:39 +08:00
_fullPathCache.clear();
_fullPathCacheDir.clear();
_searchPathArray.clear();
for (const auto& path : _originalSearchPaths)
{
std::string prefix;
std::string fullPath;
if (!isAbsolutePath(path))
2021-12-25 10:04:45 +08:00
{ // Not an absolute path
2019-11-23 20:27:39 +08:00
prefix = _defaultResRootPath;
}
fullPath = prefix + path;
2021-12-25 10:04:45 +08:00
if (!path.empty() && path[path.length() - 1] != '/')
2019-11-23 20:27:39 +08:00
{
fullPath += "/";
}
if (!existDefaultRootPath && path == _defaultResRootPath)
{
existDefaultRootPath = true;
}
_searchPathArray.emplace_back(fullPath);
2019-11-23 20:27:39 +08:00
}
if (!existDefaultRootPath)
{
2022-07-16 10:43:05 +08:00
// AXLOG("Default root path doesn't exist, adding it.");
_searchPathArray.emplace_back(_defaultResRootPath);
2019-11-23 20:27:39 +08:00
}
}
void FileUtils::addSearchPath(std::string_view searchpath, const bool front)
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
std::string path;
2019-11-23 20:27:39 +08:00
if (!isAbsolutePath(searchpath))
path = _defaultResRootPath;
2019-11-23 20:27:39 +08:00
path.append(searchpath);
2021-12-25 10:04:45 +08:00
if (!path.empty() && path[path.length() - 1] != '/')
2019-11-23 20:27:39 +08:00
{
path += "/";
}
#ifdef AX_NO_DUP_SEARCH_PATH
auto it = std::find(_searchPathArray.begin(), _searchPathArray.end(), path);
if (it != _searchPathArray.end())
{
_searchPathArray.erase(it);
auto itOrigin = std::find(_originalSearchPaths.begin(), _originalSearchPaths.end(), std::string{searchpath});
if (itOrigin != _originalSearchPaths.end())
{
_originalSearchPaths.erase(itOrigin);
}
}
#endif // AX_NO_DUP_SEARCH_PATH
2021-12-25 10:04:45 +08:00
if (front)
{
_originalSearchPaths.insert(_originalSearchPaths.begin(), std::string{searchpath});
_searchPathArray.insert(_searchPathArray.begin(), std::move(path));
2021-12-25 10:04:45 +08:00
}
else
{
_originalSearchPaths.emplace_back(std::string{searchpath});
_searchPathArray.emplace_back(std::move(path));
2019-11-23 20:27:39 +08:00
}
}
std::string FileUtils::getFullPathForFilenameWithinDirectory(std::string_view directory,
std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
// get directory+filename, safely adding '/' as necessary
std::string ret{directory};
if (!directory.empty() && directory[directory.size() - 1] != '/')
2021-12-25 10:04:45 +08:00
{
2019-11-23 20:27:39 +08:00
ret += '/';
}
ret += filename;
// if the file doesn't exist, return an empty string
2023-06-24 21:18:27 +08:00
if (isFileExistInternal(ret))
return ret;
return std::string{};
2019-11-23 20:27:39 +08:00
}
bool FileUtils::isFileExist(std::string_view filename) const
2019-11-23 20:27:39 +08:00
{
if (isAbsolutePath(filename))
{
return isFileExistInternal(filename);
}
else
{
std::string fullpath = fullPathForFilename(filename);
return !fullpath.empty();
2019-11-23 20:27:39 +08:00
}
}
void FileUtils::isFileExist(std::string_view filename, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filename);
performOperationOffthread(
[path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isFileExist(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
bool FileUtils::isAbsolutePath(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
return isAbsolutePathInternal(path);
}
bool FileUtils::isAbsolutePathInternal(std::string_view path)
{
const char* raw = path.data();
#if defined(_WIN32)
// see also: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN
return ((path.length() > 2 && ((raw[0] >= 'a' && raw[0] <= 'z') || (raw[0] >= 'A' && raw[0] <= 'Z')) &&
raw[1] == ':') // Normal absolute path
|| cxx20::starts_with(path, R"(\\?\)") // Win32 File Namespaces for Long Path
|| cxx20::starts_with(path, R"(\\.\)") // Win32 Device Namespaces for device
|| (raw[0] == '/' || raw[0] == '\\') // Current disk drive
);
#else
return (raw[0] == '/');
#endif
2019-11-23 20:27:39 +08:00
}
bool FileUtils::isDirectoryExist(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!dirPath.empty(), "Invalid path");
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
DECLARE_GUARD;
if (isAbsolutePath(dirPath))
{
return isDirectoryExistInternal(dirPath);
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
auto fullPath = fullPathForDirectory(dirPath);
return !fullPath.empty();
}
}
void FileUtils::isDirectoryExist(std::string_view fullPath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths");
performOperationOffthread(
[path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->isDirectoryExist(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::createDirectory(std::string_view dirPath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
performOperationOffthread(
[path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->createDirectory(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::removeDirectory(std::string_view dirPath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
performOperationOffthread(
[path = std::string{dirPath}]() -> bool { return FileUtils::getInstance()->removeDirectory(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::removeFile(std::string_view filepath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filepath);
performOperationOffthread(
[path = std::string{fullPath}]() -> bool { return FileUtils::getInstance()->removeFile(path); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::renameFile(std::string_view path,
std::string_view oldname,
std::string_view name,
2021-12-25 10:04:45 +08:00
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{path}, oldname = std::string{oldname}, name = std::string{name}]() -> bool {
return FileUtils::getInstance()->renameFile(path, oldname, name);
},
2021-12-25 10:04:45 +08:00
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::renameFile(std::string_view oldfullpath,
std::string_view newfullpath,
2021-12-25 10:04:45 +08:00
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[oldpath = std::string{oldfullpath}, newpath = std::string{newfullpath}]() {
2023-08-25 16:46:32 +08:00
return FileUtils::getInstance()->renameFile(oldpath, newpath);
},
2021-12-25 10:04:45 +08:00
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::getFileSize(std::string_view filepath, std::function<void(int64_t)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filepath);
performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->getFileSize(path); },
2021-12-25 10:04:45 +08:00
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::listFilesAsync(std::string_view dirPath, std::function<void(std::vector<std::string>)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForDirectory(dirPath);
performOperationOffthread([path = std::string{fullPath}]() { return FileUtils::getInstance()->listFiles(path); },
2021-12-25 10:04:45 +08:00
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::listFilesRecursivelyAsync(std::string_view dirPath,
2021-12-25 10:04:45 +08:00
std::function<void(std::vector<std::string>)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForDirectory(dirPath);
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path = std::string{fullPath}]() {
2023-08-25 16:46:32 +08:00
std::vector<std::string> retval;
FileUtils::getInstance()->listFilesRecursively(path, &retval);
return retval;
2021-12-25 10:04:45 +08:00
},
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2023-08-25 16:46:32 +08:00
std::unique_ptr<FileStream> FileUtils::openFileStream(std::string_view filePath, FileStream::Mode mode)
{
2023-08-25 16:46:32 +08:00
PosixFileStream fs;
return fs.open(filePath, mode) ? std::make_unique<PosixFileStream>(std::move(fs)) : nullptr;
}
/* !!!Notes for c++fs
a. ios: require ios 13.0+, currently use ghc as workaround in lower ios 13.0- devices
b. android: require ndk-r22+
*/
std::vector<std::string> FileUtils::listFiles(std::string_view dirPath) const
{
const auto fullPath = fullPathForDirectory(dirPath);
auto fsPath = toFspath(fullPath);
if (!stdfs::is_directory(fsPath))
{
return {};
}
std::vector<std::string> files = {};
for (const auto& entry : stdfs::directory_iterator(fsPath))
{
const auto isDir = entry.is_directory();
if (isDir || entry.is_regular_file())
{
2022-10-07 21:36:38 +08:00
#if (AX_TARGET_PLATFORM == AX_PLATFORM_WIN32)
/*
2023-08-25 16:46:32 +08:00
* Because the object memory model of std::u8string is identical to std::string
* so we use force cast to std::string without `memory alloc & copy`, the ASM code will be:
* 00F03204 lea eax,[ebp-28h]
* 00F03207 lea ecx,[edi+20h]
* 00F0320A push eax
* 008E320B call std::filesystem::path::u8string (08E1C40h)
* 008E3210 mov esi,eax
* 008E3212 mov byte ptr [ebp-4],6
*/
auto pathU8Str = entry.path().u8string();
2023-08-25 16:46:32 +08:00
auto& pathStr = *reinterpret_cast<std::string*>(&pathU8Str);
2022-10-07 21:36:38 +08:00
std::replace(pathStr.begin(), pathStr.end(), '\\', '/');
#else
std::string pathStr = entry.path().string();
#endif
if (isDir)
pathStr += '/';
files.emplace_back(std::move(pathStr));
}
}
return files;
}
void FileUtils::listFilesRecursively(std::string_view dirPath, std::vector<std::string>* files) const
{
const auto fullPath = fullPathForDirectory(dirPath);
auto fsPath = toFspath(fullPath);
if (!stdfs::is_directory(fsPath))
{
return;
}
for (const auto& entry : stdfs::recursive_directory_iterator(fsPath))
{
const auto isDir = entry.is_directory();
if (isDir || entry.is_regular_file())
{
2022-10-07 21:36:38 +08:00
#if (AX_TARGET_PLATFORM == AX_PLATFORM_WIN32)
2023-08-25 16:46:32 +08:00
auto pathU8Str = entry.path().u8string();
auto& pathStr = *reinterpret_cast<std::string*>(&pathU8Str);
2022-10-07 21:36:38 +08:00
std::replace(pathStr.begin(), pathStr.end(), '\\', '/');
#else
std::string pathStr = entry.path().string();
#endif
if (isDir)
pathStr += '/';
files->emplace_back(std::move(pathStr));
}
}
}
2023-03-08 08:34:17 +08:00
#if defined(_WIN32)
2019-11-23 20:27:39 +08:00
// windows os implement should override in platform specific FileUtiles class
bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support isDirectoryExistInternal");
2019-11-23 20:27:39 +08:00
return false;
}
bool FileUtils::createDirectory(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support createDirectory");
2019-11-23 20:27:39 +08:00
return false;
}
bool FileUtils::removeDirectory(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support removeDirectory");
2019-11-23 20:27:39 +08:00
return false;
}
bool FileUtils::removeFile(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support removeFile");
2019-11-23 20:27:39 +08:00
return false;
}
bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support renameFile");
2019-11-23 20:27:39 +08:00
return false;
}
bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "FileUtils not support renameFile");
2019-11-23 20:27:39 +08:00
return false;
}
int64_t FileUtils::getFileSize(std::string_view filepath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(false, "getFileSize should be override by platform FileUtils");
2019-11-23 20:27:39 +08:00
return 0;
}
#else
// default implements for unix like os
2021-12-25 10:04:45 +08:00
# include <sys/types.h>
# include <errno.h>
# include <dirent.h>
2019-11-23 20:27:39 +08:00
// android doesn't have ftw.h
2022-07-16 10:43:05 +08:00
# if (AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID)
2021-12-25 10:04:45 +08:00
# include <ftw.h>
# endif
2019-11-23 20:27:39 +08:00
bool FileUtils::isDirectoryExistInternal(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
struct stat st;
if (stat(dirPath.data(), &st) == 0)
2019-11-23 20:27:39 +08:00
{
return S_ISDIR(st.st_mode);
}
return false;
}
bool FileUtils::createDirectory(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!path.empty(), "Invalid path");
2019-11-23 20:27:39 +08:00
if (isDirectoryExist(path))
return true;
// Split the path
size_t start = 0;
size_t found = path.find_first_of("/\\", start);
std::string_view subpath;
2019-11-23 20:27:39 +08:00
std::vector<std::string> dirs;
if (found != std::string::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.emplace_back(std::string{subpath});
2021-12-25 10:04:45 +08:00
start = found + 1;
2019-11-23 20:27:39 +08:00
found = path.find_first_of("/\\", start);
if (found == std::string::npos)
{
if (start < path.length())
{
dirs.emplace_back(std::string{path.substr(start)});
2019-11-23 20:27:39 +08:00
}
break;
}
}
}
2021-12-25 10:04:45 +08:00
DIR* dir = NULL;
2019-11-23 20:27:39 +08:00
// Create path recursively
std::string strSubpath;
2019-11-23 20:27:39 +08:00
for (const auto& iter : dirs)
{
strSubpath += iter;
dir = opendir(strSubpath.c_str());
2019-11-23 20:27:39 +08:00
if (!dir)
{
// directory doesn't exist, should create a new one
int ret = mkdir(strSubpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
2019-11-23 20:27:39 +08:00
if (ret != 0 && (errno != EEXIST))
{
// current directory can not be created, sub directories can not be created too
// should return
return false;
}
}
else
{
// directory exists, should close opened dir
closedir(dir);
}
}
return true;
}
namespace
{
2022-07-16 10:43:05 +08:00
# if (AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID)
2021-12-25 10:04:45 +08:00
int unlink_cb(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf)
{
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
# endif
} // namespace
2019-11-23 20:27:39 +08:00
bool FileUtils::removeDirectory(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
# if !defined(AX_TARGET_OS_TVOS)
2019-11-23 20:27:39 +08:00
2022-07-16 10:43:05 +08:00
# if (AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID)
if (nftw(path.data(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1)
2019-11-23 20:27:39 +08:00
return false;
else
return true;
2021-12-25 10:04:45 +08:00
# else
std::string command = "rm -r \""s;
2019-11-23 20:27:39 +08:00
// Path may include space.
command.append(path).append("\"", 1);
2019-11-23 20:27:39 +08:00
if (system(command.c_str()) >= 0)
return true;
else
return false;
2022-07-16 10:43:05 +08:00
# endif // (AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID)
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
# else
2019-11-23 20:27:39 +08:00
return false;
2022-07-16 10:43:05 +08:00
# endif // !defined(AX_TARGET_OS_TVOS)
2019-11-23 20:27:39 +08:00
}
bool FileUtils::removeFile(std::string_view path) const
2019-11-23 20:27:39 +08:00
{
if (remove(path.data()))
2021-12-25 10:04:45 +08:00
{
2019-11-23 20:27:39 +08:00
return false;
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
return true;
}
}
bool FileUtils::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!oldfullpath.empty(), "Invalid path");
AXASSERT(!newfullpath.empty(), "Invalid path");
2019-11-23 20:27:39 +08:00
int errorCode = rename(oldfullpath.data(), newfullpath.data());
2019-11-23 20:27:39 +08:00
if (0 != errorCode)
{
2022-07-16 10:43:05 +08:00
AXLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.data(), newfullpath.data(), errorCode);
2019-11-23 20:27:39 +08:00
return false;
}
return true;
}
bool FileUtils::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!path.empty(), "Invalid path");
std::string oldPath{path};
oldPath += oldname;
std::string newPath{path};
newPath += name;
2019-11-23 20:27:39 +08:00
return this->renameFile(oldPath, newPath);
}
int64_t FileUtils::getFileSize(std::string_view filepath) const
2019-11-23 20:27:39 +08:00
{
2022-07-16 10:43:05 +08:00
AXASSERT(!filepath.empty(), "Invalid path");
2019-11-23 20:27:39 +08:00
std::string_view path;
std::string fullpath;
2019-11-23 20:27:39 +08:00
if (!isAbsolutePath(filepath))
{
fullpath = fullPathForFilename(filepath);
if (fullpath.empty())
return 0;
path = fullpath;
2019-11-23 20:27:39 +08:00
}
else
path = filepath;
2019-11-23 20:27:39 +08:00
2019-11-28 09:59:18 +08:00
struct stat info;
2019-11-23 20:27:39 +08:00
// Get data associated with "crt_stat.c":
int result = ::stat(path.data(), &info);
2019-11-23 20:27:39 +08:00
// Check if statistics are valid:
if (result != 0)
{
// Failed
return -1;
}
else
{
return info.st_size;
2019-11-23 20:27:39 +08:00
}
}
#endif
//////////////////////////////////////////////////////////////////////////
// Notification support when getFileData from invalid file path.
//////////////////////////////////////////////////////////////////////////
static bool s_popupNotify = true;
void FileUtils::setPopupNotify(bool notify)
{
s_popupNotify = notify;
}
bool FileUtils::isPopupNotify() const
{
return s_popupNotify;
}
std::string FileUtils::getFileExtension(std::string_view filePath) const
2019-11-23 20:27:39 +08:00
{
std::string fileExtension;
size_t pos = filePath.find_last_of('.');
if (pos != std::string::npos)
{
fileExtension = filePath.substr(pos, filePath.length());
std::transform(fileExtension.begin(), fileExtension.end(), fileExtension.begin(), ::tolower);
}
return fileExtension;
}
std::string FileUtils::getFileShortName(std::string_view filePath)
2020-08-01 19:25:39 +08:00
{
// std::string fileExtension;
2020-08-01 19:25:39 +08:00
size_t pos = filePath.find_last_of("/\\");
if (pos != std::string::npos)
{
return std::string{filePath.substr(pos + 1)};
2020-08-01 19:25:39 +08:00
}
return std::string{filePath};
2020-08-01 19:25:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::valueMapCompact(ValueMap& /*valueMap*/) const {}
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
void FileUtils::valueVectorCompact(ValueVector& /*valueVector*/) const {}
2019-11-23 20:27:39 +08:00
NS_AX_END