Fix indent with clang-format [ci build]

This commit is contained in:
halx99 2021-04-24 16:57:26 +08:00
parent dd69c21c0e
commit 01f2ce3a2d
2 changed files with 942 additions and 852 deletions

184
.clang-format Normal file
View File

@ -0,0 +1,184 @@
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# https://releases.llvm.org/12.0.0/tools/clang/docs/ClangFormatStyleOptions.html
---
# Language: Cpp
BasedOnStyle: LLVM
# AccessModifierOffset: -2
AccessModifierOffset: -4
# AlignAfterOpenBracket: Align
AlignAfterOpenBracket: DontAlign
# AlignConsecutiveMacros: false
AlignConsecutiveMacros: true
# AlignConsecutiveAssignments: false
AlignConsecutiveAssignments: true
# AlignConsecutiveBitFields: false
# AlignConsecutiveDeclarations: false
# AlignEscapedNewlines: Right
AlignEscapedNewlines: Left
# AlignOperands: Align
AlignOperands: AlignAfterOperator
# AlignTrailingComments: true
AlignTrailingComments: false
# AllowAllArgumentsOnNextLine: true
# AllowAllConstructorInitializersOnNextLine: true
# AllowAllParametersOfDeclarationOnNextLine: true
# AllowShortEnumsOnASingleLine: true
# AllowShortBlocksOnASingleLine: Never
# AllowShortCaseLabelsOnASingleLine: false
# AllowShortFunctionsOnASingleLine: All
AllowShortFunctionsOnASingleLine: Empty
# AllowShortLambdasOnASingleLine: All
# AllowShortIfStatementsOnASingleLine: Never
# AllowShortLoopsOnASingleLine: false
# AlwaysBreakAfterDefinitionReturnType: None
# AlwaysBreakAfterReturnType: None
# AlwaysBreakBeforeMultilineStrings: false
# AlwaysBreakTemplateDeclarations: MultiLine
AlwaysBreakTemplateDeclarations: Yes
# BinPackArguments: true
# BinPackParameters: true
# BraceWrapping:
# AfterCaseLabel: false
# AfterClass: false
# AfterControlStatement: Never
# AfterEnum: false
# AfterFunction: false
# AfterNamespace: false
# AfterObjCDeclaration: false
# AfterStruct: false
# AfterUnion: false
# AfterExternBlock: false
# BeforeCatch: false
# BeforeElse: false
# BeforeLambdaBody: false
# BeforeWhile: false
# IndentBraces: false
# SplitEmptyFunction: true
# SplitEmptyRecord: true
# SplitEmptyNamespace: true
# BreakBeforeBinaryOperators: None
BreakBeforeBinaryOperators: NonAssignment
# BreakBeforeBraces: Attach
# BreakBeforeInheritanceComma: false
# BreakInheritanceList: BeforeColon
# BreakBeforeTernaryOperators: true
# BreakConstructorInitializersBeforeComma: false
# BreakConstructorInitializers: BeforeColon
# BreakAfterJavaFieldAnnotations: false
# BreakStringLiterals: true
# ColumnLimit: 80
ColumnLimit: 120
# CommentPragmas: '^ IWYU pragma:'
# CompactNamespaces: false
# ConstructorInitializerAllOnOneLineOrOnePerLine: false
# ConstructorInitializerIndentWidth: 4
# ContinuationIndentWidth: 4
# Cpp11BracedListStyle: true
# DeriveLineEnding: true
DeriveLineEnding: false
# DerivePointerAlignment: false
# DisableFormat: false
# ExperimentalAutoDetectBinPacking: false
# FixNamespaceComments: true
# ForEachMacros:
# - foreach
# - Q_FOREACH
# - BOOST_FOREACH
# IncludeBlocks: Preserve
IncludeBlocks: Regroup
# IncludeCategories:
# - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
# Priority: 2
# SortPriority: 0
# - Regex: '^(<|"(gtest|gmock|isl|json)/)'
# Priority: 3
# SortPriority: 0
# - Regex: '.*'
# Priority: 1
# SortPriority: 0
IncludeCategories:
- Regex: '^<yvals(_core)?\.h>$'
Priority: 1
- Regex: '^<(Windows|userenv)\.h>$'
Priority: 3
SortPriority: 3
- Regex: '^<WinIoCtl\.h>$'
Priority: 3
SortPriority: 4
- Regex: '^<__.*\.hpp>$'
Priority: 2
- Regex: '\.hpp[>"]$'
Priority: 5
- Regex: '.*'
Priority: 2
# IncludeIsMainRegex: '(Test)?$'
# IncludeIsMainSourceRegex: ''
# IndentCaseLabels: false
# IndentCaseBlocks: false
IndentCaseBlocks: true
# IndentGotoLabels: true
# IndentPPDirectives: None
# IndentExternBlock: AfterExternBlock
# IndentWidth: 2
IndentWidth: 4
# IndentWrappedFunctionNames: false
IndentWrappedFunctionNames: true
# InsertTrailingCommas: None
# JavaScriptQuotes: Leave
# JavaScriptWrapImports: true
# KeepEmptyLinesAtTheStartOfBlocks: true
# NOTE: MacroBlockBegin/MacroBlockEnd don't work with _CATCH_ALL.
# MacroBlockBegin: ''
# MacroBlockEnd: ''
# MaxEmptyLinesToKeep: 1
MaxEmptyLinesToKeep: 2
# NamespaceIndentation: None
NamespaceIndentation: None
# ObjCBinPackProtocolList: Auto
# ObjCBlockIndentWidth: 2
# ObjCBreakBeforeNestedBlockParam: true
# ObjCSpaceAfterProperty: false
# ObjCSpaceBeforeProtocolList: true
# PenaltyBreakAssignment: 2
# PenaltyBreakBeforeFirstCallParameter: 19
# PenaltyBreakComment: 300
# PenaltyBreakFirstLessLess: 120
# PenaltyBreakString: 1000
# PenaltyBreakTemplateDeclaration: 10
# PenaltyExcessCharacter: 1000000
# PenaltyReturnTypeOnItsOwnLine: 60
# PointerAlignment: Right
PointerAlignment: Left
# ReflowComments: true
SortIncludes: false
# SortUsingDeclarations: true
# SpaceAfterCStyleCast: false
SpaceAfterCStyleCast: true
# SpaceAfterLogicalNot: false
# SpaceAfterTemplateKeyword: true
# SpaceBeforeAssignmentOperators: true
# SpaceBeforeCpp11BracedList: false
# SpaceBeforeCtorInitializerColon: true
# SpaceBeforeInheritanceColon: true
# SpaceBeforeParens: ControlStatements
# SpaceBeforeRangeBasedForLoopColon: true
# SpaceInEmptyBlock: false
# SpaceInEmptyParentheses: false
# SpacesBeforeTrailingComments: 1
# SpacesInAngles: false
# SpacesInConditionalStatement: false
# SpacesInContainerLiterals: true
# SpacesInCStyleCastParentheses: false
# SpacesInParentheses: false
# SpacesInSquareBrackets: false
# SpaceBeforeSquareBrackets: false
# Standard: Latest
# StatementMacros:
# - Q_UNUSED
# - QT_REQUIRE_VERSION
# NOTE: _STD_BEGIN, _STD_END, etc. aren't macros for complete statements, but telling
# clang-format that they are produces the behavior that we want (with no block indentation).
UseTab: Never

View File

@ -52,19 +52,20 @@ enum {
kCheckSumStateFailed = 1 << 1,
};
namespace cocos2d { namespace network {
namespace cocos2d {
namespace network {
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Implementation DownloadTaskCURL
class DownloadTaskCURL : public IDownloadTask
{
class DownloadTaskCURL : public IDownloadTask {
static int _sSerialId;
// if more than one task write to one file, cause file broken
// so use a set to check this situation
static set<string> _sStoragePathSet;
public:
int serialId;
@ -76,13 +77,11 @@ namespace cocos2d { namespace network {
DLLOG("Construct DownloadTaskCURL %p", this);
}
virtual ~DownloadTaskCURL()
{
virtual ~DownloadTaskCURL() {
if (_errCode != DownloadTask::ERROR_TASK_DUPLICATED) {
// if task destroyed unnormally, we should release WritenFileName stored in set.
// Normally, this action should done when task finished.
if (_tempFileName.length() && _sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName))
{
if (_tempFileName.length() && _sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName)) {
DownloadTaskCURL::_sStoragePathSet.erase(_tempFileName);
}
}
@ -96,10 +95,8 @@ namespace cocos2d { namespace network {
DLLOG("Destruct DownloadTaskCURL %p", this);
}
bool init(const string& filename, const string& tempSuffix)
{
if (0 == filename.length())
{
bool init(const string& filename, const string& tempSuffix) {
if (0 == filename.length()) {
// data task
_buf.reserve(CURL_MAX_WRITE_SIZE);
return true;
@ -110,8 +107,7 @@ namespace cocos2d { namespace network {
_tempFileName = filename;
_tempFileName.append(tempSuffix);
if (_sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName))
{
if (_sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName)) {
// there is another task uses this storage path
_errCode = DownloadTask::ERROR_TASK_DUPLICATED;
_errCodeInternal = 0;
@ -123,12 +119,10 @@ namespace cocos2d { namespace network {
// open temp file handle for write
bool ret = false;
do
{
do {
string dir;
size_t found = _tempFileName.find_last_of("/\\");
if (found == string::npos)
{
if (found == string::npos) {
_errCode = DownloadTask::ERROR_INVALID_PARAMS;
_errCodeInternal = 0;
_errDescription = "Can't find dirname in storagePath.";
@ -137,10 +131,8 @@ namespace cocos2d { namespace network {
// ensure directory is exist
dir = _tempFileName.substr(0, found + 1);
if (!FileUtils::getInstance()->isDirectoryExistInternal(dir))
{
if (!FileUtils::getInstance()->createDirectory(dir))
{
if (!FileUtils::getInstance()->isDirectoryExistInternal(dir)) {
if (!FileUtils::getInstance()->createDirectory(dir)) {
_errCode = DownloadTask::ERROR_CREATE_DIR_FAILED;
_errCodeInternal = 0;
_errDescription = "Can't create dir:";
@ -150,8 +142,7 @@ namespace cocos2d { namespace network {
}
// open file
_fs = FileUtils::getInstance()->openFileStream(_tempFileName, FileStream::Mode::APPEND);
if (!_fs)
{
if (!_fs) {
_errCode = DownloadTask::ERROR_OPEN_FILE_FAILED;
_errCodeInternal = 0;
_errDescription = "Can't open file:";
@ -165,8 +156,7 @@ namespace cocos2d { namespace network {
_fsMd5 = FileUtils::getInstance()->openFileStream(_checksumFileName, FileStream::Mode::WRITE);
if (_fsMd5->seek(0, SEEK_END) != sizeof(md5_state_s)) {
md5_init(&_md5State);
}
else {
} else {
_fsMd5->seek(0, SEEK_SET);
_fsMd5->read(&_md5State, sizeof(md5_state_s));
}
@ -176,22 +166,19 @@ namespace cocos2d { namespace network {
return ret;
}
void cancel() override
{
void cancel() override {
lock_guard<std::recursive_mutex> lock(_mutex);
if (!_cancelled) {
_cancelled = true;
if (this->_sockfd != -1)
{
if (this->_sockfd != -1) {
::shutdown(this->_sockfd, SD_BOTH); // may cause curl CURLE_SEND_ERROR(55) or CURLE_RECV_ERROR(56)
this->_sockfd = -1;
}
}
}
curl_socket_t openSocket(curlsocktype propose, curl_sockaddr* addr)
{
curl_socket_t openSocket(curlsocktype propose, curl_sockaddr* addr) {
lock_guard<std::recursive_mutex> lock(_mutex);
if (!_cancelled) {
@ -219,44 +206,36 @@ namespace cocos2d { namespace network {
return status;
}
void initProc()
{
void initProc() {
lock_guard<std::recursive_mutex> lock(_mutex);
_initInternal();
}
void setErrorProc(int code, int codeInternal, const char *desc)
{
void setErrorProc(int code, int codeInternal, const char* desc) {
lock_guard<std::recursive_mutex> lock(_mutex);
_errCode = code;
_errCodeInternal = codeInternal;
_errDescription = desc;
}
size_t writeDataProc(unsigned char *buffer, size_t size, size_t count)
{
size_t writeDataProc(unsigned char* buffer, size_t size, size_t count) {
lock_guard<std::recursive_mutex> lock(_mutex);
size_t ret = 0;
auto bytes_transferred = size * count;
if (_fs->isOpen())
{
if (_fs->isOpen()) {
ret = _fs->write(buffer, bytes_transferred); // fwrite(buffer, size, count, _fp);
}
else
{
} else {
ret = bytes_transferred;
auto cap = _buf.capacity();
auto bufSize = _buf.size();
if (cap < bufSize + ret)
{
if (cap < bufSize + ret) {
_buf.reserve(bufSize * 2);
}
_buf.insert(_buf.end(), buffer, buffer + ret);
}
if (ret > 0)
{
if (ret > 0) {
_bytesReceived += ret;
_totalBytesReceived += ret;
@ -311,8 +290,7 @@ namespace cocos2d { namespace network {
md5_state_s _md5State;
void _initInternal()
{
void _initInternal() {
_acceptRanges = (false);
_headerAchieved = (false);
_bytesReceived = (0);
@ -332,8 +310,7 @@ namespace cocos2d { namespace network {
////////////////////////////////////////////////////////////////////////////////
// Implementation DownloaderCURL::Impl
// This class shared by DownloaderCURL and work thread.
class DownloaderCURL::Impl : public enable_shared_from_this<DownloaderCURL::Impl>
{
class DownloaderCURL::Impl : public enable_shared_from_this<DownloaderCURL::Impl> {
public:
DownloaderHints hints;
@ -343,31 +320,25 @@ namespace cocos2d { namespace network {
DLLOG("Construct DownloaderCURL::Impl %p", this);
}
~Impl()
{
~Impl() {
DLLOG("Destruct DownloaderCURL::Impl %p", this);
}
void addTask(std::shared_ptr<DownloadTask> task, DownloadTaskCURL* coTask)
{
void addTask(std::shared_ptr<DownloadTask> task, DownloadTaskCURL* coTask) {
int status = coTask->checkFileMd5(task->checksum);
if (status & kCheckSumStateSucceed || DownloadTask::ERROR_NO_ERROR != coTask->_errCode)
{
if (status & kCheckSumStateSucceed || DownloadTask::ERROR_NO_ERROR != coTask->_errCode) {
_owner->_onDownloadFinished(std::make_pair(task, coTask), status);
}
else {
} else {
lock_guard<mutex> lock(_requestMutex);
_requestQueue.push_back(std::make_pair(task, coTask));
}
}
void run()
{
void run() {
lock_guard<mutex> lock(_threadMutex);
if (_tasksFinished)
{ // all tasks finished, make sure thread not joinable
if (_tasksFinished) { // all tasks finished, make sure thread not joinable
if (_thread.joinable())
_thread.join();
_tasksFinished = false;
@ -377,8 +348,7 @@ namespace cocos2d { namespace network {
_thread = std::thread(&DownloaderCURL::Impl::_threadProc, this);
}
void stop()
{ // make sure all task exit properly
void stop() { // make sure all task exit properly
if (!_requestQueue.empty()) {
lock_guard<mutex> lock(_requestMutex);
_requestQueue.clear();
@ -395,16 +365,14 @@ namespace cocos2d { namespace network {
_thread.join();
}
void getProcessTasks(vector<TaskWrapper>& outList)
{
void getProcessTasks(vector<TaskWrapper>& outList) {
lock_guard<mutex> lock(_processMutex);
outList.reserve(_processSet.size());
outList.insert(outList.end(), _processSet.begin(), _processSet.end());
}
private:
static size_t _outputHeaderCallbackProc(void *buffer, size_t size, size_t count, void *userdata)
{
static size_t _outputHeaderCallbackProc(void* buffer, size_t size, size_t count, void* userdata) {
int strLen = int(size * count);
DLLOG(" _outputHeaderCallbackProc: %.*s", strLen, buffer);
DownloadTaskCURL& coTask = *((DownloadTaskCURL*) (userdata));
@ -412,8 +380,7 @@ namespace cocos2d { namespace network {
return strLen;
}
static size_t _outputDataCallbackProc(void *buffer, size_t size, size_t count, void *userdata)
{
static size_t _outputDataCallbackProc(void* buffer, size_t size, size_t count, void* userdata) {
// DLLOG(" _outputDataCallbackProc: size(%ld), count(%ld)", size, count);
DownloadTaskCURL* coTask = (DownloadTaskCURL*) userdata;
@ -421,23 +388,21 @@ namespace cocos2d { namespace network {
return coTask->writeDataProc((unsigned char*) buffer, size, count);
}
static int _progressCallbackProc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded)
{
static int _progressCallbackProc(
void* ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded) {
DownloaderCURL* downloader = (DownloaderCURL*) ptr;
downloader->_onDownloadProgress();
return 0;
}
static curl_socket_t _openSocketCallback(DownloadTaskCURL& pTask, curlsocktype propose, curl_sockaddr* addr)
{
static curl_socket_t _openSocketCallback(DownloadTaskCURL& pTask, curlsocktype propose, curl_sockaddr* addr) {
return pTask.openSocket(propose, addr);
}
// this function designed call in work thread
// the curl handle destroyed in _threadProc
// handle inited for get header
CURLcode _initCurlHandleProc(CURL *handle, TaskWrapper& wrapper, bool forContent = false)
{
CURLcode _initCurlHandleProc(CURL* handle, TaskWrapper& wrapper, bool forContent = false) {
const DownloadTask& task = *wrapper.first;
DownloadTaskCURL* coTask = wrapper.second;
@ -449,12 +414,9 @@ namespace cocos2d { namespace network {
curl_easy_setopt(handle, CURLOPT_URL, internalURL.c_str());
// set write func
if (forContent)
{
if (forContent) {
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, _outputDataCallbackProc);
}
else
{
} else {
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, _outputHeaderCallbackProc);
}
curl_easy_setopt(handle, CURLOPT_WRITEDATA, coTask);
@ -472,19 +434,15 @@ namespace cocos2d { namespace network {
curl_easy_setopt(handle, CURLOPT_OPENSOCKETFUNCTION, _openSocketCallback);
curl_easy_setopt(handle, CURLOPT_OPENSOCKETDATA, coTask);
if (forContent)
{
if (forContent) {
/** if server acceptRanges and local has part of file, we continue to download **/
if (coTask->_acceptRanges && coTask->_totalBytesReceived > 0)
{
if (coTask->_acceptRanges && coTask->_totalBytesReceived > 0) {
char buf[128];
sprintf(buf, "%" PRId64 "-", coTask->_totalBytesReceived);
curl_easy_setopt(handle, CURLOPT_RANGE, buf);
curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE, (curl_off_t) coTask->_totalBytesReceived);
}
}
else
{
} else {
// get header options
curl_easy_setopt(handle, CURLOPT_HEADER, 1);
curl_easy_setopt(handle, CURLOPT_NOBODY, 1);
@ -494,8 +452,7 @@ namespace cocos2d { namespace network {
// {
// curl_easy_setopt(curl, CURLOPT_PROXY, sProxy.c_str());
// }
if (hints.timeoutInSeconds)
{
if (hints.timeoutInSeconds) {
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, hints.timeoutInSeconds);
}
@ -508,8 +465,7 @@ namespace cocos2d { namespace network {
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
static const int MAX_REDIRS = 5;
if (MAX_REDIRS)
{
if (MAX_REDIRS) {
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, true);
curl_easy_setopt(handle, CURLOPT_MAXREDIRS, MAX_REDIRS);
}
@ -520,16 +476,13 @@ namespace cocos2d { namespace network {
}
// get header info, if success set handle to content download state
bool _getHeaderInfoProc(CURL *handle, TaskWrapper& wrapper)
{
bool _getHeaderInfoProc(CURL* handle, TaskWrapper& wrapper) {
DownloadTaskCURL& coTask = *wrapper.second;
CURLcode rc = CURLE_OK;
do
{
do {
long httpResponseCode = 0;
rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode);
if (CURLE_OK != rc)
{
if (CURLE_OK != rc) {
break;
}
// Comment follow code to support ftp
@ -547,8 +500,7 @@ namespace cocos2d { namespace network {
// curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &contentType);
double contentLen = 0;
rc = curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLen);
if (CURLE_OK != rc)
{
if (CURLE_OK != rc) {
break;
}
@ -557,8 +509,7 @@ namespace cocos2d { namespace network {
// get current file size
int64_t fileSize = 0;
if (acceptRanges && coTask._tempFileName.length())
{
if (acceptRanges && coTask._tempFileName.length()) {
fileSize = FileUtils::getInstance()->getFileSize(coTask._tempFileName);
}
@ -566,22 +517,19 @@ namespace cocos2d { namespace network {
lock_guard<std::recursive_mutex> lock(coTask._mutex);
coTask._totalBytesExpected = (int64_t) contentLen;
coTask._acceptRanges = acceptRanges;
if (acceptRanges && fileSize > 0)
{
if (acceptRanges && fileSize > 0) {
coTask._totalBytesReceived = fileSize;
}
coTask._headerAchieved = true;
} while (0);
if (CURLE_OK != rc)
{
if (CURLE_OK != rc) {
coTask.setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, rc, curl_easy_strerror(rc));
}
return coTask._headerAchieved;
}
void _threadProc()
{
void _threadProc() {
DLLOG("++++DownloaderCURL::Impl::_threadProc begin %p", this);
// the holder prevent DownloaderCURL::Impl class instance be destruct in main thread
auto holder = this->shared_from_this();
@ -594,26 +542,23 @@ namespace cocos2d { namespace network {
CURLMcode mcode = CURLM_OK;
int rc = 0; // select return code
do
{
do {
// check the thread should exit or not
{
lock_guard<mutex> lock(_threadMutex);
// if the Impl stoped, this->_thread.reset will be called, thus _thread.get_id() not equal with thisThreadId
if (thisThreadId != this->_thread.get_id())
{
// if the Impl stoped, this->_thread.reset will be called, thus _thread.get_id() not equal with
// thisThreadId
if (thisThreadId != this->_thread.get_id()) {
break;
}
}
if (runningHandles)
{
if (runningHandles) {
// get timeout setting from multi-handle
long timeoutMS = -1;
curl_multi_timeout(curlmHandle, &timeoutMS);
if(timeoutMS < 0)
{
if (timeoutMS < 0) {
timeoutMS = 1000;
}
@ -628,19 +573,15 @@ namespace cocos2d { namespace network {
FD_ZERO(&fdexcep);
mcode = curl_multi_fdset(curlmHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
if (CURLM_OK != mcode)
{
if (CURLM_OK != mcode) {
break;
}
// do wait action
if(maxfd == -1)
{
if (maxfd == -1) {
this_thread::sleep_for(chrono::milliseconds(CC_CURL_POLL_TIMEOUT_MS));
rc = 0;
}
else
{
} else {
struct timeval timeout;
timeout.tv_sec = timeoutMS / 1000;
@ -649,21 +590,17 @@ namespace cocos2d { namespace network {
rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
}
if (rc < 0)
{
if (rc < 0) {
DLLOG(" _threadProc: select return unexpect code: %d", rc);
}
}
if (!coTaskMap.empty())
{
if (!coTaskMap.empty()) {
mcode = CURLM_CALL_MULTI_PERFORM;
while(CURLM_CALL_MULTI_PERFORM == mcode)
{
while (CURLM_CALL_MULTI_PERFORM == mcode) {
mcode = curl_multi_perform(curlmHandle, &runningHandles);
}
if (CURLM_OK != mcode)
{
if (CURLM_OK != mcode) {
break;
}
@ -671,8 +608,7 @@ namespace cocos2d { namespace network {
do {
int msgq = 0;
m = curl_multi_info_read(curlmHandle, &msgq);
if(m && (m->msg == CURLMSG_DONE))
{
if (m && (m->msg == CURLMSG_DONE)) {
CURL* curlHandle = m->easy_handle;
CURLcode errCode = m->data.result;
@ -681,34 +617,31 @@ namespace cocos2d { namespace network {
// remove from multi-handle
curl_multi_remove_handle(curlmHandle, curlHandle);
bool reinited = false;
do
{
if (CURLE_OK != errCode)
{
wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, errCode, curl_easy_strerror(errCode));
do {
if (CURLE_OK != errCode) {
wrapper.second->setErrorProc(
DownloadTask::ERROR_IMPL_INTERNAL, errCode, curl_easy_strerror(errCode));
break;
}
// if the task is content download task, cleanup the handle
if (wrapper.second->_headerAchieved)
{
if (wrapper.second->_headerAchieved) {
break;
}
// the task is get header task
// first, we get info from response
if (!_getHeaderInfoProc(curlHandle, wrapper))
{
if (!_getHeaderInfoProc(curlHandle, wrapper)) {
// the error info has been set in _getHeaderInfoProc
break;
}
// after get header info success
// wrapper.second->_totalBytesReceived inited by local file size
// if the local file size equal with the content size from header, the file has downloaded finish
if (wrapper.second->_totalBytesReceived &&
wrapper.second->_totalBytesReceived == wrapper.second->_totalBytesExpected)
{
// if the local file size equal with the content size from header, the file has
// downloaded finish
if (wrapper.second->_totalBytesReceived
&& wrapper.second->_totalBytesReceived == wrapper.second->_totalBytesExpected) {
// the file has download complete
// break to move this task to finish queue
break;
@ -716,22 +649,21 @@ namespace cocos2d { namespace network {
// reinit curl handle for download content
curl_easy_reset(curlHandle);
auto error = _initCurlHandleProc(curlHandle, wrapper, true);
if (error != CURLE_OK)
{
wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, error, curl_easy_strerror(error));
if (error != CURLE_OK) {
wrapper.second->setErrorProc(
DownloadTask::ERROR_IMPL_INTERNAL, error, curl_easy_strerror(error));
break;
}
mcode = curl_multi_add_handle(curlmHandle, curlHandle);
if (CURLM_OK != mcode)
{
wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, mcode, curl_multi_strerror(mcode));
if (CURLM_OK != mcode) {
wrapper.second->setErrorProc(
DownloadTask::ERROR_IMPL_INTERNAL, mcode, curl_multi_strerror(mcode));
break;
}
reinited = true;
} while (0);
if (reinited)
{
if (reinited) {
continue;
}
curl_easy_cleanup(curlHandle);
@ -755,22 +687,19 @@ namespace cocos2d { namespace network {
// process tasks in _requestList
auto size = coTaskMap.size();
while (0 == countOfMaxProcessingTasks || size < countOfMaxProcessingTasks)
{
while (0 == countOfMaxProcessingTasks || size < countOfMaxProcessingTasks) {
// get task wrapper from request queue
TaskWrapper wrapper;
{
lock_guard<mutex> lock(_requestMutex);
if (!_requestQueue.empty())
{
if (!_requestQueue.empty()) {
wrapper = _requestQueue.front();
_requestQueue.pop_front();
}
}
// if request queue is empty, the wrapper.first is nullptr
if (! wrapper.first)
{
if (!wrapper.first) {
break;
}
@ -779,8 +708,7 @@ namespace cocos2d { namespace network {
// create curl handle from task and add into curl multi handle
CURL* curlHandle = curl_easy_init();
if (nullptr == curlHandle)
{
if (nullptr == curlHandle) {
wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, 0, "Alloc curl handle failed.");
_owner->_onDownloadFinished(std::move(wrapper));
continue;
@ -791,8 +719,7 @@ namespace cocos2d { namespace network {
// add curl handle to process list
mcode = curl_multi_add_handle(curlmHandle, curlHandle);
if (CURLM_OK != mcode)
{
if (CURLM_OK != mcode) {
wrapper.second->setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, mcode, curl_multi_strerror(mcode));
_owner->_onDownloadFinished(std::move(wrapper));
continue;
@ -829,20 +756,15 @@ public:
////////////////////////////////////////////////////////////////////////////////
// Implementation DownloaderCURL
DownloaderCURL::DownloaderCURL(const DownloaderHints& hints)
: _impl(std::make_shared<Impl>())
, _currTask(nullptr)
{
DownloaderCURL::DownloaderCURL(const DownloaderHints& hints) : _impl(std::make_shared<Impl>()), _currTask(nullptr) {
DLLOG("Construct DownloaderCURL %p", this);
_impl->hints = hints;
_impl->_owner = this;
_transferDataToBuffer = [this](void *buf, int64_t len)->int64_t
{
_transferDataToBuffer = [this](void* buf, int64_t len) -> int64_t {
DownloadTaskCURL& coTask = *_currTask;
int64_t dataLen = coTask._buf.size();
if (len < dataLen)
{
if (len < dataLen) {
return 0;
}
@ -852,14 +774,12 @@ public:
};
}
DownloaderCURL::~DownloaderCURL()
{
DownloaderCURL::~DownloaderCURL() {
_impl->stop();
DLLOG("Destruct DownloaderCURL %p", this);
}
IDownloadTask *DownloaderCURL::createCoTask(std::shared_ptr<DownloadTask>& task)
{
IDownloadTask* DownloaderCURL::createCoTask(std::shared_ptr<DownloadTask>& task) {
DownloadTaskCURL* coTask = new (std::nothrow) DownloadTaskCURL;
coTask->init(task->storagePath, _impl->hints.tempFileNameSuffix);
@ -872,14 +792,12 @@ public:
return coTask;
}
void DownloaderCURL::_onDownloadFinished(TaskWrapper&& wrapper, int checkState)
{
void DownloaderCURL::_onDownloadFinished(TaskWrapper&& wrapper, int checkState) {
const DownloadTask& task = *wrapper.first;
DownloadTaskCURL& coTask = *wrapper.second;
// if there is bytesReceived, call progress update first
if (coTask._bytesReceived)
{
if (coTask._bytesReceived) {
_currTask = &coTask;
task.progressInfo.bytesReceived = coTask._bytesReceived;
task.progressInfo.totalBytesReceived = coTask._totalBytesReceived;
@ -891,17 +809,16 @@ public:
}
// if file task, close file handle and rename file if needed
if (coTask._fs)
{
do
{
if (coTask._fs) {
do {
auto pFileUtils = FileUtils::getInstance();
coTask._fs->close();
coTask._fsMd5->close();
if (checkState & kCheckSumStateSucceed) // No need download
{
FileStream* fsOrigin = FileUtils::getInstance()->openFileStream(coTask._fileName, FileStream::Mode::READ);
FileStream* fsOrigin =
FileUtils::getInstance()->openFileStream(coTask._fileName, FileStream::Mode::READ);
if (fsOrigin) {
task.progressInfo.totalBytesExpected = fsOrigin->seek(0, SEEK_END);
task.progressInfo.bytesReceived = task.progressInfo.totalBytesExpected;
@ -917,8 +834,7 @@ public:
delete fsOrigin;
fsOrigin = nullptr;
}
else {
} else {
coTask._errCode = DownloadTask::ERROR_ORIGIN_FILE_MISSING;
coTask._errCodeInternal = 0;
coTask._errDescription = "Check file md5 succeed, but the origin file is missing!";
@ -929,8 +845,7 @@ public:
break;
}
if (coTask._fileName.empty() || DownloadTask::ERROR_NO_ERROR != coTask._errCode)
{
if (coTask._fileName.empty() || DownloadTask::ERROR_NO_ERROR != coTask._errCode) {
if (coTask._errCodeInternal == CURLE_RANGE_ERROR) {
// If CURLE_RANGE_ERROR, means the server not support resume from download.
pFileUtils->removeFile(coTask._checksumFileName);
@ -940,10 +855,8 @@ public:
}
// if file already exist, remove it
if (pFileUtils->isFileExistInternal(coTask._fileName))
{
if (!pFileUtils->removeFile(coTask._fileName))
{
if (pFileUtils->isFileExistInternal(coTask._fileName)) {
if (!pFileUtils->removeFile(coTask._fileName)) {
coTask._errCode = DownloadTask::ERROR_REMOVE_FILE_FAILED;
coTask._errCodeInternal = errno;
coTask._errDescription = "Can't remove old file: ";
@ -958,9 +871,8 @@ public:
if (coTask.checkFileMd5(task.checksum, &realMd5) & kCheckSumStateFailed) {
coTask._errCode = DownloadTask::ERROR_CHECK_SUM_FAILED;
coTask._errCodeInternal = 0;
coTask._errDescription = StringUtils::format("Check file: %s md5 failed, required:%s, real:%s", coTask._fileName.c_str(),
task.checksum.c_str(),
realMd5.c_str());
coTask._errDescription = StringUtils::format("Check file: %s md5 failed, required:%s, real:%s",
coTask._fileName.c_str(), task.checksum.c_str(), realMd5.c_str());
pFileUtils->removeFile(coTask._checksumFileName);
pFileUtils->removeFile(coTask._tempFileName);
@ -969,8 +881,7 @@ public:
// remove file firstly, confirm rename file work fine.
pFileUtils->removeFile(coTask._fileName);
if (pFileUtils->renameFile(coTask._tempFileName, coTask._fileName))
{
if (pFileUtils->renameFile(coTask._tempFileName, coTask._fileName)) {
// success, remove storage from set
DownloadTaskCURL::_sStoragePathSet.erase(coTask._tempFileName);
break;
@ -984,7 +895,6 @@ public:
coTask._errDescription.append(" to: ");
coTask._errDescription.append(coTask._fileName);
} while (0);
}
// needn't lock coTask here, because tasks has removed form _impl
@ -992,27 +902,23 @@ public:
DLLOG(" DownloaderCURL: finish Task: Id(%d)", coTask.serialId);
}
void DownloaderCURL::_onDownloadProgress()
{
void DownloaderCURL::_onDownloadProgress() {
vector<TaskWrapper> tasks;
// update processing tasks
_impl->getProcessTasks(tasks);
for (auto& wrapper : tasks)
{
for (auto& wrapper : tasks) {
const DownloadTask& task = *wrapper.first;
DownloadTaskCURL& coTask = *wrapper.second;
lock_guard<std::recursive_mutex> lock(coTask._mutex);
if (coTask._bytesReceived)
{
if (coTask._bytesReceived) {
_currTask = &coTask;
task.progressInfo.bytesReceived = coTask._bytesReceived;
task.progressInfo.totalBytesReceived = coTask._totalBytesReceived;
task.progressInfo.totalBytesExpected = coTask._totalBytesExpected;
task.progressInfo.speedInBytes = coTask._speed;
onTaskProgress(task,
_transferDataToBuffer);
onTaskProgress(task, _transferDataToBuffer);
_currTask = nullptr;
coTask._bytesReceived = 0;
}
@ -1020,5 +926,5 @@ public:
tasks.resize(0);
}
}} // namespace cocos2d::network
} // namespace network
} // namespace cocos2d