axmol/cocos/platform/CCFileUtils.cpp

1517 lines
43 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.
2021-10-09 13:48:56 +08:00
Copyright (c) 2021 Bytedance Inc.
2019-11-23 20:27:39 +08:00
2021-10-09 13:48:56 +08:00
https://adxe.org
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/CCFileUtils.h"
#include <stack>
#include <sstream>
2019-11-23 20:27:39 +08:00
#include "base/CCData.h"
#include "base/ccMacros.h"
#include "base/CCDirector.h"
#include "platform/CCSAXParser.h"
//#include "base/ccUtils.h"
#include "platform/CCPosixFileStream.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>
#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
NS_CC_BEGIN
// 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(const std::string& fileName)
{
_resultType = SAX_RESULT_DICT;
SAXParser parser;
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
parser.setDelegator(this);
parser.parse(fileName);
return _rootDict;
}
ValueMap dictionaryWithDataOfFile(const char* filedata, int filesize)
{
_resultType = SAX_RESULT_DICT;
SAXParser parser;
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
parser.setDelegator(this);
parser.parse(filedata, filesize);
return _rootDict;
}
ValueVector arrayWithContentsOfFile(const std::string& fileName)
{
_resultType = SAX_RESULT_ARRAY;
SAXParser parser;
CCASSERT(parser.init("UTF-8"), "The file format isn't UTF-8");
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);
2021-12-25 10:04:45 +08:00
if (sName == "dict")
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->push_back(Value(ValueMap()));
_curDict = &(_curArray->rbegin())->asValueMap();
}
else if (SAX_DICT == preState)
{
// add a new dictionary into the pre dictionary
2021-12-25 10:04:45 +08:00
CCASSERT(!_dictStack.empty(), "The state is wrong!");
ValueMap* preDict = _dictStack.top();
2019-11-23 20:27:39 +08:00
(*preDict)[_curKey] = Value(ValueMap());
2021-12-25 10:04:45 +08:00
_curDict = &(*preDict)[_curKey].asValueMap();
2019-11-23 20:27:39 +08:00
}
// record the dict state
_stateStack.push(_state);
_dictStack.push(_curDict);
}
2021-12-25 10:04:45 +08:00
else if (sName == "key")
2019-11-23 20:27:39 +08:00
{
_state = SAX_KEY;
}
2021-12-25 10:04:45 +08:00
else if (sName == "integer")
2019-11-23 20:27:39 +08:00
{
_state = SAX_INT;
}
2021-12-25 10:04:45 +08:00
else if (sName == "real")
2019-11-23 20:27:39 +08:00
{
_state = SAX_REAL;
}
2021-12-25 10:04:45 +08:00
else if (sName == "string")
2019-11-23 20:27:39 +08:00
{
_state = SAX_STRING;
}
else if (sName == "array")
{
_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)
{
2021-12-25 10:04:45 +08:00
CCASSERT(!_arrayStack.empty(), "The state is wrong!");
2019-11-23 20:27:39 +08:00
ValueVector* preArray = _arrayStack.top();
preArray->push_back(Value(ValueVector()));
_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);
2021-12-25 10:04:45 +08:00
if (sName == "dict")
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")
{
_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")
{
if (SAX_ARRAY == curState)
{
_curArray->push_back(Value(true));
}
else if (SAX_DICT == curState)
{
(*_curDict)[_curKey] = Value(true);
}
}
else if (sName == "false")
{
if (SAX_ARRAY == curState)
{
_curArray->push_back(Value(false));
}
else if (SAX_DICT == curState)
{
(*_curDict)[_curKey] = Value(false);
}
}
else if (sName == "string" || sName == "integer" || sName == "real")
{
if (SAX_ARRAY == curState)
{
if (sName == "string")
_curArray->push_back(Value(_curValue));
else if (sName == "integer")
_curArray->push_back(Value(atoi(_curValue.c_str())));
else
_curArray->push_back(Value(std::atof(_curValue.c_str())));
}
else if (SAX_DICT == curState)
{
if (sName == "string")
(*_curDict)[_curKey] = Value(_curValue);
else if (sName == "integer")
(*_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
{
2021-12-25 10:04:45 +08:00
CCASSERT(!_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(const std::string& filename) const
{
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(const std::string& filename) const
{
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
*/
2021-12-25 10:04:45 +08:00
bool FileUtils::writeToFile(const ValueMap& dict, const std::string& fullPath) const
2019-11-23 20:27:39 +08:00
{
return writeValueMapToFile(dict, fullPath);
}
bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const
{
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, const std::string& fullPath) const
{
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)
{
2021-12-25 10:04:45 +08:00
auto node = parent.append_child("string");
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString().c_str());
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
{
2021-12-25 10:04:45 +08:00
auto node = parent.append_child("integer");
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString().c_str());
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
{
2021-12-25 10:04:45 +08:00
auto node = parent.append_child("real");
node.append_child(pugi::xml_node_type::node_pcdata).set_value(value.asString().c_str());
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().c_str());
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");
2021-12-25 10:04:45 +08:00
for (const auto& iter : dict)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto key = dictDS.append_child("key");
key.append_child(pugi::xml_node_type::node_pcdata).set_value(iter.first.c_str());
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");
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()
{
CC_SAFE_DELETE(s_sharedFileUtils);
}
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;
}
2021-12-25 10:04:45 +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(const std::string& dataStr, const std::string& fullPath) const
{
return FileUtils::writeBinaryToFile(dataStr.c_str(), 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,
const std::string& fullPath,
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[fullPath](const std::string& dataStrIn) -> bool {
return FileUtils::getInstance()->writeStringToFile(dataStrIn, fullPath);
},
std::move(callback), std::move(dataStr));
2019-11-23 20:27:39 +08:00
}
bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath) const
{
return FileUtils::writeBinaryToFile(data.getBytes(), data.getSize(), fullPath);
}
void FileUtils::writeDataToFile(Data data, const std::string& fullPath, std::function<void(bool)> callback) const
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[fullPath](const Data& dataIn) -> bool { return FileUtils::getInstance()->writeDataToFile(dataIn, fullPath); },
std::move(callback), std::move(data));
}
bool FileUtils::writeBinaryToFile(const void* data, size_t dataSize, const std::string& fullPath)
{
CCASSERT(!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
{
auto fileStream = fileUtils->openFileStream(fullPath, FileStream::Mode::WRITE);
2019-11-23 20:27:39 +08:00
// Read the file from hardware
CC_BREAK_IF(!fileStream);
2019-11-23 20:27:39 +08:00
2021-10-09 13:48:56 +08:00
fileStream->write(data, static_cast<unsigned int>(dataSize));
2019-11-23 20:27:39 +08:00
return true;
} while (0);
return false;
}
bool FileUtils::init()
{
DECLARE_GUARD;
_searchPathArray.push_back(_defaultResRootPath);
2019-11-24 23:15:56 +08:00
_searchResolutionsOrderArray.emplace_back("");
2019-11-23 20:27:39 +08:00
return true;
}
void FileUtils::purgeCachedEntries()
{
DECLARE_GUARD;
_fullPathCache.clear();
_fullPathCacheDir.clear();
}
std::string FileUtils::getStringFromFile(const std::string& filename) const
{
std::string s;
getContents(filename, &s);
return s;
}
2021-12-25 10:04:45 +08:00
void FileUtils::getStringFromFile(const std::string& 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(
[fullPath]() -> std::string { return FileUtils::getInstance()->getStringFromFile(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
Data FileUtils::getDataFromFile(const std::string& filename) const
{
Data d;
getContents(filename, &d);
return d;
}
void FileUtils::getDataFromFile(const std::string& filename, std::function<void(Data)> callback) const
{
auto fullPath = fullPathForFilename(filename);
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() -> Data { return FileUtils::getInstance()->getDataFromFile(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) const
{
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
auto fileStream = fileUtils->openFileStream(fullPath, FileStream::Mode::READ);
if (!fileStream)
2020-08-05 13:10:37 +08:00
return Status::OpenFailed;
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);
2021-04-25 23:05:06 +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;
}
2021-12-25 10:04:45 +08:00
void FileUtils::writeValueMapToFile(ValueMap dict,
const std::string& fullPath,
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[fullPath](const ValueMap& dictIn) -> bool {
return FileUtils::getInstance()->writeValueMapToFile(dictIn, fullPath);
},
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,
const std::string& fullPath,
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[fullPath](const ValueVector& vecDataIn) -> bool {
return FileUtils::getInstance()->writeValueVectorToFile(vecDataIn, fullPath);
},
std::move(callback), std::move(vecData));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::getNewFilename(const std::string& filename) const
2019-11-23 20:27:39 +08:00
{
std::string newFileName;
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
DECLARE_GUARD;
// in Lookup Filename dictionary ?
auto iter = _filenameLookupDict.find(filename);
if (iter == _filenameLookupDict.end())
{
newFileName = filename;
}
else
{
newFileName = iter->second.asString();
}
return newFileName;
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::getPathForFilename(const std::string& filename,
const std::string& resolutionDirectory,
const std::string& searchPath) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
std::string file = filename;
2019-11-23 20:27:39 +08:00
std::string file_path = "";
2021-12-25 10:04:45 +08:00
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;
path += file_path;
path += resolutionDirectory;
path = getFullPathForFilenameWithinDirectory(path, file);
return path;
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::getPathForDirectory(const std::string& dir,
const std::string& resolutionDiretory,
const std::string& searchPath) const
2019-11-23 20:27:39 +08:00
{
return searchPath + resolutionDiretory + dir;
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::fullPathForFilename(const std::string& 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 filename;
}
// 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;
}
// Get the new file name.
2021-12-25 10:04:45 +08:00
const std::string newFilename(getNewFilename(filename));
2019-11-23 20:27:39 +08:00
std::string fullpath;
for (const auto& searchIt : _searchPathArray)
{
for (const auto& resolutionIt : _searchResolutionsOrderArray)
{
fullpath = this->getPathForFilename(newFilename, resolutionIt, searchIt);
if (!fullpath.empty())
{
// Using the filename passed in as key.
_fullPathCache.emplace(filename, fullpath);
return fullpath;
}
}
}
2021-12-25 10:04:45 +08:00
if (isPopupNotify())
{
2019-11-23 20:27:39 +08:00
CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename.c_str());
}
// The file wasn't found, return empty string.
return "";
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::fullPathForDirectory(const std::string& dir) const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
if (dir.empty())
{
return "";
}
if (isAbsolutePath(dir))
{
return dir;
}
// 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;
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
}
2021-12-25 10:04:45 +08:00
const std::string newdirname(getNewFilename(longdir));
2019-11-23 20:27:39 +08:00
for (const auto& searchIt : _searchPathArray)
{
for (const auto& resolutionIt : _searchResolutionsOrderArray)
{
fullpath = this->getPathForDirectory(newdirname, resolutionIt, searchIt);
if (!fullpath.empty() && isDirectoryExistInternal(fullpath))
{
// Using the filename passed in as key.
_fullPathCacheDir.emplace(dir, fullpath);
return fullpath;
}
}
}
2021-12-25 10:04:45 +08:00
if (isPopupNotify())
{
2019-11-23 20:27:39 +08:00
CCLOG("cocos2d: fullPathForDirectory: No directory found at %s. Possible missing directory.", dir.c_str());
}
// The file wasn't found, return empty string.
return "";
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::fullPathFromRelativeFile(const std::string& filename, const std::string& relativeFile) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
return relativeFile.substr(0, relativeFile.rfind('/') + 1) + getNewFilename(filename);
2019-11-23 20:27:39 +08:00
}
void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
{
DECLARE_GUARD;
if (_searchResolutionsOrderArray == searchResolutionsOrder)
{
return;
}
bool existDefault = false;
_fullPathCache.clear();
_fullPathCacheDir.clear();
_searchResolutionsOrderArray.clear();
2021-12-25 10:04:45 +08:00
for (const auto& iter : searchResolutionsOrder)
2019-11-23 20:27:39 +08:00
{
std::string resolutionDirectory = iter;
if (!existDefault && resolutionDirectory == "")
{
existDefault = true;
}
2021-12-25 10:04:45 +08:00
if (!resolutionDirectory.empty() && resolutionDirectory[resolutionDirectory.length() - 1] != '/')
2019-11-23 20:27:39 +08:00
{
resolutionDirectory += "/";
}
_searchResolutionsOrderArray.push_back(resolutionDirectory);
}
if (!existDefault)
{
_searchResolutionsOrderArray.push_back("");
}
}
2021-12-25 10:04:45 +08:00
void FileUtils::addSearchResolutionsOrder(const std::string& order, const bool front)
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;
std::string resOrder = order;
2021-12-25 10:04:45 +08:00
if (!resOrder.empty() && resOrder[resOrder.length() - 1] != '/')
resOrder.push_back('/');
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
if (front)
{
2019-11-23 20:27:39 +08:00
_searchResolutionsOrderArray.insert(_searchResolutionsOrderArray.begin(), resOrder);
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
_searchResolutionsOrderArray.push_back(resOrder);
}
}
const std::vector<std::string> FileUtils::getSearchResolutionsOrder() const
{
DECLARE_GUARD;
return _searchResolutionsOrderArray;
}
const std::vector<std::string> FileUtils::getSearchPaths() const
{
DECLARE_GUARD;
return _searchPathArray;
}
const std::vector<std::string> FileUtils::getOriginalSearchPaths() const
{
DECLARE_GUARD;
return _originalSearchPaths;
}
void FileUtils::setWritablePath(const std::string& writablePath)
{
DECLARE_GUARD;
_writablePath = writablePath;
}
const std::string FileUtils::getDefaultResourceRootPath() const
{
DECLARE_GUARD;
return _defaultResRootPath;
}
void FileUtils::setDefaultResourceRootPath(const std::string& path)
{
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.push_back(fullPath);
}
if (!existDefaultRootPath)
{
2021-12-25 10:04:45 +08:00
// CCLOG("Default root path doesn't exist, adding it.");
2019-11-23 20:27:39 +08:00
_searchPathArray.push_back(_defaultResRootPath);
}
}
2021-12-25 10:04:45 +08:00
void FileUtils::addSearchPath(const std::string& searchpath, const bool front)
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
std::string prefix;
if (!isAbsolutePath(searchpath))
prefix = _defaultResRootPath;
std::string path = prefix + 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 += "/";
}
2021-12-25 10:04:45 +08:00
if (front)
{
2019-11-23 20:27:39 +08:00
_originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath);
_searchPathArray.insert(_searchPathArray.begin(), path);
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
_originalSearchPaths.push_back(searchpath);
_searchPathArray.push_back(path);
}
}
void FileUtils::setFilenameLookupDictionary(const ValueMap& filenameLookupDict)
{
DECLARE_GUARD;
_fullPathCache.clear();
_fullPathCacheDir.clear();
_filenameLookupDict = filenameLookupDict;
}
2021-12-25 10:04:45 +08:00
void FileUtils::loadFilenameLookupDictionaryFromFile(const std::string& filename)
2019-11-23 20:27:39 +08:00
{
const std::string fullPath = fullPathForFilename(filename);
if (!fullPath.empty())
{
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
if (!dict.empty())
{
2021-12-25 10:04:45 +08:00
ValueMap& metadata = dict["metadata"].asValueMap();
int version = metadata["version"].asInt();
2019-11-23 20:27:39 +08:00
if (version != 1)
{
2021-12-25 10:04:45 +08:00
CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %d. Filename: %s", version,
filename.c_str());
2019-11-23 20:27:39 +08:00
return;
}
2021-12-25 10:04:45 +08:00
setFilenameLookupDictionary(dict["filenames"].asValueMap());
2019-11-23 20:27:39 +08:00
}
}
}
2021-12-25 10:04:45 +08:00
std::string FileUtils::getFullPathForFilenameWithinDirectory(const std::string& directory,
const std::string& filename) const
2019-11-23 20:27:39 +08:00
{
// get directory+filename, safely adding '/' as necessary
std::string ret = directory;
2021-12-25 10:04:45 +08:00
if (directory.size() && directory[directory.size() - 1] != '/')
{
2019-11-23 20:27:39 +08:00
ret += '/';
}
ret += filename;
// if the file doesn't exist, return an empty string
2021-12-25 10:04:45 +08:00
if (!isFileExistInternal(ret))
{
2019-11-23 20:27:39 +08:00
ret = "";
}
return ret;
}
bool FileUtils::isFileExist(const std::string& filename) const
{
if (isAbsolutePath(filename))
{
return isFileExistInternal(filename);
}
else
{
std::string fullpath = fullPathForFilename(filename);
if (fullpath.empty())
return false;
else
return true;
}
}
void FileUtils::isFileExist(const std::string& filename, std::function<void(bool)> callback) const
{
auto fullPath = fullPathForFilename(filename);
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isFileExist(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
bool FileUtils::isAbsolutePath(const std::string& path) const
{
return isAbsolutePathInternal(path);
}
bool FileUtils::isAbsolutePathInternal(const std::string& path)
{
#if defined(_WIN32)
// see also: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN
return ((path.length() > 2 && ((path[0] >= 'a' && path[0] <= 'z') || (path[0] >= 'A' && path[0] <= 'Z')) &&
path[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
|| (path[0] == '/' || path[0] == '\\') // Current disk drive
);
#else
2019-11-23 20:27:39 +08:00
return (path[0] == '/');
#endif
2019-11-23 20:27:39 +08:00
}
bool FileUtils::isDirectoryExist(const std::string& dirPath) const
{
CCASSERT(!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(const std::string& fullPath, std::function<void(bool)> callback) const
{
CCASSERT(isAbsolutePath(fullPath), "Async isDirectoryExist only accepts absolute file paths");
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->isDirectoryExist(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::createDirectory(const std::string& dirPath, std::function<void(bool)> callback) const
{
2021-12-25 10:04:45 +08:00
performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->createDirectory(dirPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::removeDirectory(const std::string& dirPath, std::function<void(bool)> callback) const
{
2021-12-25 10:04:45 +08:00
performOperationOffthread([dirPath]() -> bool { return FileUtils::getInstance()->removeDirectory(dirPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::removeFile(const std::string& filepath, std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filepath);
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() -> bool { return FileUtils::getInstance()->removeFile(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::renameFile(const std::string& path,
const std::string& oldname,
const std::string& name,
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[path, oldname, name]() -> bool { return FileUtils::getInstance()->renameFile(path, oldname, name); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::renameFile(const std::string& oldfullpath,
const std::string& newfullpath,
std::function<void(bool)> callback) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
performOperationOffthread(
[oldfullpath, newfullpath]() { return FileUtils::getInstance()->renameFile(oldfullpath, newfullpath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::getFileSize(const std::string& filepath, std::function<void(int64_t)> callback) const
2019-11-23 20:27:39 +08:00
{
auto fullPath = fullPathForFilename(filepath);
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() { return FileUtils::getInstance()->getFileSize(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
void FileUtils::listFilesAsync(const std::string& dirPath, std::function<void(std::vector<std::string>)> callback) const
{
auto fullPath = fullPathForDirectory(dirPath);
2021-12-25 10:04:45 +08:00
performOperationOffthread([fullPath]() { return FileUtils::getInstance()->listFiles(fullPath); },
std::move(callback));
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void FileUtils::listFilesRecursivelyAsync(const std::string& dirPath,
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(
[fullPath]() {
std::vector<std::string> retval;
FileUtils::getInstance()->listFilesRecursively(fullPath, &retval);
return retval;
},
std::move(callback));
2019-11-23 20:27:39 +08:00
}
std::unique_ptr<FileStream> FileUtils::openFileStream(const std::string& filePath, FileStream::Mode mode)
{
PosixFileStream fs;
if (fs.open(filePath, mode))
{
2021-12-25 10:04:45 +08:00
return std::make_unique<PosixFileStream>(std::move(fs)); // PosixFileStream is the default implementation
}
return nullptr;
}
2019-11-23 20:27:39 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
// windows os implement should override in platform specific FileUtiles class
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
return false;
}
bool FileUtils::createDirectory(const std::string& path) const
{
CCASSERT(false, "FileUtils not support createDirectory");
return false;
}
bool FileUtils::removeDirectory(const std::string& path) const
{
CCASSERT(false, "FileUtils not support removeDirectory");
return false;
}
2021-12-25 10:04:45 +08:00
bool FileUtils::removeFile(const std::string& path) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(false, "FileUtils not support removeFile");
return false;
}
2021-12-25 10:04:45 +08:00
bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(false, "FileUtils not support renameFile");
return false;
}
2021-12-25 10:04:45 +08:00
bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(false, "FileUtils not support renameFile");
return false;
}
2021-12-25 10:04:45 +08:00
int64_t FileUtils::getFileSize(const std::string& filepath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(false, "getFileSize should be override by platform FileUtils");
return 0;
}
std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
{
CCASSERT(false, "FileUtils not support listFiles");
return std::vector<std::string>();
}
2021-12-25 10:04:45 +08:00
void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string>* files) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(false, "FileUtils not support listFilesRecursively");
return;
}
#else
2021-12-25 10:04:45 +08:00
# include "tinydir/tinydir.h"
2019-11-23 20:27:39 +08:00
// 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
2021-12-25 10:04:45 +08:00
# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
# include <ftw.h>
# endif
2019-11-23 20:27:39 +08:00
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
}
bool FileUtils::createDirectory(const std::string& path) const
{
CCASSERT(!path.empty(), "Invalid path");
if (isDirectoryExist(path))
return true;
// Split the path
size_t start = 0;
size_t found = path.find_first_of("/\\", start);
std::string subpath;
std::vector<std::string> dirs;
if (found != std::string::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.push_back(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.push_back(path.substr(start));
}
break;
}
}
}
2021-12-25 10:04:45 +08:00
DIR* dir = NULL;
2019-11-23 20:27:39 +08:00
// Create path recursively
subpath = "";
for (const auto& iter : dirs)
{
subpath += iter;
dir = opendir(subpath.c_str());
if (!dir)
{
// directory doesn't exist, should create a new one
int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
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
{
2021-12-25 10:04:45 +08:00
# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
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(const std::string& path) const
{
2021-12-25 10:04:45 +08:00
# if !defined(CC_TARGET_OS_TVOS)
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
# if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
2019-11-23 20:27:39 +08:00
if (nftw(path.c_str(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1)
return false;
else
return true;
2021-12-25 10:04:45 +08:00
# else
2019-11-23 20:27:39 +08:00
std::string command = "rm -r ";
// Path may include space.
command += "\"" + path + "\"";
if (system(command.c_str()) >= 0)
return true;
else
return false;
2021-12-25 10:04:45 +08:00
# endif // (CC_TARGET_PLATFORM != CC_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;
2021-12-25 10:04:45 +08:00
# endif // !defined(CC_TARGET_OS_TVOS)
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
bool FileUtils::removeFile(const std::string& path) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (remove(path.c_str()))
{
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;
}
}
2021-12-25 10:04:45 +08:00
bool FileUtils::renameFile(const std::string& oldfullpath, const std::string& newfullpath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!oldfullpath.empty(), "Invalid path");
CCASSERT(!newfullpath.empty(), "Invalid path");
int errorCode = rename(oldfullpath.c_str(), newfullpath.c_str());
if (0 != errorCode)
{
2021-12-25 10:04:45 +08:00
CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldfullpath.c_str(), newfullpath.c_str(),
errorCode);
2019-11-23 20:27:39 +08:00
return false;
}
return true;
}
2021-12-25 10:04:45 +08:00
bool FileUtils::renameFile(const std::string& path, const std::string& oldname, const std::string& name) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!path.empty(), "Invalid path");
std::string oldPath = path + oldname;
std::string newPath = path + name;
return this->renameFile(oldPath, newPath);
}
2021-12-25 10:04:45 +08:00
int64_t FileUtils::getFileSize(const std::string& filepath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!filepath.empty(), "Invalid path");
std::string fullpath = filepath;
if (!isAbsolutePath(filepath))
{
fullpath = fullPathForFilename(filepath);
if (fullpath.empty())
return 0;
}
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":
2019-11-28 09:59:18 +08:00
int result = ::stat(fullpath.c_str(), &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
}
}
std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
{
std::vector<std::string> files;
std::string fullpath = fullPathForDirectory(dirPath);
if (!fullpath.empty() && isDirectoryExist(fullpath))
{
tinydir_dir dir;
std::string fullpathstr = fullpath;
if (tinydir_open(&dir, &fullpathstr[0]) != -1)
{
while (dir.has_next)
{
tinydir_file file;
if (tinydir_readfile(&dir, &file) == -1)
{
// Error getting file
break;
}
std::string filepath = file.path;
2021-12-25 10:04:45 +08:00
if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0)
2019-11-23 20:27:39 +08:00
{
2020-08-28 11:04:14 +08:00
if (file.is_dir)
filepath.push_back('/');
files.push_back(std::move(filepath));
2019-11-23 20:27:39 +08:00
}
if (tinydir_next(&dir) == -1)
{
// Error getting next file
break;
}
}
}
tinydir_close(&dir);
}
return files;
}
2021-12-25 10:04:45 +08:00
void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string>* files) const
2019-11-23 20:27:39 +08:00
{
std::string fullpath = fullPathForDirectory(dirPath);
if (isDirectoryExist(fullpath))
{
tinydir_dir dir;
std::string fullpathstr = fullpath;
if (tinydir_open(&dir, &fullpathstr[0]) != -1)
{
while (dir.has_next)
{
tinydir_file file;
if (tinydir_readfile(&dir, &file) == -1)
{
// Error getting file
break;
}
2021-12-25 10:04:45 +08:00
if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0)
2019-11-23 20:27:39 +08:00
{
std::string filepath = file.path;
if (file.is_dir)
{
filepath.push_back('/');
2019-11-23 20:27:39 +08:00
files->push_back(filepath);
listFilesRecursively(filepath, files);
}
else
{
2020-08-28 11:04:14 +08:00
files->push_back(std::move(filepath));
2019-11-23 20:27:39 +08:00
}
}
if (tinydir_next(&dir) == -1)
{
// Error getting next file
break;
}
}
}
tinydir_close(&dir);
}
}
#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(const std::string& filePath) const
{
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;
}
2020-08-01 19:25:39 +08:00
std::string FileUtils::getFileShortName(const std::string& filePath)
{
std::string fileExtension;
size_t pos = filePath.find_last_of("/\\");
if (pos != std::string::npos)
{
return filePath.substr(pos + 1);
}
return filePath;
}
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_CC_END