axmol/cocos/platform/win32/CCFileUtils-win32.cpp

562 lines
17 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2021 Bytedance Inc.
2019-11-23 20:27:39 +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/win32/CCFileUtils-win32.h"
#include "platform/CCCommon.h"
#include "tinydir/tinydir.h"
#include <Shlobj.h>
#include <cstdlib>
#include <regex>
#include <sstream>
2021-12-25 10:04:45 +08:00
#include <sys/types.h>
#include <sys/stat.h>
2019-11-23 20:27:39 +08:00
2021-11-26 17:19:50 +08:00
#include "ntcvt/ntcvt.hpp"
2021-12-25 10:04:45 +08:00
#define DECLARE_GUARD (void)0 // std::lock_guard<std::recursive_mutex> mutexGuard(_mutex)
2019-11-23 20:27:39 +08:00
NS_CC_BEGIN
2021-12-25 10:04:45 +08:00
#define CC_MAX_PATH 512
2019-11-23 20:27:39 +08:00
// The root path of resources, the character encoding is UTF-8.
2021-07-04 21:21:29 +08:00
// UTF-8 is the only encoding supported by adxe API by default.
2021-12-26 23:26:34 +08:00
static std::wstring s_workingPath;
static std::string s_exePath;
2019-11-23 20:27:39 +08:00
// D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
2021-12-26 23:26:34 +08:00
static std::string convertPathFormatToUnixStyle(std::string_view path)
2019-11-23 20:27:39 +08:00
{
2021-12-26 23:26:34 +08:00
std::string ret{path};
2021-12-25 10:04:45 +08:00
int len = ret.length();
2019-11-23 20:27:39 +08:00
for (int i = 0; i < len; ++i)
{
if (ret[i] == '\\')
{
ret[i] = '/';
}
}
return ret;
}
2021-12-26 23:26:34 +08:00
static std::string convertPathFormatToWinStyle(std::string_view path)
{
std::string ret{path};
int len = ret.length();
for (int i = 0; i < len; ++i)
{
if (ret[i] == '/')
{
ret[i] = '\\';
}
}
return ret;
}
static void _checkWorkingPath()
2019-11-23 20:27:39 +08:00
{
if (s_workingPath.empty())
2019-11-23 20:27:39 +08:00
{
WCHAR utf16Path[CC_MAX_PATH] = {0};
int nNum = GetCurrentDirectoryW(CC_MAX_PATH - 2, utf16Path);
2021-12-26 23:26:34 +08:00
s_workingPath.assign(utf16Path, nNum);
//char utf8WorkingDir[CC_MAX_PATH] = {0};
//nNum =
// WideCharToMultiByte(CP_UTF8, 0, utf16Path, nNum, utf8WorkingDir, sizeof(utf8WorkingDir), nullptr, nullptr);
//if (nNum < (CC_MAX_PATH - 2))
//{
// utf8WorkingDir[nNum] = '\\';
// utf8WorkingDir[nNum + 1] = '\0';
// s_workingPath = convertPathFormatToUnixStyle(utf8WorkingDir);
//}
}
}
static void _checkExePath()
{
if (s_exePath.empty())
{
WCHAR utf16Path[CC_MAX_PATH] = {0};
2019-11-23 20:27:39 +08:00
GetModuleFileNameW(NULL, utf16Path, CC_MAX_PATH - 1);
WCHAR* pUtf16ExePath = &(utf16Path[0]);
2019-11-23 20:27:39 +08:00
// We need only directory part without exe
WCHAR* pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\');
2019-11-23 20:27:39 +08:00
auto utf8ExeDir = ntcvt::wcbs2a<std::string>(pUtf16ExePath, pUtf16DirEnd - pUtf16ExePath + 1);
2019-11-23 20:27:39 +08:00
s_exePath = convertPathFormatToUnixStyle(utf8ExeDir);
2019-11-23 20:27:39 +08:00
}
}
FileUtils* FileUtils::getInstance()
{
if (s_sharedFileUtils == nullptr)
{
s_sharedFileUtils = new FileUtilsWin32();
2021-12-25 10:04:45 +08:00
if (!s_sharedFileUtils->init())
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
delete s_sharedFileUtils;
s_sharedFileUtils = nullptr;
CCLOG("ERROR: Could not init CCFileUtilsWin32");
2019-11-23 20:27:39 +08:00
}
}
return s_sharedFileUtils;
}
2021-12-25 10:04:45 +08:00
FileUtilsWin32::FileUtilsWin32() {}
2019-11-23 20:27:39 +08:00
bool FileUtilsWin32::init()
{
DECLARE_GUARD;
_checkWorkingPath();
2021-12-26 23:26:34 +08:00
_defaultResRootPath = ntcvt::from_chars(s_workingPath);
_defaultResRootPathUtf16 = s_workingPath;
bool bRet = FileUtils::init();
_checkExePath();
2021-12-26 23:26:34 +08:00
if (_defaultResRootPath != s_exePath)
addSearchPath(s_exePath);
return bRet;
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::isDirectoryExistInternal(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
uint32_t fAttrib = GetFileAttributesW(ntcvt::from_chars(dirPath).c_str());
2021-12-25 10:04:45 +08:00
return (fAttrib != INVALID_FILE_ATTRIBUTES && (fAttrib & FILE_ATTRIBUTE_DIRECTORY));
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::isFileExistInternal(std::string_view strFilePath) const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
if (strFilePath.empty())
{
return false;
}
2021-12-26 23:26:34 +08:00
std::wstring strPathUtf16;
if (!isAbsolutePath(strFilePath))
2021-12-25 10:04:45 +08:00
{ // Not absolute path, add the default root path at the beginning.
2021-12-26 23:26:34 +08:00
strPathUtf16.insert(0, _defaultResRootPathUtf16);
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
else
strPathUtf16 = ntcvt::from_chars(strFilePath);
2019-11-23 20:27:39 +08:00
2021-12-26 23:26:34 +08:00
DWORD attr = GetFileAttributesW(strPathUtf16.c_str());
return (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY));
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
FileUtils::Status FileUtilsWin32::getContents(std::string_view filename, ResizableBuffer* buffer) const
2019-11-23 20:27:39 +08:00
{
if (filename.empty())
return FileUtils::Status::NotExists;
// read the file from hardware
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
2021-12-25 10:04:45 +08:00
HANDLE fileHandle = ::CreateFileW(ntcvt::from_chars(fullPath).c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
2019-11-23 20:27:39 +08:00
if (fileHandle == INVALID_HANDLE_VALUE)
return FileUtils::Status::OpenFailed;
2021-12-25 10:04:45 +08:00
DWORD hi;
2019-11-23 20:27:39 +08:00
auto size = ::GetFileSize(fileHandle, &hi);
2021-12-25 10:04:45 +08:00
if (hi > 0)
{
::CloseHandle(fileHandle);
return FileUtils::Status::TooLarge;
}
2019-11-23 20:27:39 +08:00
// don't read file content if it is empty
if (size == 0)
{
::CloseHandle(fileHandle);
return FileUtils::Status::OK;
}
buffer->resize(size);
DWORD sizeRead = 0;
BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr);
::CloseHandle(fileHandle);
2021-12-25 10:04:45 +08:00
if (!successed)
{
CCLOG("Get data from file(%s) failed, error code is %s", filename.data(),
std::to_string(::GetLastError()).data());
buffer->resize(sizeRead);
return FileUtils::Status::ReadFailed;
2019-11-23 20:27:39 +08:00
}
return FileUtils::Status::OK;
}
2021-12-26 23:26:34 +08:00
std::string FileUtilsWin32::getPathForFilename(std::string_view filename,
std::string_view resolutionDirectory,
std::string_view searchPath) const
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
std::string unixFileName = convertPathFormatToUnixStyle(filename);
2019-11-23 20:27:39 +08:00
std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
2021-12-25 10:04:45 +08:00
std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath);
2019-11-23 20:27:39 +08:00
return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
}
2021-12-26 23:26:34 +08:00
std::string FileUtilsWin32::getFullPathForFilenameWithinDirectory(std::string_view strDirectory,
std::string_view strFilename) const
2019-11-23 20:27:39 +08:00
{
std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
2021-12-25 10:04:45 +08:00
std::string unixFilename = convertPathFormatToUnixStyle(strFilename);
2019-11-23 20:27:39 +08:00
return FileUtils::getFullPathForFilenameWithinDirectory(unixDirectory, unixFilename);
}
2021-12-26 23:26:34 +08:00
void FileUtilsWin32::listFilesRecursively(std::string_view dirPath, std::vector<std::string>* files) const
2019-11-23 20:27:39 +08:00
{
std::string fullpath = fullPathForDirectory(dirPath);
2019-11-23 20:27:39 +08:00
if (isDirectoryExist(fullpath))
{
tinydir_dir dir;
std::wstring fullpathstr = ntcvt::from_chars(fullpath);
2019-11-23 20:27:39 +08:00
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 fileName = ntcvt::from_chars(file.name);
2019-11-23 20:27:39 +08:00
if (fileName != "." && fileName != "..")
{
std::string filepath = ntcvt::from_chars(file.path);
2019-11-23 20:27:39 +08:00
if (file.is_dir)
{
filepath.push_back('/');
2019-11-23 20:27:39 +08:00
files->push_back(filepath);
listFilesRecursively(filepath, files);
}
else
{
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);
}
}
2021-12-26 23:26:34 +08:00
int64_t FileUtilsWin32::getFileSize(std::string_view filepath) const
2019-11-23 20:27:39 +08:00
{
if (filepath.empty())
return -1;
2021-12-25 10:04:45 +08:00
WIN32_FILE_ATTRIBUTE_DATA attrs = {0};
if (GetFileAttributesExW(ntcvt::from_chars(filepath).c_str(), GetFileExInfoStandard, &attrs) &&
!(attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2021-12-25 10:04:45 +08:00
return static_cast<long long>(attrs.nFileSizeHigh) << 32 | static_cast<unsigned long long>(attrs.nFileSizeLow);
return -1;
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
std::vector<std::string> FileUtilsWin32::listFiles(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
std::string fullpath = fullPathForDirectory(dirPath);
std::vector<std::string> files;
if (isDirectoryExist(fullpath))
{
tinydir_dir dir;
std::wstring fullpathstr = ntcvt::from_chars(fullpath);
2019-11-23 20:27:39 +08:00
if (tinydir_open(&dir, &fullpathstr[0]) != -1)
{
while (dir.has_next)
{
tinydir_file file;
if (tinydir_readfile(&dir, &file) == -1)
{
// Error getting file
break;
}
2020-08-01 19:25:39 +08:00
std::string fileName = ntcvt::from_chars(file.name);
if (fileName != "." && fileName != "..")
2019-11-23 20:27:39 +08:00
{
2020-08-01 19:25:39 +08:00
std::string filepath = ntcvt::from_chars(file.path);
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-07-04 21:21:29 +08:00
std::string FileUtilsWin32::getWritablePath() const
{
DECLARE_GUARD;
return getNativeWritableAbsolutePath();
}
std::string FileUtilsWin32::getNativeWritableAbsolutePath() const
2019-11-23 20:27:39 +08:00
{
DECLARE_GUARD;
if (_writablePath.length())
{
return _writablePath;
}
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
2021-12-25 10:04:45 +08:00
WCHAR full_path[CC_MAX_PATH + 1] = {0};
::GetModuleFileNameW(nullptr, full_path, CC_MAX_PATH + 1);
2019-11-23 20:27:39 +08:00
// Debug app uses executable directory; Non-debug app uses local app data directory
2021-12-25 10:04:45 +08:00
//#ifndef _DEBUG
2019-11-23 20:27:39 +08:00
// Get filename of executable only, e.g. MyGame.exe
WCHAR* base_name = wcsrchr(full_path, '\\');
2021-07-04 21:21:29 +08:00
std::wstring retPath;
if (base_name)
2019-11-23 20:27:39 +08:00
{
WCHAR app_data_path[CC_MAX_PATH + 1];
// Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
2019-11-23 20:27:39 +08:00
{
2021-07-04 21:21:29 +08:00
std::wstring ret(app_data_path);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
// Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application
// Data\MyGame.exe
2019-11-23 20:27:39 +08:00
ret += base_name;
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(0, ret.rfind(L"."));
ret += L"\\";
// Create directory
if (SUCCEEDED(SHCreateDirectoryExW(nullptr, ret.c_str(), nullptr)))
2019-11-23 20:27:39 +08:00
{
retPath = ret;
}
}
}
if (retPath.empty())
2021-12-25 10:04:45 +08:00
//#endif // not defined _DEBUG
2019-11-23 20:27:39 +08:00
{
// If fetching of local app data directory fails, use the executable one
retPath = full_path;
// remove xxx.exe
retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
}
return convertPathFormatToUnixStyle(ntcvt::from_chars(retPath));
2019-11-23 20:27:39 +08:00
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::renameFile(std::string_view oldfullpath, std::string_view newfullpath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!oldfullpath.empty(), "Invalid path");
CCASSERT(!newfullpath.empty(), "Invalid path");
std::wstring _wNew = ntcvt::from_chars(newfullpath);
std::wstring _wOld = ntcvt::from_chars(oldfullpath);
2019-11-23 20:27:39 +08:00
if (FileUtils::getInstance()->isFileExist(newfullpath))
{
if (!DeleteFile(_wNew.c_str()))
{
2021-12-26 23:26:34 +08:00
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newfullpath.data(), GetLastError());
2019-11-23 20:27:39 +08:00
}
}
if (MoveFileW(_wOld.c_str(), _wNew.c_str()))
2019-11-23 20:27:39 +08:00
{
return true;
}
else
{
2021-12-26 23:26:34 +08:00
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldfullpath.data(), newfullpath.data(),
2021-12-25 10:04:45 +08:00
GetLastError());
2019-11-23 20:27:39 +08:00
return false;
}
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::renameFile(std::string_view path, std::string_view oldname, std::string_view name) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!path.empty(), "Invalid path");
2021-12-26 23:26:34 +08:00
std::string oldPath{path};
oldPath += oldname;
std::string newPath{path};
newPath += name;
2019-11-23 20:27:39 +08:00
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
return renameFile(_old, _new);
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::createDirectory(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
CCASSERT(!dirPath.empty(), "Invalid path");
if (isDirectoryExist(dirPath))
return true;
std::wstring path = ntcvt::from_chars(dirPath);
2019-11-23 20:27:39 +08:00
// Split the path
size_t start = 0;
size_t found = path.find_first_of(L"/\\", start);
std::wstring subpath;
std::vector<std::wstring> dirs;
if (found != std::wstring::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.push_back(subpath);
start = found + 1;
found = path.find_first_of(L"/\\", start);
if (found == std::wstring::npos)
{
if (start < path.length())
{
dirs.push_back(path.substr(start));
}
break;
}
}
}
if ((GetFileAttributesW(path.c_str())) == INVALID_FILE_ATTRIBUTES)
2019-11-23 20:27:39 +08:00
{
subpath = L"";
for (unsigned int i = 0, size = dirs.size(); i < size; ++i)
{
subpath += dirs[i];
std::string utf8Path = ntcvt::from_chars(subpath);
2019-11-23 20:27:39 +08:00
if (!isDirectoryExist(utf8Path))
{
BOOL ret = CreateDirectoryW(subpath.c_str(), NULL);
2019-11-23 20:27:39 +08:00
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
return false;
}
}
}
}
return true;
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::removeFile(std::string_view filepath) const
2019-11-23 20:27:39 +08:00
{
2021-12-26 23:26:34 +08:00
std::string win32path = convertPathFormatToWinStyle(filepath);
2019-11-23 20:27:39 +08:00
if (DeleteFileW(ntcvt::from_chars(win32path).c_str()))
2019-11-23 20:27:39 +08:00
{
return true;
}
else
{
2021-12-26 23:26:34 +08:00
CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.data(), GetLastError());
2019-11-23 20:27:39 +08:00
return false;
}
}
2021-12-26 23:26:34 +08:00
bool FileUtilsWin32::removeDirectory(std::string_view dirPath) const
2019-11-23 20:27:39 +08:00
{
2021-12-26 23:26:34 +08:00
std::string dirPathCopy{dirPath};
2020-08-18 14:29:09 +08:00
if (!dirPath.empty() && dirPath[dirPath.length() - 1] != '/' && dirPath[dirPath.length() - 1] != '\\')
2019-11-23 20:27:39 +08:00
{
dirPathCopy.push_back('/');
2019-11-23 20:27:39 +08:00
}
std::wstring wpath = ntcvt::from_chars(dirPathCopy);
2019-11-23 20:27:39 +08:00
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
2021-12-25 10:04:45 +08:00
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret = true;
2019-11-23 20:27:39 +08:00
if (search != INVALID_HANDLE_VALUE)
{
BOOL find = true;
while (find)
{
// Need check string . and .. for delete folders and files begin name.
std::wstring fileName = wfd.cFileName;
if (fileName != L"." && fileName != L"..")
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(ntcvt::from_chars(temp));
2019-11-23 20:27:39 +08:00
}
else
{
SetFileAttributesW(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFileW(temp.c_str());
2019-11-23 20:27:39 +08:00
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectoryW(wpath.c_str()))
2019-11-23 20:27:39 +08:00
{
return true;
}
return false;
}
NS_CC_END