diff --git a/native/cocos/base/CCScriptSupport.h b/native/cocos/base/CCScriptSupport.h index 4a9a76b833..9f6bb29171 100644 --- a/native/cocos/base/CCScriptSupport.h +++ b/native/cocos/base/CCScriptSupport.h @@ -801,7 +801,7 @@ public: /** Remove proxy for a native object */ - virtual void removeObjectProxy(Ref* obj) {} + virtual void removeObjectProxy(void* obj) {} /** Triggers the garbage collector */ virtual void garbageCollect() {} diff --git a/native/cocos/network/CCDownloader-android.cpp b/native/cocos/network/CCDownloader-android.cpp index 08f61bf7b8..d24fcb576f 100644 --- a/native/cocos/network/CCDownloader-android.cpp +++ b/native/cocos/network/CCDownloader-android.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -27,6 +27,8 @@ #include "network/CCDownloader.h" #include "platform/android/jni/JniHelper.h" +#include + #define JCLS_DOWNLOADER "org/cocos2dx/lib/Cocos2dxDownloader" #define JCLS_TASK "com/loopj/android/http/RequestHandle" #define JARG_STR "Ljava/lang/String;" @@ -38,6 +40,33 @@ using namespace std; static bool _registerNativeMethods(JNIEnv* env); unordered_map sDownloaderMap; +std::mutex sDownloaderMutex; + +static void _insertDownloaderAndroid(int id, cocos2d::network::DownloaderAndroid* downloaderPtr) +{ + std::lock_guard guard(sDownloaderMutex); + sDownloaderMap.insert(make_pair(id, downloaderPtr)); +} + +static void _eraseDownloaderAndroid(int id) +{ + std::lock_guard guard(sDownloaderMutex); + sDownloaderMap.erase(id); +} + +/** + * If not found, return nullptr, otherwise return the Downloader + */ +static cocos2d::network::DownloaderAndroid* _findDownloaderAndroid(int id) +{ + std::lock_guard guard(sDownloaderMutex); + auto iter = sDownloaderMap.find(id); + if (sDownloaderMap.end() == iter) { + return nullptr; + } else { + return iter->second; + } +} namespace cocos2d { namespace network { @@ -83,7 +112,9 @@ namespace cocos2d { namespace network { ); _impl = methodInfo.env->NewGlobalRef(jObj); DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl); - sDownloaderMap.insert(make_pair(_id, this)); + //It's not thread-safe here, use thread-safe method instead + //sDownloaderMap.insert(make_pair(_id, this)); + _insertDownloaderAndroid(_id, this); methodInfo.env->DeleteLocalRef(jStr); methodInfo.env->DeleteLocalRef(jObj); methodInfo.env->DeleteLocalRef(methodInfo.classID); @@ -107,7 +138,9 @@ namespace cocos2d { namespace network { ); methodInfo.env->DeleteLocalRef(methodInfo.classID); } - sDownloaderMap.erase(_id); + //It's not thread-safe here, use thread-safe method instead + //sDownloaderMap.erase(_id); + _eraseDownloaderAndroid(_id); JniHelper::getEnv()->DeleteGlobalRef(_impl); } DLLOG("Destruct DownloaderAndroid: %p", this); @@ -186,26 +219,26 @@ namespace cocos2d { namespace network { static void _nativeOnProgress(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal) { DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal); - auto iter = sDownloaderMap.find(id); - if (sDownloaderMap.end() == iter) + //It's not thread-safe here, use thread-safe method instead + cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id); + if (nullptr == downloader) { DLLOG("_nativeOnProgress can't find downloader by key: %p for task: %d", clazz, id); return; } - cocos2d::network::DownloaderAndroid *downloader = iter->second; downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal); } static void _nativeOnFinish(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId); - auto iter = sDownloaderMap.find(id); - if (sDownloaderMap.end() == iter) + //It's not thread-safe here, use thread-safe method instead + cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id); + if (nullptr == downloader) { DLLOG("_nativeOnFinish can't find downloader id: %d for task: %d", id, taskId); return; } - cocos2d::network::DownloaderAndroid *downloader = iter->second; vector buf; if (errStr) { diff --git a/native/cocos/network/CCDownloader-android.h b/native/cocos/network/CCDownloader-android.h index 868f602736..d820fd8e6a 100644 --- a/native/cocos/network/CCDownloader-android.h +++ b/native/cocos/network/CCDownloader-android.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader-apple.h b/native/cocos/network/CCDownloader-apple.h index 7c08eb47a9..fd087d260d 100644 --- a/native/cocos/network/CCDownloader-apple.h +++ b/native/cocos/network/CCDownloader-apple.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 0613d7df30..8d67db6d96 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -30,7 +30,7 @@ //////////////////////////////////////////////////////////////////////////////// // OC Classes Declaration -#import +#import // this wrapper used to wrap C++ class DownloadTask into NSMutableDictionary @interface DownloadTaskWrapper : NSObject @@ -227,7 +227,9 @@ namespace cocos2d { namespace network { request = [NSURLRequest requestWithURL:url]; } NSURLSessionDataTask *ocTask = [self.downloadSession dataTaskWithRequest:request]; - [self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask]; + DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task]; + [self.taskDict setObject:taskWrapper forKey:ocTask]; + [taskWrapper release]; if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) { [ocTask resume]; @@ -263,7 +265,10 @@ namespace cocos2d { namespace network { { ocTask = [self.downloadSession downloadTaskWithRequest:request]; } - [self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask]; + + DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task]; + [self.taskDict setObject:taskWrapper forKey:ocTask]; + [taskWrapper release]; if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) { [ocTask resume]; @@ -321,15 +326,19 @@ namespace cocos2d { namespace network { } } _outer = nullptr; - + + while(!_taskQueue.empty()) + _taskQueue.pop(); + [self.downloadSession invalidateAndCancel]; [self release]; } -(void)dealloc { - [super dealloc]; DLLOG("Destruct DownloaderAppleImpl %p", self); + self.downloadSession = nil; + [super dealloc]; } #pragma mark - NSURLSessionTaskDelegate methods @@ -405,9 +414,9 @@ namespace cocos2d { namespace network { std::string errorString; const int64_t buflen = [wrapper totalBytesReceived]; - char buf[buflen]; + std::vector data((size_t)buflen); + char* buf = (char*)data.data(); [wrapper transferDataToBuffer:buf lengthOfBuffer:buflen]; - std::vector data(buf, buf + buflen); _outer->onTaskFinish(*[wrapper get], cocos2d::network::DownloadTask::ERROR_NO_ERROR, @@ -423,8 +432,8 @@ namespace cocos2d { namespace network { if (statusCode >= 400) { std::vector buf; // just a placeholder - const char *orignalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding]; - std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", orignalURL, (int)statusCode); + const char *originalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding]; + std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", originalURL, (int)statusCode); _outer->onTaskFinish(*[wrapper get], cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL, @@ -435,7 +444,6 @@ namespace cocos2d { namespace network { } } [self.taskDict removeObjectForKey:task]; - [wrapper release]; while (!_taskQueue.empty() && _taskQueue.front() == nil) { _taskQueue.pop(); diff --git a/native/cocos/network/CCDownloader-curl.cpp b/native/cocos/network/CCDownloader-curl.cpp index 5567296a26..c842a743f1 100644 --- a/native/cocos/network/CCDownloader-curl.cpp +++ b/native/cocos/network/CCDownloader-curl.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -624,7 +624,8 @@ namespace cocos2d { namespace network { } // process tasks in _requestList - while (0 == countOfMaxProcessingTasks || coTaskMap.size() < countOfMaxProcessingTasks) + auto size = coTaskMap.size(); + while (0 == countOfMaxProcessingTasks || size < countOfMaxProcessingTasks) { // get task wrapper from request queue TaskWrapper wrapper; diff --git a/native/cocos/network/CCDownloader-curl.h b/native/cocos/network/CCDownloader-curl.h index 4cfe5e3dda..b5d924cd3b 100644 --- a/native/cocos/network/CCDownloader-curl.h +++ b/native/cocos/network/CCDownloader-curl.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/CCDownloader.cpp b/native/cocos/network/CCDownloader.cpp index bce110f4b3..6dbf6b3bac 100644 --- a/native/cocos/network/CCDownloader.cpp +++ b/native/cocos/network/CCDownloader.cpp @@ -25,13 +25,7 @@ #include "network/CCDownloader.h" // include platform specific implement class -#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - -#include "network/CCDownloader-apple.h" -#include "network/CCDownloader-curl.h" -#define DownloaderImpl DownloaderCURL - -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "network/CCDownloader-apple.h" #define DownloaderImpl DownloaderApple @@ -81,7 +75,7 @@ namespace cocos2d { namespace network { int64_t bytesReceived, int64_t totalBytesReceived, int64_t totalBytesExpected, - std::function& transferDataToBuffer) + std::function& /*transferDataToBuffer*/) { if (onTaskProgress) { diff --git a/native/cocos/network/CCIDownloaderImpl.h b/native/cocos/network/CCIDownloaderImpl.h index 82a9465aa2..098ddd8832 100644 --- a/native/cocos/network/CCIDownloaderImpl.h +++ b/native/cocos/network/CCIDownloaderImpl.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2015-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpAsynConnection-apple.h b/native/cocos/network/HttpAsynConnection-apple.h index df370a91e9..573f37d211 100644 --- a/native/cocos/network/HttpAsynConnection-apple.h +++ b/native/cocos/network/HttpAsynConnection-apple.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpAsynConnection-apple.m b/native/cocos/network/HttpAsynConnection-apple.m index 51c83b41ab..c80e278302 100755 --- a/native/cocos/network/HttpAsynConnection-apple.m +++ b/native/cocos/network/HttpAsynConnection-apple.m @@ -1,18 +1,18 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - + Copyright (c) 2013-2017 Chukong Technologies Inc. + http://www.cocos2d-x.org - + 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 @@ -58,7 +58,7 @@ [conn release]; [runLoop release]; [connError release]; - + [super dealloc]; } @@ -67,7 +67,7 @@ #ifdef COCOS2D_DEBUG NSLog(@"Starting to load %@", srcURL); #endif - + finish = false; self.responseData = [NSMutableData data]; @@ -75,31 +75,31 @@ self.responseError = nil; self.connError = nil; - + // create the connection with the target request and this class as the delegate self.conn = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease]; - + [self.conn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - + // start the connection [self.conn start]; } #pragma mark NSURLConnectionDelegate methods /** - * This delegate method is called when the NSURLConnection connects to the server. It contains the + * This delegate method is called when the NSURLConnection connects to the server. It contains the * NSURLResponse object with the headers returned by the server. This method may be called multiple times. * Therefore, it is important to reset the data on each call. Do not assume that it is the first call * of this method. **/ -- (void) connection:(NSURLConnection *)connection +- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { #ifdef COCOS2D_DEBUG NSLog(@"Received response from request to url %@", srcURL); #endif - + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; //NSLog(@"All headers = %@", [httpResponse allHeaderFields]); self.responseHeader = [httpResponse allHeaderFields]; @@ -108,7 +108,7 @@ self.statusString = [NSHTTPURLResponse localizedStringForStatusCode:responseCode]; if(responseCode == 200) self.statusString = @"OK"; - + /*The individual values of the numeric status codes defined for HTTP/1.1 | "200" ; OK | "201" ; Created @@ -122,17 +122,17 @@ {// something went wrong, abort the whole thing self.responseError = [NSError errorWithDomain:@"CCBackendDomain" code:responseCode - userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}]; + userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}]; } - + [responseData setLength:0]; } /** * This delegate method is called for each chunk of data received from the server. The chunk size - * is dependent on the network type and the server configuration. + * is dependent on the network type and the server configuration. */ -- (void)connection:(NSURLConnection *)connection +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //NSLog(@"get some data"); @@ -141,20 +141,20 @@ } /** - * This delegate methodis called if the connection cannot be established to the server. + * This delegate method is called if the connection cannot be established to the server. * The error object will have a description of the error **/ -- (void)connection:(NSURLConnection *)connection +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //NSLog(@"Load failed with error %@", [error localizedDescription]); self.connError = error; - + finish = true; } /** - * This delegate method is called when the data load is complete. The delegate will be released + * This delegate method is called when the data load is complete. The delegate will be released * following this call **/ - (void)connectionDidFinishLoading:(NSURLConnection *)connection @@ -172,16 +172,16 @@ NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath]; CFDataRef certDataRef = (CFDataRef)certData; SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef); - + //Establish a chain of trust anchored on our bundled certificate CFArrayRef certArrayRef = CFArrayCreate(NULL, (void*)&cert, 1, NULL); SecTrustRef serverTrust = protectionSpace.serverTrust; SecTrustSetAnchorCertificates(serverTrust, certArrayRef); - + //Verify that trust SecTrustResultType trustResult; SecTrustEvaluate(serverTrust, &trustResult); - + if(trustResult == kSecTrustResultRecoverableTrustFailure) { CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust); @@ -206,14 +206,14 @@ { id sender = challenge.sender; NSURLProtectionSpace *protectionSpace = challenge.protectionSpace; - + //Should server trust client? if([self shouldTrustProtectionSpace:protectionSpace]) { SecTrustRef trust = [protectionSpace serverTrust]; -// +// // SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0); -// +// // NSData *serverCertificateData = (NSData*)SecCertificateCopyData(certificate); // NSString *serverCertificateDataHash = [[serverCertificateData base64EncodedString] ] NSURLCredential *credential = [NSURLCredential credentialForTrust:trust]; diff --git a/native/cocos/network/HttpClient-android.cpp b/native/cocos/network/HttpClient-android.cpp index 7d1f6b5d8f..382ad0df6d 100644 --- a/native/cocos/network/HttpClient-android.cpp +++ b/native/cocos/network/HttpClient-android.cpp @@ -1,20 +1,20 @@ /**************************************************************************** Copyright (c) 2012 greathqy Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - + Copyright (c) 2013-2017 Chukong Technologies Inc. + http://www.cocos2d-x.org - + 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 @@ -39,18 +39,18 @@ #include "platform/android/jni/JniHelper.h" #include "base/ccUTF8.h" - + NS_CC_BEGIN namespace network { - + typedef std::vector HttpRequestHeaders; typedef HttpRequestHeaders::iterator HttpRequestHeadersIter; typedef std::vector HttpCookies; typedef HttpCookies::iterator HttpCookiesIter; static HttpClient* _httpClient = nullptr; // pointer to singleton - + struct CookiesInfo { @@ -70,7 +70,7 @@ static size_t writeData(void* buffer, size_t sizes, HttpResponse* response) recvBuffer->clear(); recvBuffer->insert(recvBuffer->end(), (char*)buffer, ((char*)buffer) + sizes); return sizes; -} +} //static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream) size_t writeHeaderData(void* buffer, size_t sizes,HttpResponse* response) @@ -85,8 +85,8 @@ class HttpURLConnection { public: HttpURLConnection(HttpClient* httpClient) - :_httpURLConnection(nullptr) - ,_client(httpClient) + :_client(httpClient) + ,_httpURLConnection(nullptr) ,_requestmethod("") ,_responseCookies("") ,_cookieFileName("") @@ -102,7 +102,7 @@ public: JniHelper::getEnv()->DeleteGlobalRef(_httpURLConnection); } } - + void setRequestMethod(const char* method) { _requestmethod = method; @@ -119,8 +119,12 @@ public: methodInfo.env->DeleteLocalRef(jstr); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } - + bool init(HttpRequest* request) { createHttpURLConnection(request->getUrl()); @@ -133,27 +137,25 @@ public: if(!headers.empty()) { /* append custom headers one by one */ - for (HttpRequestHeadersIter it = headers.begin(); it != headers.end(); ++it) + for (auto& header : headers) { - std::string val = *it; - - int len = val.length(); - int pos = val.find(':'); + int len = header.length(); + int pos = header.find(':'); if (-1 == pos || pos >= len) { continue; } - std::string str1 = val.substr(0, pos); - std::string str2 = val.substr(pos + 1, len - pos - 1); + std::string str1 = header.substr(0, pos); + std::string str2 = header.substr(pos + 1, len - pos - 1); addRequestHeader(str1.c_str(), str2.c_str()); } } - + addCookiesForRequestHeader(); - + return true; } - + int connect() { int suc = 0; @@ -167,10 +169,14 @@ public: methodInfo.classID, methodInfo.methodID, _httpURLConnection); methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return suc; } - + void disconnect() { JniMethodInfo methodInfo; @@ -183,8 +189,12 @@ public: methodInfo.classID, methodInfo.methodID, _httpURLConnection); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } - + int getResponseCode() { int responseCode = 0; @@ -198,10 +208,14 @@ public: methodInfo.classID, methodInfo.methodID, _httpURLConnection); methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return responseCode; } - + char* getResponseMessage() { char* message = nullptr; @@ -220,10 +234,14 @@ public: } methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return message; } - + void sendRequest(HttpRequest* request) { JniMethodInfo methodInfo; @@ -232,7 +250,7 @@ public: "sendRequest", "(Ljava/net/HttpURLConnection;[B)V")) { - + jbyteArray bytearray; ssize_t dataSize = request->getRequestDataSize(); bytearray = methodInfo.env->NewByteArray(dataSize); @@ -242,34 +260,38 @@ public: methodInfo.env->DeleteLocalRef(bytearray); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } - + size_t saveResponseCookies(const char* responseCookies, size_t count) { if (nullptr == responseCookies || strlen(responseCookies) == 0 || count == 0) { return 0; } - + if (_cookieFileName.empty()) { _cookieFileName = FileUtils::getInstance()->getWritablePath() + "cookieFile.txt"; } - + FILE* fp = fopen(_cookieFileName.c_str(), "w"); if (nullptr == fp) { CCLOG("can't create or open response cookie files"); return 0; } - + fwrite(responseCookies, sizeof(char), count, fp); - + fclose(fp); - + return count; } - + char* getResponseHeaders() { char* headers = nullptr; @@ -287,18 +309,22 @@ public: } methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return headers; - + } - + char* getResponseContent(HttpResponse* response) { if (nullptr == response) { return nullptr; } - + char* content = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, @@ -308,18 +334,22 @@ public: { jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - + _contentLength = getCStrFromJByteArray((jbyteArray)jObj, methodInfo.env, &content); - if (nullptr != jObj) + if (nullptr != jObj) { methodInfo.env->DeleteLocalRef(jObj); } methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return content; } - + char* getResponseHeaderByKey(const char* key) { char* value = nullptr; @@ -339,10 +369,14 @@ public: } methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return value; } - + int getResponseHeaderByKeyInt(const char* key) { int contentLength = 0; @@ -358,10 +392,14 @@ public: methodInfo.env->DeleteLocalRef(jstrKey); methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return contentLength; } - + char* getResponseHeaderByIdx(int idx) { char* header = nullptr; @@ -379,25 +417,29 @@ public: } methodInfo.env->DeleteLocalRef(methodInfo.classID); } - + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } + return header; } - + const std::string& getCookieFileName() const { return _cookieFileName; } - + void setCookieFileName(std::string& filename) { _cookieFileName = filename; } - + int getContentLength() { return _contentLength; } - + private: void createHttpURLConnection(const std::string& url) { @@ -415,9 +457,13 @@ private: methodInfo.env->DeleteLocalRef(jObj); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } - void addRequestHeader(const char* key, const char* value) + void addRequestHeader(const char* key, const char* value) { JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, @@ -433,61 +479,62 @@ private: methodInfo.env->DeleteLocalRef(jstrVal); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } - + void addCookiesForRequestHeader() { if(_client->getCookieFilename().empty()) { return; } - + _cookieFileName = FileUtils::getInstance()->fullPathForFilename(_client->getCookieFilename()); - + std::string cookiesInfo = FileUtils::getInstance()->getStringFromFile(_cookieFileName); - + if (cookiesInfo.empty()) return; - + HttpCookies cookiesVec; cookiesVec.clear(); - + std::stringstream stream(cookiesInfo); std::string item; while (std::getline(stream, item, '\n')) { cookiesVec.push_back(item); } - + if (cookiesVec.empty()) return; - - HttpCookiesIter iter = cookiesVec.begin(); - + std::vector cookiesInfoVec; cookiesInfoVec.clear(); - for (; iter != cookiesVec.end(); iter++) + for (auto& cookies : cookiesVec) { - std::string cookies = *iter; if (cookies.find("#HttpOnly_") != std::string::npos) { cookies = cookies.substr(10); } - + if(cookies.at(0) == '#') continue; - + CookiesInfo co; std::stringstream streamInfo(cookies); std::string item; std::vector elems; - + while (std::getline(streamInfo, item, '\t')) { elems.push_back(item); } - + co.domain = elems[0]; if (co.domain.at(0) == '.') { @@ -502,19 +549,18 @@ private: cookiesInfoVec.push_back(co); } - std::vector::iterator cookiesIter = cookiesInfoVec.begin(); std::string sendCookiesInfo = ""; int cookiesCount = 0; - for (; cookiesIter != cookiesInfoVec.end(); cookiesIter++) + for (auto& cookieInfo : cookiesInfoVec) { - if (_url.find(cookiesIter->domain) != std::string::npos) + if (_url.find(cookieInfo.domain) != std::string::npos) { - std::string keyValue = cookiesIter->key; + std::string keyValue = cookieInfo.key; keyValue.append("="); - keyValue.append(cookiesIter->value); + keyValue.append(cookieInfo.value); if (cookiesCount != 0) sendCookiesInfo.append(";"); - + sendCookiesInfo.append(keyValue); } cookiesCount++; @@ -536,6 +582,10 @@ private: methodInfo.classID, methodInfo.methodID, _httpURLConnection, readMiliseconds, connectMiliseconds); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } void setVerifySSL() @@ -557,10 +607,14 @@ private: methodInfo.env->DeleteLocalRef(jstrfullpath); methodInfo.env->DeleteLocalRef(methodInfo.classID); } + else + { + CCLOGERROR("HttpClient::%s failed!", __FUNCTION__); + } } bool configure() - { + { if(nullptr == _httpURLConnection) { return false; @@ -584,10 +638,8 @@ private: { return nullptr; } - char *ret = nullptr; std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, jstr); - ret = strdup(strValue.c_str()); - return ret; + return strdup(strValue.c_str()); } int getCStrFromJByteArray(jbyteArray jba, JNIEnv* env, char** ppData) @@ -598,10 +650,8 @@ private: return 0; } - char* str = nullptr; - - int len = env->GetArrayLength(jba); - str = (char*)malloc(sizeof(char)*len); + int len = env->GetArrayLength(jba); + char* str = (char*)malloc(sizeof(char)*len); env->GetByteArrayRegion(jba, 0, len, (jbyte*)str); *ppData = str; @@ -686,6 +736,14 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) responseCode = urlConnection.getResponseCode(); + if (0 == responseCode) + { + response->setSucceed(false); + response->setErrorBuffer("connect failed"); + response->setResponseCode(-1); + return; + } + char* headers = urlConnection.getResponseHeaders(); if (nullptr != headers) { @@ -704,17 +762,20 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) //content len int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length"); char* contentInfo = urlConnection.getResponseContent(response); - if (nullptr != contentInfo) + if (nullptr != contentInfo) { std::vector * recvBuffer = (std::vector*)response->getResponseData(); recvBuffer->clear(); recvBuffer->insert(recvBuffer->begin(), (char*)contentInfo, ((char*)contentInfo) + urlConnection.getContentLength()); } free(contentInfo); - + char *messageInfo = urlConnection.getResponseMessage(); - strcpy(responseMessage, messageInfo); - free(messageInfo); + if (messageInfo) + { + strcpy(responseMessage, messageInfo); + free(messageInfo); + } urlConnection.disconnect(); @@ -724,7 +785,14 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) if (responseCode == -1) { response->setSucceed(false); - response->setErrorBuffer(responseMessage); + if (responseMessage != nullptr) + { + response->setErrorBuffer(responseMessage); + } + else + { + response->setErrorBuffer("response code error!"); + } } else { @@ -734,10 +802,10 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) // Worker thread void HttpClient::networkThread() -{ +{ increaseThreadCount(); - while (true) + while (true) { HttpRequest *request; @@ -754,16 +822,16 @@ void HttpClient::networkThread() if (request == _requestSentinel) { break; } - + // Create a HttpResponse object, the default setting is http access failed HttpResponse *response = new (std::nothrow) HttpResponse(request); processResponse(response, _responseMessage); - + // add response packet into queue _responseQueueMutex.lock(); _responseQueue.pushBack(response); _responseQueueMutex.unlock(); - + _schedulerMutex.lock(); if (nullptr != _scheduler) { @@ -771,17 +839,17 @@ void HttpClient::networkThread() } _schedulerMutex.unlock(); } - + // cleanup: if worker thread received quit signal, clean up un-completed request queue _requestQueueMutex.lock(); _requestQueue.clear(); _requestQueueMutex.unlock(); - + _responseQueueMutex.lock(); _responseQueue.clear(); _responseQueueMutex.unlock(); - decreaseThreadCountAndMayDeleteThis(); + decreaseThreadCountAndMayDeleteThis(); } // Worker thread @@ -815,11 +883,11 @@ void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response // HttpClient implementation HttpClient* HttpClient::getInstance() { - if (_httpClient == nullptr) + if (_httpClient == nullptr) { _httpClient = new (std::nothrow) HttpClient(); } - + return _httpClient; } @@ -852,7 +920,7 @@ void HttpClient::destroyInstance() CCLOG("HttpClient::destroyInstance() finished!"); } -void HttpClient::enableCookies(const char* cookieFile) +void HttpClient::enableCookies(const char* cookieFile) { std::lock_guard lock(_cookieFileMutex); if (cookieFile) @@ -864,7 +932,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt"); } } - + void HttpClient::setSSLVerification(const std::string& caFile) { std::lock_guard lock(_sslCaFileMutex); @@ -872,12 +940,12 @@ void HttpClient::setSSLVerification(const std::string& caFile) } HttpClient::HttpClient() -: _timeoutForConnect(30) +: _isInited(false) +, _timeoutForConnect(30) , _timeoutForRead(60) -, _isInited(false) , _threadCount(0) -, _requestSentinel(new HttpRequest()) , _cookie(nullptr) +, _requestSentinel(new HttpRequest()) { CCLOG("In the constructor of HttpClient!"); increaseThreadCount(); @@ -891,7 +959,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -909,17 +977,17 @@ bool HttpClient::lazyInitThreadSemphore() //Add a get task to queue void HttpClient::send(HttpRequest* request) -{ - if (!lazyInitThreadSemphore()) +{ + if (!lazyInitThreadSemaphore()) { return; } - + if (nullptr == request) { return; } - + request->retain(); _requestQueueMutex.lock(); @@ -951,7 +1019,7 @@ void HttpClient::dispatchResponseCallbacks() // log("CCHttpClient::dispatchResponseCallbacks is running"); //occurs when cocos thread fires but the network thread has already quited HttpResponse* response = nullptr; - + _responseQueueMutex.lock(); if (!_responseQueue.empty()) @@ -961,7 +1029,7 @@ void HttpClient::dispatchResponseCallbacks() } _responseQueueMutex.unlock(); - + if (response) { HttpRequest *request = response->getHttpRequest(); @@ -994,7 +1062,7 @@ void HttpClient::decreaseThreadCountAndMayDeleteThis() { needDeleteThis = true; } - + _threadCountMutex.unlock(); if (needDeleteThis) { @@ -1007,31 +1075,31 @@ void HttpClient::setTimeoutForConnect(int value) std::lock_guard lock(_timeoutForConnectMutex); _timeoutForConnect = value; } - + int HttpClient::getTimeoutForConnect() { std::lock_guard lock(_timeoutForConnectMutex); return _timeoutForConnect; } - + void HttpClient::setTimeoutForRead(int value) { std::lock_guard lock(_timeoutForReadMutex); _timeoutForRead = value; } - + int HttpClient::getTimeoutForRead() { std::lock_guard lock(_timeoutForReadMutex); return _timeoutForRead; } - + const std::string& HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } - + const std::string& HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index 6288c8648e..f807450eeb 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -1,7 +1,7 @@ /**************************************************************************** Copyright (c) 2012 greathqy Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -49,8 +49,9 @@ static int processTask(HttpClient* client, HttpRequest *request, NSString *reque void HttpClient::networkThread() { increaseThreadCount(); - + while (true) @autoreleasepool { + HttpRequest *request; // step 1: send http request if the requestQueue isn't empty @@ -84,16 +85,16 @@ void HttpClient::networkThread() } _schedulerMutex.unlock(); } - + // cleanup: if worker thread received quit signal, clean up un-completed request queue _requestQueueMutex.lock(); _requestQueue.clear(); _requestQueueMutex.unlock(); - + _responseQueueMutex.lock(); _responseQueue.clear(); _responseQueueMutex.unlock(); - + decreaseThreadCountAndMayDeleteThis(); } @@ -101,7 +102,7 @@ void HttpClient::networkThread() void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response) { increaseThreadCount(); - + char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 }; processResponse(response, responseMessage); @@ -133,7 +134,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque strcpy(errorBuffer, "client object is invalid"); return 0; } - + //create request with url NSString* urlstring = [NSString stringWithUTF8String:request->getUrl()]; NSURL *url = [NSURL URLWithString:urlstring]; @@ -150,12 +151,12 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque if(!headers.empty()) { /* append custom headers one by one */ - for (std::vector::iterator it = headers.begin(); it != headers.end(); ++it) + for (auto& header : headers) { - unsigned long i = it->find(':', 0); - unsigned long length = it->size(); - std::string field = it->substr(0, i); - std::string value = it->substr(i+1, length-i); + unsigned long i = header.find(':', 0); + unsigned long length = header.size(); + std::string field = header.substr(0, i); + std::string value = header.substr(i+1, length-i); NSString *headerField = [NSString stringWithUTF8String:field.c_str()]; NSString *headerValue = [NSString stringWithUTF8String:value.c_str()]; [nsrequest setValue:headerValue forHTTPHeaderField:headerField]; @@ -164,7 +165,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque //if request type is post or put,set header and data if([requestType isEqual: @"POST"] || [requestType isEqual: @"PUT"]) - { + { char* requestDataBuffer = request->getRequestData(); if (nullptr != requestDataBuffer && 0 != request->getRequestDataSize()) { @@ -190,34 +191,34 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque value, NSHTTPCookieValue, path, NSHTTPCookiePath, domain, NSHTTPCookieDomain, nil]; - + // create the cookie from the properties NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties]; - + // add the cookie to the cookie storage [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; } } - + HttpAsynConnection *httpAsynConn = [[HttpAsynConnection new] autorelease]; httpAsynConn.srcURL = urlstring; httpAsynConn.sslFile = nil; - + std::string sslCaFileName = client->getSSLVerification(); if(!sslCaFileName.empty()) { long len = sslCaFileName.length(); long pos = sslCaFileName.rfind('.', len-1); - + httpAsynConn.sslFile = [NSString stringWithUTF8String:sslCaFileName.substr(0, pos).c_str()]; } [httpAsynConn startRequest:nsrequest]; - + while( httpAsynConn.finish != true) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } - + //if http connection return error if (httpAsynConn.connError != nil) { @@ -232,9 +233,9 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque NSString* errorString = [httpAsynConn.responseError localizedDescription]; strcpy(errorBuffer, [errorString UTF8String]); } - + *responseCode = httpAsynConn.responseCode; - + //add cookie to cookies vector if(!cookieFilename.empty()) { @@ -249,7 +250,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque NSDate *date = cookie.expiresDate; NSString *name = cookie.name; NSString *value = cookie.value; - + CookiesInfo cookieInfo; cookieInfo.domain = [domain cStringUsingEncoding: NSUTF8StringEncoding]; cookieInfo.path = [path cStringUsingEncoding: NSUTF8StringEncoding]; @@ -258,11 +259,11 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque cookieInfo.name = [name cStringUsingEncoding: NSUTF8StringEncoding]; cookieInfo.value = [value cStringUsingEncoding: NSUTF8StringEncoding]; cookieInfo.tailmatch = true; - + client->getCookie()->updateOrAddCookie(&cookieInfo); } } - + //handle response header NSMutableString *header = [NSMutableString string]; [header appendFormat:@"HTTP/1.1 %ld %@\n", (long)httpAsynConn.responseCode, httpAsynConn.statusString]; @@ -358,12 +359,12 @@ void HttpClient::setSSLVerification(const std::string& caFile) } HttpClient::HttpClient() -: _timeoutForConnect(30) +: _isInited(false) +, _timeoutForConnect(30) , _timeoutForRead(60) -, _isInited(false) , _threadCount(0) -, _requestSentinel(new HttpRequest()) , _cookie(nullptr) +, _requestSentinel(new HttpRequest()) { CCLOG("In the constructor of HttpClient!"); memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE); @@ -384,7 +385,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -403,7 +404,7 @@ bool HttpClient::lazyInitThreadSemphore() //Add a get task to queue void HttpClient::send(HttpRequest* request) { - if (false == lazyInitThreadSemphore()) + if (false == lazyInitThreadSemaphore()) { return; } @@ -496,7 +497,7 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) break; default: - CCASSERT(false , "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported"); + CCASSERT(false, "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported"); break; } diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index 20104fc346..9d790ca837 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -1,20 +1,20 @@ /**************************************************************************** Copyright (c) 2012 greathqy Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - + Copyright (c) 2013-2017 Chukong Technologies Inc. + http://www.cocos2d-x.org - + 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 @@ -48,11 +48,11 @@ static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) { std::vector *recvBuffer = (std::vector*)stream; size_t sizes = size * nmemb; - + // add data to the end of recvBuffer // write data maybe called more than once in a single request recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes); - + return sizes; } @@ -61,11 +61,11 @@ static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream { std::vector *recvBuffer = (std::vector*)stream; size_t sizes = size * nmemb; - + // add data to the end of recvBuffer // write data maybe called more than once in a single request recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes); - + return sizes; } @@ -101,7 +101,7 @@ void HttpClient::networkThread() } // step 2: libcurl sync access - + // Create a HttpResponse object, the default setting is http access failed HttpResponse *response = new (std::nothrow) HttpResponse(request); @@ -120,7 +120,7 @@ void HttpClient::networkThread() } _schedulerMutex.unlock(); } - + // cleanup: if worker thread received quit signal, clean up un-completed request queue _requestQueueMutex.lock(); _requestQueue.clear(); @@ -167,7 +167,7 @@ static bool configureCURL(HttpClient* client, CURL* handle, char* errorBuffer) if (!handle) { return false; } - + int32_t code; code = curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, errorBuffer); if (code != CURLE_OK) { @@ -191,9 +191,9 @@ static bool configureCURL(HttpClient* client, CURL* handle, char* errorBuffer) curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 2L); curl_easy_setopt(handle, CURLOPT_CAINFO, sslCaFilename.c_str()); } - + // FIXED #3224: The subthread of CCHttpClient interrupts main thread if timeout comes. - // Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL + // Document is here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTNOSIGNAL curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, ""); @@ -247,8 +247,8 @@ public: if(!headers.empty()) { /* append custom headers one by one */ - for (std::vector::iterator it = headers.begin(); it != headers.end(); ++it) - _headers = curl_slist_append(_headers,it->c_str()); + for (auto& header : headers) + _headers = curl_slist_append(_headers,header.c_str()); /* set custom headers for curl */ if (!setOption(CURLOPT_HTTPHEADER, _headers)) return false; @@ -268,7 +268,7 @@ public: && setOption(CURLOPT_WRITEDATA, stream) && setOption(CURLOPT_HEADERFUNCTION, headerCallback) && setOption(CURLOPT_HEADERDATA, headerStream); - + } /// @param responseCode Null not allowed @@ -282,7 +282,7 @@ public: return false; } // Get some mor data. - + return true; } }; @@ -339,7 +339,7 @@ HttpClient* HttpClient::getInstance() { _httpClient = new (std::nothrow) HttpClient(); } - + return _httpClient; } @@ -382,7 +382,7 @@ void HttpClient::enableCookies(const char* cookieFile) _cookieFilename = (FileUtils::getInstance()->getWritablePath() + "cookieFile.txt"); } } - + void HttpClient::setSSLVerification(const std::string& caFile) { std::lock_guard lock(_sslCaFileMutex); @@ -390,12 +390,12 @@ void HttpClient::setSSLVerification(const std::string& caFile) } HttpClient::HttpClient() -: _timeoutForConnect(30) +: _isInited(false) +, _timeoutForConnect(30) , _timeoutForRead(60) -, _isInited(false) , _threadCount(0) -, _requestSentinel(new HttpRequest()) , _cookie(nullptr) +, _requestSentinel(new HttpRequest()) { CCLOG("In the constructor of HttpClient!"); memset(_responseMessage, 0, RESPONSE_BUFFER_SIZE * sizeof(char)); @@ -410,7 +410,7 @@ HttpClient::~HttpClient() } //Lazy create semaphore & mutex & thread -bool HttpClient::lazyInitThreadSemphore() +bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { @@ -422,23 +422,23 @@ bool HttpClient::lazyInitThreadSemphore() t.detach(); _isInited = true; } - + return true; } //Add a get task to queue void HttpClient::send(HttpRequest* request) { - if (false == lazyInitThreadSemphore()) + if (false == lazyInitThreadSemaphore()) { return; } - + if (!request) { return; } - + request->retain(); _requestQueueMutex.lock(); @@ -478,7 +478,7 @@ void HttpClient::dispatchResponseCallbacks() _responseQueue.erase(0); } _responseQueueMutex.unlock(); - + if (response) { HttpRequest *request = response->getHttpRequest(); @@ -546,7 +546,7 @@ void HttpClient::processResponse(HttpResponse* response, char* responseMessage) break; default: - CCASSERT(false , "CCHttpClient: unknown request type, only GET,POST,PUT or DELETE is supported"); + CCASSERT(false, "CCHttpClient: unknown request type, only GET, POST, PUT or DELETE is supported"); break; } @@ -592,31 +592,31 @@ void HttpClient::setTimeoutForConnect(int value) std::lock_guard lock(_timeoutForConnectMutex); _timeoutForConnect = value; } - + int HttpClient::getTimeoutForConnect() { std::lock_guard lock(_timeoutForConnectMutex); return _timeoutForConnect; } - + void HttpClient::setTimeoutForRead(int value) { std::lock_guard lock(_timeoutForReadMutex); _timeoutForRead = value; } - + int HttpClient::getTimeoutForRead() { std::lock_guard lock(_timeoutForReadMutex); return _timeoutForRead; } - + const std::string& HttpClient::getCookieFilename() { std::lock_guard lock(_cookieFileMutex); return _cookieFilename; } - + const std::string& HttpClient::getSSLVerification() { std::lock_guard lock(_sslCaFileMutex); @@ -627,3 +627,4 @@ const std::string& HttpClient::getSSLVerification() NS_CC_END + diff --git a/native/cocos/network/HttpClient.h b/native/cocos/network/HttpClient.h index b5a6841b04..a24d448b35 100644 --- a/native/cocos/network/HttpClient.h +++ b/native/cocos/network/HttpClient.h @@ -1,7 +1,7 @@ /**************************************************************************** Copyright (c) 2012 greathqy Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -162,7 +162,7 @@ private: * Init pthread mutex, semaphore, and create new thread for http requests * @return bool */ - bool lazyInitThreadSemphore(); + bool lazyInitThreadSemaphore(); void networkThread(); void networkThreadAlone(HttpRequest* request, HttpResponse* response); /** Poll function called from main thread to dispatch callbacks when http requests finished **/ diff --git a/native/cocos/network/HttpCookie.cpp b/native/cocos/network/HttpCookie.cpp index 3c8b60704c..cf9a4f864f 100644 --- a/native/cocos/network/HttpCookie.cpp +++ b/native/cocos/network/HttpCookie.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -47,10 +47,8 @@ void HttpCookie::readFile() _cookies.clear(); - for(auto iter = cookiesVec.begin();iter != cookiesVec.end(); iter++) + for(auto& cookie : cookiesVec) { - std::string cookie = *iter; - if(cookie.length() == 0) continue; @@ -95,10 +93,10 @@ const std::vector* HttpCookie::getCookies() const const CookiesInfo* HttpCookie::getMatchCookie(const std::string& url) const { - for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++) + for(auto& cookie : _cookies) { - if(url.find(iter->domain) != std::string::npos) - return &(*iter); + if(url.find(cookie.domain) != std::string::npos) + return &cookie; } return nullptr; @@ -106,11 +104,11 @@ const CookiesInfo* HttpCookie::getMatchCookie(const std::string& url) const void HttpCookie::updateOrAddCookie(CookiesInfo* cookie) { - for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++) + for(auto& _cookie : _cookies) { - if(cookie->domain == iter->domain) + if(cookie->domain == _cookie.domain) { - *iter = *cookie; + _cookie = *cookie; return; } } @@ -128,22 +126,22 @@ void HttpCookie::writeFile() out); std::string line; - for(auto iter = _cookies.begin(); iter != _cookies.end(); iter++) + for(auto& cookie : _cookies) { line.clear(); - line.append(iter->domain); + line.append(cookie.domain); line.append(1, '\t'); - iter->tailmatch ? line.append("TRUE") : line.append("FALSE"); + cookie.tailmatch ? line.append("TRUE") : line.append("FALSE"); line.append(1, '\t'); - line.append(iter->path); + line.append(cookie.path); line.append(1, '\t'); - iter->secure ? line.append("TRUE") : line.append("FALSE"); + cookie.secure ? line.append("TRUE") : line.append("FALSE"); line.append(1, '\t'); - line.append(iter->expires); + line.append(cookie.expires); line.append(1, '\t'); - line.append(iter->name); + line.append(cookie.name); line.append(1, '\t'); - line.append(iter->value); + line.append(cookie.value); //line.append(1, '\n'); fprintf(out, "%s\n", line.c_str()); diff --git a/native/cocos/network/HttpCookie.h b/native/cocos/network/HttpCookie.h index 86450d79cb..ab81795b04 100644 --- a/native/cocos/network/HttpCookie.h +++ b/native/cocos/network/HttpCookie.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index 99eeec5873..6c0aec0c38 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -79,7 +79,7 @@ public: /** * Constructor. - * Because HttpRequest object will be used between UI thead and network thread, + * Because HttpRequest object will be used between UI thread and network thread, requestObj->autorelease() is forbidden to avoid crashes in AutoreleasePool new/retain/release still works, which means you need to release it manually Please refer to HttpRequestTest.cpp to find its usage. diff --git a/native/cocos/network/HttpResponse.h b/native/cocos/network/HttpResponse.h index efbae4bfe4..f73eaba0e5 100644 --- a/native/cocos/network/HttpResponse.h +++ b/native/cocos/network/HttpResponse.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -51,9 +51,9 @@ public: * @param request the corresponding HttpRequest which leads to this response. */ HttpResponse(HttpRequest* request) - : _pHttpRequest(request) - , _succeed(false) - , _responseDataString("") + : _pHttpRequest(request) + , _succeed(false) + , _responseDataString("") { if (_pHttpRequest) { @@ -89,7 +89,7 @@ public: /** * Get the corresponding HttpRequest object which leads to this response. - * There's no paired setter for it, because it's already setted in class constructor + * There's no paired setter for it, because it's already set in class constructor * @return HttpRequest* the corresponding HttpRequest object which leads to this response. */ inline HttpRequest* getHttpRequest() const @@ -196,7 +196,8 @@ public: inline void setErrorBuffer(const char* value) { _errorBuffer.clear(); - _errorBuffer.assign(value); + if (value != nullptr) + _errorBuffer.assign(value); } /** diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java index aa3745f3d6..1568013ee7 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java @@ -234,7 +234,6 @@ public class Cocos2dxEditBoxHelper { if (editBox != null) { mEditBoxArray.remove(index); mFrameLayout.removeView(editBox); - Log.e(TAG, "remove EditBox"); } } }); diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java index 33bdac6759..adfb8c599a 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java @@ -150,6 +150,9 @@ public class Cocos2dxHttpURLConnection Log.e("cocos2d-x debug info", "come in connect"); Log.e("cocos2d-x debug info", e.toString()); suc = 1; + } catch (Exception e) { + e.printStackTrace(); + suc = 1; } return suc; diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java index 012d4b62bb..d18e4e88f4 100755 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java @@ -101,6 +101,8 @@ public class Cocos2dxWebViewHelper { if (webView != null) { webViews.remove(index); sLayout.removeView(webView); + webView.destroy(); + webView = null; } } }); diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 80d97b9b58..c2bdc31560 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -1,5 +1,7 @@ /* - * Copyright (c) 2017 Chukong Technologies Inc. + * Created by Rolando Abarca on 3/14/12. + * Copyright (c) 2012 Zynga Inc. All rights reserved. + * Copyright (c) 2013-2016 Chukong Technologies Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -21,13 +23,523 @@ */ #include "scripting/js-bindings/manual/ScriptingCore.h" -#include "scripting/js-bindings/manual/jsb_conversions.hpp" -#include "scripting/js-bindings/jswrapper/SeApi.h" -#include "cocos2d.h" +#include "js/Initialization.h" +#include "storage/local-storage/LocalStorage.h" +#include "scripting/js-bindings/manual/cocos2d_specifics.hpp" +#include "scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp" +#include "scripting/js-bindings/manual/js_bindings_config.h" +#include "scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp" +#include "network/HttpClient.h" + +#include "cocos2d.h" // we used cocos2dVersion() ... + +// for debug socket +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ANDROID +#include +#include +#include +#endif + +#ifdef ANDROID +#define LOG_TAG "ScriptingCore.cpp" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +#else +#define LOGD(...) js_log(__VA_ARGS__) +#endif + +#if COCOS2D_DEBUG +#define TRACE_DEBUGGER_SERVER(...) CCLOG(__VA_ARGS__) +#else +#define TRACE_DEBUGGER_SERVER(...) +#endif // #if COCOS2D_DEBUG + +#define BYTE_CODE_FILE_EXT ".jsc" using namespace cocos2d; +static std::string inData; +static std::string outData; +static std::vector g_queue; +static std::mutex g_qMutex; +static std::mutex g_rwMutex; +static int clientSocket = -1; +static uint32_t s_nestedLoopLevel = 0; + +// server entry point for the bg thread +static void serverEntryPoint(unsigned int port); + +// global datas +// type name ~> jsb class type +std::unordered_map *_js_global_type_map = nullptr; +// native pointer ~> jsb proxy +static std::unordered_map *_native_js_global_map = nullptr; +// filename ~> JSScript +static std::unordered_map *_filename_script = nullptr; +// port ~> socket +static std::unordered_map ports_sockets; +// callback list for JSB API registration +static std::vector registrationList; + +static char *_js_log_buf = nullptr; + +const char *ScriptingCore::EVENT_RESET = "scriptingcore_event_reset"; + +static void cc_closesocket(int fd) +{ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + closesocket(fd); +#else + close(fd); +#endif +} + +static std::string getTouchesFuncName(EventTouch::EventCode eventCode) +{ + std::string funcName; + switch(eventCode) + { + case EventTouch::EventCode::BEGAN: + funcName = "onTouchesBegan"; + break; + case EventTouch::EventCode::ENDED: + funcName = "onTouchesEnded"; + break; + case EventTouch::EventCode::MOVED: + funcName = "onTouchesMoved"; + break; + case EventTouch::EventCode::CANCELLED: + funcName = "onTouchesCancelled"; + break; + default: + CCASSERT(false, "Invalid event code!"); + break; + } + return funcName; +} + +static std::string getTouchFuncName(EventTouch::EventCode eventCode) +{ + std::string funcName; + switch(eventCode) { + case EventTouch::EventCode::BEGAN: + funcName = "onTouchBegan"; + break; + case EventTouch::EventCode::ENDED: + funcName = "onTouchEnded"; + break; + case EventTouch::EventCode::MOVED: + funcName = "onTouchMoved"; + break; + case EventTouch::EventCode::CANCELLED: + funcName = "onTouchCancelled"; + break; + default: + CCASSERT(false, "Invalid event code!"); + } + + return funcName; +} + +static std::string getMouseFuncName(EventMouse::MouseEventType eventType) +{ + std::string funcName; + switch(eventType) { + case EventMouse::MouseEventType::MOUSE_DOWN: + funcName = "onMouseDown"; + break; + case EventMouse::MouseEventType::MOUSE_UP: + funcName = "onMouseUp"; + break; + case EventMouse::MouseEventType::MOUSE_MOVE: + funcName = "onMouseMove"; + break; + case EventMouse::MouseEventType::MOUSE_SCROLL: + funcName = "onMouseScroll"; + break; + default: + CCASSERT(false, "Invalid event code!"); + } + + return funcName; +} + +void ScriptingCore::executeJSFunctionWithThisObj(JS::HandleValue thisObj, JS::HandleValue callback) +{ + JS::RootedValue retVal(_cx); + executeJSFunctionWithThisObj(thisObj, callback, JS::HandleValueArray::empty(), &retVal); +} + +void ScriptingCore::executeJSFunctionWithThisObj(JS::HandleValue thisObj, + JS::HandleValue callback, + const JS::HandleValueArray& vp, + JS::MutableHandleValue retVal) +{ + if (!callback.isNullOrUndefined() || !thisObj.isNullOrUndefined()) + { + // Very important: The last parameter 'retVal' passed to 'JS_CallFunctionValue' should not be a NULL pointer. + // If it's a NULL pointer, crash will be triggered in 'JS_CallFunctionValue'. To find out the reason of this crash is very difficult. + // So we have to check the availability of 'retVal'. + JS::RootedObject jsthis(_cx, thisObj.toObjectOrNull()); + JS_CallFunctionValue(_cx, jsthis, callback, vp, retVal); + if (JS_IsExceptionPending(_cx)) { + handlePendingException(_cx); + } + } +} + +static void ReportException(JSContext *cx) +{ + if (JS_IsExceptionPending(cx)) { + handlePendingException(cx); + } +} + +void js_log(const char *format, ...) +{ +#if COCOS2D_DEBUG + if (_js_log_buf == NULL) + { + _js_log_buf = (char *)calloc(sizeof(char), MAX_LOG_LENGTH+1); + _js_log_buf[MAX_LOG_LENGTH] = '\0'; + } + va_list vl; + va_start(vl, format); + int len = vsnprintf(_js_log_buf, MAX_LOG_LENGTH, format, vl); + va_end(vl); + if (len > 0) + { + log("%s", _js_log_buf); + } +#endif +} + +bool JSBCore_platform(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + if (argc!=0) + { + JS_ReportErrorUTF8(cx, "Invalid number of arguments in __getPlatform"); + return false; + } + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + Application::Platform platform; + + platform = Application::getInstance()->getTargetPlatform(); + args.rval().set(JS::Int32Value((int)platform)); + return true; +}; + +bool JSBCore_version(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + if (argc!=0) + { + JS_ReportErrorUTF8(cx, "Invalid number of arguments in __getVersion"); + return false; + } + + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + std::string version = cocos2dVersion(); + JS::RootedValue js_version(cx); + std_string_to_jsval(cx, version, &js_version); + + args.rval().set(js_version); + return true; +}; + +bool JSBCore_os(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + if (argc!=0) + { + JS_ReportErrorUTF8(cx, "Invalid number of arguments in __getOS"); + return false; + } + + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + + JS::RootedValue os(cx); + + // osx, ios, android, windows, linux, etc.. +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + c_string_to_jsval(cx, "iOS", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + c_string_to_jsval(cx, "Android", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) + c_string_to_jsval(cx, "Windows", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE) + c_string_to_jsval(cx, "Marmalade", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) + c_string_to_jsval(cx, "Linux", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BADA) + c_string_to_jsval(cx, "Bada", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) + c_string_to_jsval(cx, "Blackberry", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + c_string_to_jsval(cx, "OS X", &os); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + c_string_to_jsval(cx, "WINRT", &os); +#else + c_string_to_jsval(cx, "Unknown", &os); +#endif + + args.rval().set(os); + return true; +}; + +bool JSB_cleanScript(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + if (argc != 1) + { + JS_ReportErrorUTF8(cx, "Invalid number of arguments in JSB_cleanScript"); + return false; + } + + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedString jsPath(cx, args.get(0).toString()); + JSB_PRECONDITION2(jsPath, cx, false, "Error js file in clean script"); + JSStringWrapper wrapper(jsPath); + ScriptingCore::getInstance()->cleanScript(wrapper.get()); + + args.rval().setUndefined(); + + return true; +}; + +bool JSB_core_restartVM(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments in executeScript"); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + ScriptingCore::getInstance()->reset(); + args.rval().setUndefined(); + return true; +}; + +bool JSB_closeWindow(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + EventListenerCustom* _event = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [&](EventCustom *event) { + Director::getInstance()->getEventDispatcher()->removeEventListener(_event); + CC_SAFE_RELEASE(_event); + + ScriptingCore::getInstance()->cleanup(); + }); + _event->retain(); + Director::getInstance()->end(); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + exit(0); +#endif + return true; +}; + +void registerDefaultClasses(JSContext* cx, JS::HandleObject global) +{ + JS::RootedObject ns(cx); + get_or_create_js_obj(cx, global, "cc", &ns); + JS::RootedValue nsval(cx, JS::ObjectOrNullValue(ns)); + + // register some global functions + JS_DefineFunction(cx, global, "require", ScriptingCore::executeScript, 1, JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "log", ScriptingCore::log, 0, JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "forceGC", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT); + + JS_DefineFunction(cx, global, "__getPlatform", JSBCore_platform, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "__getOS", JSBCore_os, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "__getVersion", JSBCore_version, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "__restartVM", JSB_core_restartVM, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, global, "__cleanScript", JSB_cleanScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "__isObjectValid", ScriptingCore::isObjectValid, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "close", JSB_closeWindow, 0, JSPROP_READONLY | JSPROP_PERMANENT); + + // + // Javascript controller (__jsc__) + // + JS::RootedObject jsc(cx, JS_NewPlainObject(cx)); + JS::RootedValue jscVal(cx); + jscVal = JS::ObjectOrNullValue(jsc); + JS_SetProperty(cx, global, "__jsc__", jscVal); + +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + JS::RootedValue trueVal(cx, JS::TrueHandleValue); + JS_SetProperty(cx, global, "__ENABLE_GC_FOR_NATIVE_OBJECTS__", trueVal); +#else + JS::RootedValue falseVal(cx, JS::FalseHandleValue); + JS_SetProperty(cx, global, "__ENABLE_GC_FOR_NATIVE_OBJECTS__", falseVal); +#endif + + JS_DefineFunction(cx, jsc, "garbageCollect", ScriptingCore::forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, jsc, "dumpRoot", ScriptingCore::dumpRoot, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, jsc, "executeScript", ScriptingCore::executeScript, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +} + +static const JSClassOps global_classOps = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, + nullptr, + nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook +}; +static const JSClass global_class = { + "global", + JSCLASS_GLOBAL_FLAGS, + &global_classOps +}; + +// Callbacks + +static bool +GetBuildId(JS::BuildIdCharVector* buildId) +{ + const char buildid[] = "cocos_xdr"; + bool ok = buildId->append(buildid, strlen(buildid)); + return ok; +} + +void jsbWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data) +{ + auto it_js = _native_js_global_map->begin(); + while (it_js != _native_js_global_map->end()) + { + js_proxy_t *proxy = it_js->second; + if (proxy->obj) + { + JS_UpdateWeakPointerAfterGC(&proxy->obj); + } + it_js++; + } +} + +static void +on_garbage_collect(JSContext* cx, JSGCStatus status, void* data) +{ + /* We finalize any pending toggle refs before doing any garbage collection, + * so that we can collect the JS wrapper objects, and in order to minimize + * the chances of objects having a pending toggle up queued when they are + * garbage collected. */ + if (status == JSGC_BEGIN) + { + CCLOG("on_garbage_collect: begin, Native -> JS map count: %d\n", (int)_native_js_global_map->size()); + } + else if (status == JSGC_END) + { + CCLOG("on_garbage_collect: end, Native -> JS map count: %d\n", (int)_native_js_global_map->size()); + } +} + +static void warningHandler(JSContext *cx, JSErrorReport *report) +{ + if (cx && report) + { + JS::RootedValue err(cx); + if (JS_GetPendingException(cx, &err)) + { + // Should clear pending exception, otherwise it will trigger infinite loop + JS_ClearPendingException(cx); + } + ScriptingCore::reportError(cx, report, err); + } +}; + +// Promise support + +using JobQueue = JS::GCVector; + +// Per-context shell state. +struct PromiseState +{ + explicit PromiseState(JSContext* cx); + ~PromiseState(); + + JS::PersistentRooted jobQueue; + bool drainingJobQueue; + bool quitting; + EventListenerCustom *drainJobsHook; +}; + +PromiseState* getPromiseState(JSContext* cx) +{ + PromiseState* sc = static_cast(JS_GetContextPrivate(cx)); + assert(sc); + return sc; +} + +JSObject* onGetIncumbentGlobalCallback(JSContext* cx) +{ + return JS::CurrentGlobalOrNull(cx); +} + +bool onEnqueuePromiseJobCallback(JSContext* cx, JS::HandleObject job, JS::HandleObject allocationSite, + JS::HandleObject incumbentGlobal, void* data) +{ + PromiseState* sc = getPromiseState(cx); + assert(job); + return sc->jobQueue.append(job); +} + +bool drainJobQueue() +{ + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + PromiseState* sc = getPromiseState(cx); + if (sc->quitting || sc->drainingJobQueue) + return true; + + sc->drainingJobQueue = true; + + JS::RootedObject job(cx); + JS::HandleValueArray args(JS::HandleValueArray::empty()); + JS::RootedValue rval(cx); + // Execute jobs in a loop until we've reached the end of the queue. + // Since executing a job can trigger enqueuing of additional jobs, + // it's crucial to re-check the queue length during each iteration. + for (size_t i = 0; i < sc->jobQueue.length(); i++) + { + job = sc->jobQueue[i]; + JSAutoCompartment ac(cx, job); + JS::Call(cx, JS::UndefinedHandleValue, job, args, &rval); + if (JS_IsExceptionPending(cx)) { + handlePendingException(cx); + } + sc->jobQueue[i].set(nullptr); + } + sc->jobQueue.clear(); + sc->drainingJobQueue = false; + + return true; +} + +PromiseState::PromiseState(JSContext* cx) +: drainingJobQueue(false) +, quitting(false) +{ + drainJobsHook = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [&](EventCustom *event) { + drainJobQueue(); + }); + CC_SAFE_RETAIN(drainJobsHook); +} + +PromiseState::~PromiseState() +{ + Director::getInstance()->getEventDispatcher()->removeEventListener(drainJobsHook); + CC_SAFE_RELEASE(drainJobsHook); +} + +// Promise support end + ScriptingCore* ScriptingCore::getInstance() { static ScriptingCore* instance = nullptr; @@ -38,40 +550,685 @@ ScriptingCore* ScriptingCore::getInstance() } ScriptingCore::ScriptingCore() -: _callFromScript(false) +: _cx(nullptr) +, _global(nullptr) +, _debugGlobal(nullptr) +, _jsInited(false) +, _needCleanup(false) +, _callFromScript(false) +, _finalizing(nullptr) { + // Init global datas + _js_global_type_map = new (std::nothrow) std::unordered_map(); + _native_js_global_map = new (std::nothrow) std::unordered_map(); + _filename_script = new (std::nothrow) std::unordered_map(); + + bool ok = JS_Init(); + if (!ok) { + CCLOG("System errno : %d", errno); + CCASSERT(ok, "ScriptingCore: failed to initialize JS engine."); + } +} +bool ScriptingCore::evalString(const char *string, JS::MutableHandleValue outVal, const char *filename, JSContext* cx, JS::HandleObject global) +{ + JS::PersistentRootedScript script(cx); + + JS::CompileOptions op(cx); + op.setUTF8(true); + + std::string content = string; + + bool ok = false; + bool evaluatedOK = false; + if (!content.empty()) + { + ok = JS::Compile(cx, op, content.c_str(), content.size(), &(script) ); + } + if (ok) { + evaluatedOK = JS_ExecuteScript(cx, script, outVal); + if (false == evaluatedOK) { + cocos2d::log("Evaluating %s failed (evaluatedOK == JS_FALSE)", content.c_str()); + handlePendingException(cx); + } + } + else { + cocos2d::log("ScriptingCore:: evaluateScript fail: %s", content.c_str()); + } + return evaluatedOK; +} + +bool ScriptingCore::evalString(const char *string, JS::MutableHandleValue outVal) +{ + JS::RootedObject global(_cx, _global->get()); + return evalString(string, outVal, nullptr, _cx, global); +} + +bool ScriptingCore::evalString(const char *string) +{ + JS::RootedValue retVal(_cx); + return evalString(string, &retVal); +} + +void ScriptingCore::start() +{ + _engineStartTime = std::chrono::steady_clock::now(); + // for now just this + createGlobalContext(); +} + +void ScriptingCore::addRegisterCallback(sc_register_sth callback) { + registrationList.push_back(callback); +} + +void ScriptingCore::removeAllProxys(JSContext *cx) +{ + auto it_js = _native_js_global_map->begin(); + while (it_js != _native_js_global_map->end()) + { + // Erase hook private first in case gc access the proxy again + auto proxy = it_js->second; + if (proxy->obj.get()) + { + JS::RootedObject jsObj(cx, proxy->obj); + JS::RootedValue hook(cx); + JS_GetProperty(cx, jsObj, "__hook", &hook); + + if (hook.isObject()) + { + JSObject *hookObj = hook.toObjectOrNull(); + JS_SetPrivate(hookObj, nullptr); + } + } + + CC_SAFE_DELETE(proxy); + it_js = _native_js_global_map->erase(it_js); + } + _native_js_global_map->clear(); +} + +void ScriptingCore::createGlobalContext() { + if (_cx) { + ScriptingCore::removeAllProxys(_cx); + JS_DestroyContext(_cx); + _cx = nullptr; + } + + _cx = JS_NewContext(JS::DefaultHeapMaxBytes); + if (nullptr == _cx) + { + return; + } + + JS_SetGCParameter(_cx, JSGC_MAX_BYTES, 0xffffffff); + JS_SetGCParameter(_cx, JSGC_MAX_MALLOC_BYTES, 1024 * 1024); + JS_SetGCParameter(_cx, JSGC_COMPACTING_ENABLED, true); + JS_SetGCParameter(_cx, JSGC_MODE, JSGC_MODE_INCREMENTAL); + JS_SetNativeStackQuota(_cx, JSB_MAX_STACK_QUOTA); + // Waiting is allowed on the shell's main thread, for now. + JS_SetFutexCanWait(_cx); + JS_SetDefaultLocale(_cx, "UTF-8"); + JS::SetWarningReporter(_cx, warningHandler); +#if COCOS2D_DEBUG > 1 + JS_SetGCCallback(_cx, on_garbage_collect, nullptr); +#endif + + if (!JS::InitSelfHostedCode(_cx)) + { + return; + } + + PromiseState* sc = new (std::nothrow) PromiseState(_cx); + if (!sc) + { + return; + } + JS_SetContextPrivate(_cx, sc); + + JS_BeginRequest(_cx); + + JS::CompartmentOptions options; + options.behaviors().setVersion(JSVERSION_LATEST); + options.creationOptions().setSharedMemoryAndAtomicsEnabled(true); + +#ifdef DEBUG +#ifdef JS_GC_ZEAL + JS_SetGCZeal(_cx, 2, JS_DEFAULT_ZEAL_FREQ); +#endif + + JS::ContextOptionsRef(_cx) + .setExtraWarnings(true) + .setIon(false) + .setBaseline(false) + .setAsmJS(true) + .setNativeRegExp(true); +#else + JS::ContextOptionsRef(_cx) + .setIon(true) + .setBaseline(true) + .setAsmJS(true) + .setNativeRegExp(true); +#endif + + JS::RootedObject global(_cx, JS_NewGlobalObject(_cx, &global_class, nullptr, JS::DontFireOnNewGlobalHook, options)); + _global = new (std::nothrow) JS::PersistentRootedObject(_cx, global); + + _oldCompartment = JS_EnterCompartment(_cx, global); + JS_InitStandardClasses(_cx, global); + JS_DefineDebuggerObject(_cx, global); + + // Register ScriptingCore system bindings + registerDefaultClasses(_cx, global); + + JS_AddWeakPointerCompartmentCallback(_cx, &jsbWeakPointerCompartmentCallback, nullptr); + JS_FireOnNewGlobalObject(_cx, global); + JS::SetBuildIdOp(_cx, GetBuildId); + + // Support promise + sc->jobQueue.init(_cx, JobQueue(js::SystemAllocPolicy())); + JS::SetEnqueuePromiseJobCallback(_cx, onEnqueuePromiseJobCallback); + JS::SetGetIncumbentGlobalCallback(_cx, onGetIncumbentGlobalCallback); + + runScript("script/jsb_prepare.js"); + + for (std::vector::iterator it = registrationList.begin(); it != registrationList.end(); it++) { + sc_register_sth callback = *it; + callback(_cx, global); + + if (JS_IsExceptionPending(_cx)) { + handlePendingException(_cx); + } + } + registrationList.clear(); + + _jsInited = true; + _needCleanup = true; +} + +static std::string RemoveFileExt(const std::string& filePath) { + size_t pos = filePath.rfind('.'); + if (0 < pos) { + return filePath.substr(0, pos); + } + else { + return filePath; + } +} + +bool ScriptingCore::getScript(const std::string& path, JS::MutableHandleScript script) +{ + // a) check jsc file first + std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; + if (_filename_script->find(byteCodePath) != _filename_script->end()) + { + script.set((*_filename_script)[byteCodePath]->get()); + return true; + } + + // b) no jsc file, check js file + std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(path); + if (_filename_script->find(fullPath) != _filename_script->end()) + { + script.set((*_filename_script)[fullPath]->get()); + return true; + } + + return false; +} + +bool ScriptingCore::compileScript(const std::string& path, JS::HandleObject global, JS::MutableHandleScript script) +{ + if (path.empty()) { + return false; + } + + bool ok = getScript(path, script); + if (ok) { + return true; + } + + cocos2d::FileUtils *futil = cocos2d::FileUtils::getInstance(); + bool isPopupNotify = futil->isPopupNotify(); + futil->setPopupNotify(false); + + JS::RootedObject obj(_cx, global); + bool compileSucceed = false; + + // a) check jsc file first + std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; + + // Check whether '.jsc' files exist to avoid outputting log which says 'couldn't find .jsc file'. + if (futil->isFileExist(byteCodePath)) + { + Data data = futil->getDataFromFile(byteCodePath); + if (!data.isNull()) + { + JS::TranscodeBuffer buffer; + bool appended = buffer.append((uint8_t*)data.getBytes(), data.getSize()); + JS::TranscodeResult result = JS::DecodeScript(_cx, buffer, script); + if (appended && result == JS::TranscodeResult::TranscodeResult_Ok) + { + compileSucceed = true; + (*_filename_script)[byteCodePath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get()); + } + } + } + futil->setPopupNotify(isPopupNotify); + + // b) no jsc file, check js file + if (!compileSucceed) + { + /* Clear any pending exception from previous failed decoding. */ + ReportException(_cx); + + JS::CompileOptions op(_cx); + op.setUTF8(true); + std::string fullPath = futil->fullPathForFilename(path); + op.setFileAndLine(fullPath.c_str(), 1); + + ok = false; + std::string jsFileContent = futil->getStringFromFile(fullPath); + if (!jsFileContent.empty()) + { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + ok = JS::Compile(_cx, op, jsFileContent.c_str(), jsFileContent.size(), script); +#else + ok = JS::Compile(_cx, op, fullPath.c_str(), script); +#endif + } + if (ok) { + compileSucceed = true; + (*_filename_script)[fullPath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get()); + } + } + + if (JS_IsExceptionPending(_cx)) { + handlePendingException(_cx); + } + + if (compileSucceed) { + return true; + } else { + LOGD("ScriptingCore::compileScript fail:%s", path.c_str()); + return false; + } +} + +void ScriptingCore::cleanScript(const char *path) +{ + std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; + auto it = _filename_script->find(byteCodePath); + if (it != _filename_script->end()) + { + _filename_script->erase(it); + } + + std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(path); + it = _filename_script->find(fullPath); + if (it != _filename_script->end()) + { + _filename_script->erase(it); + } +} + +std::unordered_map* ScriptingCore::getFileScript() +{ + return _filename_script; +} + +void ScriptingCore::cleanAllScript() +{ + _filename_script->clear(); +} + +bool ScriptingCore::runScript(const std::string& path) +{ + JS::RootedObject global(_cx, _global->get()); + return runScript(path, global, _cx); +} + +bool ScriptingCore::runScript(const std::string& path, JS::HandleObject global, JSContext* cx) +{ + if (cx == nullptr) { + cx = _cx; + } + + JS::RootedScript script(cx); + bool ok = compileScript(path, global, &script); + if (ok) { + JS::RootedValue rval(cx); + ok = JS_ExecuteScript(cx, script, &rval); + if (false == ok) { + cocos2d::log("Evaluating %s failed (evaluatedOK == JS_FALSE)", path.c_str()); + handlePendingException(cx); + } + } + + return ok; +} + +bool ScriptingCore::requireScript(const char *path, JS::MutableHandleValue jsvalRet) +{ + JS::RootedObject global(_cx, _global->get()); + return requireScript(path, global, _cx, jsvalRet); +} + +bool ScriptingCore::requireScript(const char *path, JS::HandleObject global, JSContext* cx, JS::MutableHandleValue jsvalRet) +{ + if (cx == nullptr) + { + cx = _cx; + } + + JS::RootedScript script(cx); + bool ok = compileScript(path, global, &script); + + if (ok) + { + ok = JS_ExecuteScript(cx, script, jsvalRet); + if (!ok) + { + cocos2d::log("(evaluatedOK == JS_FALSE)"); + handlePendingException(cx); + } + } + + return ok; +} + +void ScriptingCore::reset() +{ + Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(EVENT_RESET); + + // Cleanup js objects + JS::RootedObject global(_cx, _global->get()); + JS::RootedValue globalVal(_cx, JS::ObjectOrNullValue(global)); + executeFunctionWithOwner(globalVal, "__cleanup", JS::HandleValueArray::empty()); + + Director::getInstance()->restart(); +} + +void ScriptingCore::restartVM() +{ + cleanup(); + Application::getInstance()->applicationDidFinishLaunching(); } ScriptingCore::~ScriptingCore() { - se::ScriptEngine::destroyInstance(); + cleanup(); + JS_ShutDown(); + + // clear datas + CC_SAFE_DELETE(_js_global_type_map); + CC_SAFE_DELETE(_native_js_global_map); + CC_SAFE_DELETE(_filename_script); } -// Override functions - -void ScriptingCore::retainScriptObject(Ref* owner, Ref* target) +void ScriptingCore::cleanup() { - se::ScriptEngine::getInstance()->_retainScriptObject(owner, target); + if (!_needCleanup) { + return; + } + + localStorageFree(); + + // clear http client callbacks + network::HttpClient::destroyInstance(); + + // Clear all cached script + cleanAllScript(); + + // Cleanup jsb type map + for (auto iter = _js_global_type_map->begin(); iter != _js_global_type_map->end(); ++iter) + { + CC_SAFE_DELETE(iter->second->proto); + free(iter->second); + } + _js_global_type_map->clear(); + + // Release promise state + auto sc = getPromiseState(_cx); + sc->quitting = true; + delete sc; + + // force gc + JS_GC(_cx); + PoolManager::getInstance()->getCurrentPool()->clear(); + CC_SAFE_DELETE(_global); + JS_GC(_cx); + JS_GC(_cx); + + // Remove tracker to object ref, remove all jsb objects proxy + JS_RemoveWeakPointerCompartmentCallback(_cx, jsbWeakPointerCompartmentCallback); + removeAllProxys(_cx); + + // Remove log buf + if (_js_log_buf) { + free(_js_log_buf); + _js_log_buf = nullptr; + } + + if (_cx) + { + JS_LeaveCompartment(_cx, _oldCompartment); + JS::SetGetIncumbentGlobalCallback(_cx, nullptr); + JS::SetEnqueuePromiseJobCallback(_cx, nullptr); + JS_EndRequest(_cx); + JS_DestroyContext(_cx); + } + + _cx = nullptr; + _global = nullptr; + _oldCompartment = nullptr; + _needCleanup = false; } -void ScriptingCore::rootScriptObject(Ref* target) +void ScriptingCore::reportError(JSContext *cx, JSErrorReport *report, JS::HandleValue err) { - assert(false); -} + if (cx && report) + { + std::string fileName = report->filename ? report->filename : ""; + int32_t lineno = report->lineno; + std::string msg = report->message().c_str(); + CCLOGERROR("JS Exception: %s, file: %s, lineno: %u\n", msg.c_str(), fileName.c_str(), lineno); + + std::string stackStr = ""; + if (err.isObject()) + { + JS::RootedObject errObj(cx, err.toObjectOrNull()); + JS::RootedValue stack(cx); + if (JS_GetProperty(cx, errObj, "stack", &stack) && stack.isString()) + { + JS::RootedString jsstackStr(cx, stack.toString()); + char *rawStr = JS_EncodeStringToUTF8(cx, jsstackStr); + if (rawStr != nullptr) + { + stackStr = rawStr; + JS_free(cx, rawStr); + CCLOGERROR("Stack: %s\n", stackStr.c_str()); + } + } + } + + JS::AutoValueVector valArr(cx); + JS::RootedValue argv(cx); + std_string_to_jsval(cx, fileName, &argv); + valArr.append(argv); + valArr.append(JS::Int32Value(lineno)); + std_string_to_jsval(cx, msg, &argv); + valArr.append(argv); + std_string_to_jsval(cx, stackStr, &argv); + valArr.append(argv); + JS::HandleValueArray args(valArr); + + JS::RootedValue rval(cx); + JS::RootedValue global(cx, JS::ObjectOrNullValue(getInstance()->getGlobalObject())); + getInstance()->executeFunctionWithOwner(global, "__errorHandler", args, &rval); + } +}; -void ScriptingCore::releaseScriptObject(Ref* owner, Ref* target) + +bool ScriptingCore::log(JSContext* cx, uint32_t argc, JS::Value *vp) { - assert(!se::ScriptEngine::getInstance()->isGarbageCollecting()); - se::ScriptEngine::getInstance()->_releaseScriptObject(owner, target); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); +#if COCOS2D_DEBUG + if (argc > 0) { + JS::RootedString string(cx, args.get(0).toString()); + if (string) { + JSStringWrapper wrapper(string); + js_log("%s", wrapper.get()); + } + } +#endif + args.rval().setUndefined(); + return true; } -void ScriptingCore::unrootScriptObject(Ref* target) + +void ScriptingCore::retainScriptObject(cocos2d::Ref* owner, cocos2d::Ref* target) { - assert(false); + if (!_global) + { + return; + } + JS::RootedObject global(_cx, _global->get()); + JS::RootedObject jsbObj(_cx); + get_or_create_js_obj(_cx, global, "jsb", &jsbObj); + JS::RootedValue jsbVal(_cx, JS::ObjectOrNullValue(jsbObj)); + if (jsbVal.isNullOrUndefined()) + { + return; + } + + js_proxy_t *pOwner = jsb_get_native_proxy(owner); + js_proxy_t *pTarget = jsb_get_native_proxy(target); + if (!pOwner || !pTarget) + { + return; + } + JS::RootedValue valOwner(_cx, JS::ObjectOrNullValue(pOwner->obj)); + JS::RootedValue valTarget(_cx, JS::ObjectOrNullValue(pTarget->obj)); + if (valTarget.isPrimitive()) + { + return; + } + + JS::RootedValue retval(_cx); + JS::AutoValueVector valArr(_cx); + valArr.append(valOwner); + valArr.append(valTarget); + JS::HandleValueArray args(valArr); + + executeFunctionWithOwner(jsbVal, "registerNativeRef", args, &retval); } -void ScriptingCore::releaseAllChildrenRecursive(Node *node) +void ScriptingCore::rootScriptObject(cocos2d::Ref* target) +{ + if (!_global) + { + return; + } + JS::RootedObject global(_cx, _global->get()); + JS::RootedObject jsbObj(_cx); + get_or_create_js_obj(_cx, global, "jsb", &jsbObj); + JS::RootedValue jsbVal(_cx, JS::ObjectOrNullValue(jsbObj)); + if (jsbVal.isNullOrUndefined()) + { + return; + } + js_proxy_t *pTarget = jsb_get_native_proxy(target); + if (!pTarget) + { + return; + } + JS::RootedValue valTarget(_cx, JS::ObjectOrNullValue(pTarget->obj)); + if (valTarget.isPrimitive()) + { + return; + } + + JS::RootedObject root(_cx); + get_or_create_js_obj(_cx, jsbObj, "_root", &root); + JS::RootedValue valRoot(_cx, JS::ObjectOrNullValue(root)); + + JS::RootedValue retval(_cx); + JS::AutoValueVector valArr(_cx); + valArr.append(valRoot); + valArr.append(valTarget); + JS::HandleValueArray args(valArr); + + executeFunctionWithOwner(jsbVal, "registerNativeRef", args, &retval); +} + +void ScriptingCore::releaseScriptObject(cocos2d::Ref* owner, cocos2d::Ref* target) +{ + JS::RootedObject global(_cx, _global->get()); + JS::RootedObject jsbObj(_cx); + get_or_create_js_obj(_cx, global, "jsb", &jsbObj); + JS::RootedValue jsbVal(_cx, JS::ObjectOrNullValue(jsbObj)); + if (jsbVal.isNullOrUndefined()) + { + return; + } + + js_proxy_t *pOwner = jsb_get_native_proxy(owner); + js_proxy_t *pTarget = jsb_get_native_proxy(target); + if (!pOwner || !pTarget) + { + return; + } + JS::RootedValue valOwner(_cx, JS::ObjectOrNullValue(pOwner->obj)); + JS::RootedValue valTarget(_cx, JS::ObjectOrNullValue(pTarget->obj)); + if (valTarget.isPrimitive()) + { + return; + } + + JS::RootedValue retval(_cx); + JS::AutoValueVector valArr(_cx); + valArr.append(valOwner); + valArr.append(valTarget); + JS::HandleValueArray args(valArr); + + executeFunctionWithOwner(jsbVal, "unregisterNativeRef", args, &retval); +} + +void ScriptingCore::unrootScriptObject(cocos2d::Ref* target) +{ + JS::RootedObject global(_cx, _global->get()); + JS::RootedObject jsbObj(_cx); + get_or_create_js_obj(_cx, global, "jsb", &jsbObj); + JS::RootedValue jsbVal(_cx, JS::ObjectOrNullValue(jsbObj)); + if (jsbVal.isNullOrUndefined()) + { + return; + } + js_proxy_t *pTarget = jsb_get_native_proxy(target); + if (!pTarget) + { + return; + } + JS::RootedValue valTarget(_cx, JS::ObjectOrNullValue(pTarget->obj)); + if (valTarget.isPrimitive()) + { + return; + } + + JS::RootedObject root(_cx); + get_or_create_js_obj(_cx, jsbObj, "_root", &root); + JS::RootedValue valRoot(_cx, JS::ObjectOrNullValue(root)); + + JS::RootedValue retval(_cx); + JS::AutoValueVector valArr(_cx); + valArr.append(valRoot); + valArr.append(valTarget); + JS::HandleValueArray args(valArr); + + executeFunctionWithOwner(jsbVal, "unregisterNativeRef", args, &retval); +} + +void ScriptingCore::releaseAllChildrenRecursive(cocos2d::Node *node) { const Vector& children = node->getChildren(); for (auto child : children) @@ -81,28 +1238,590 @@ void ScriptingCore::releaseAllChildrenRecursive(Node *node) } } -void ScriptingCore::releaseAllNativeRefs(Ref* owner) +void ScriptingCore::releaseAllNativeRefs(cocos2d::Ref* owner) { - assert(false); + JS::RootedObject global(_cx, _global->get()); + JS::RootedObject jsbObj(_cx); + get_or_create_js_obj(_cx, global, "jsb", &jsbObj); + JS::RootedValue jsbVal(_cx, JS::ObjectOrNullValue(jsbObj)); + if (jsbVal.isNullOrUndefined()) + { + return; + } + + js_proxy_t *pOwner = jsb_get_native_proxy(owner); + if (!pOwner) + { + return; + } + JS::RootedValue valOwner(_cx, JS::ObjectOrNullValue(pOwner->obj)); + + JS::RootedValue retval(_cx); + JS::HandleValueArray args(valOwner); + executeFunctionWithOwner(jsbVal, "unregisterAllNativeRefs", args, &retval); } -void ScriptingCore::removeScriptObjectByObject(Ref* obj) + +void ScriptingCore::removeScriptObjectByObject(Ref* pObj) { - assert(false); + auto proxy = jsb_get_native_proxy(pObj); + if (proxy) + { +// JSContext *cx = getGlobalContext(); +// JS::RemoveObjectRoot(cx, &proxy->obj); + jsb_remove_proxy(proxy); + } +} + +bool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + ScriptingCore *engine = ScriptingCore::getInstance(); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + if (argc >= 1) { + JS::RootedValue jsstr(cx, args.get(0)); + JS::RootedString str(cx, jsstr.toString()); + JSStringWrapper path(str); + bool res = false; + JS::RootedValue jsret(cx); + if (argc == 2 && args.get(1).isString()) { + JS::RootedString globalName(cx, args.get(1).toString()); + JSStringWrapper name(globalName); + + JS::RootedObject debugObj(cx, engine->getDebugGlobal()); + if (debugObj) { + res = engine->requireScript(path.get(), debugObj, cx, &jsret); + } else { + JS_ReportErrorUTF8(cx, "Invalid global object: %s", name.get()); + args.rval().setUndefined(); + return false; + } + } else { + JS::RootedObject glob(cx, JS::CurrentGlobalOrNull(cx)); + res = engine->requireScript(path.get(), glob, cx, &jsret); + } + args.rval().set(jsret); + return res; + } + args.rval().setUndefined(); + return true; +} + +bool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + JS_GC(cx); + return true; +} + +bool ScriptingCore::dumpRoot(JSContext *cx, uint32_t argc, JS::Value *vp) +{ + // JS_DumpNamedRoots is only available on DEBUG versions of SpiderMonkey. + // Mac and Simulator versions were compiled with DEBUG. +#if COCOS2D_DEBUG +// JSContext *_cx = ScriptingCore::getInstance()->getGlobalContext(); +// JSRuntime *rt = JS_GetRuntime(_cx); +// JS_DumpNamedRoots(rt, dumpNamedRoot, NULL); +// JS_DumpHeap(rt, stdout, NULL, JSTRACE_OBJECT, NULL, 2, NULL); +#endif + return true; +} + +void ScriptingCore::pauseSchedulesAndActions(js_proxy_t* p) +{ + JS::RootedObject obj(_cx, p->obj.get()); + auto arr = JSScheduleWrapper::getTargetForJSObject(_cx, obj); + if (! arr) return; + + Node* node = (Node*)p->ptr; + for(ssize_t i = 0; i < arr->size(); ++i) { + if (arr->at(i)) { + node->getScheduler()->pauseTarget(arr->at(i)); + } + } +} + + +void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) +{ + JS::RootedObject obj(_cx, p->obj.get()); + auto arr = JSScheduleWrapper::getTargetForJSObject(_cx, obj); + if (!arr) return; + + Node* node = (Node*)p->ptr; + for(ssize_t i = 0; i < arr->size(); ++i) { + if (!arr->at(i)) continue; + node->getScheduler()->resumeTarget(arr->at(i)); + } +} + +void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) +{ + JS::RootedObject obj(_cx, p->obj.get()); + auto targetArray = JSScheduleWrapper::getTargetForJSObject(_cx, obj); + if (targetArray) + { + Node* node = (Node*)p->ptr; + auto scheduler = node->getScheduler(); + for (auto&& target : *targetArray) + { + scheduler->unscheduleAllForTarget(target); + } + + JSScheduleWrapper::removeAllTargetsForJSObject(_cx, obj); + } +} + +bool ScriptingCore::isFunctionOverridedInJS(JS::HandleObject obj, const std::string& name, JSNative native) +{ + JS::RootedObject jsobj(_cx, obj); + JS::RootedValue value(_cx); + bool ok = JS_GetProperty(_cx, jsobj, name.c_str(), &value); + if (ok && !value.isNullOrUndefined() && !JS_IsNativeFunction(value.toObjectOrNull(), native)) + { + return true; + } + + return false; +} + +int ScriptingCore::handleActionEvent(void* data) +{ + if (NULL == data) + return 0; + + ActionObjectScriptData* actionObjectScriptData = static_cast(data); + if (NULL == actionObjectScriptData->nativeObject || NULL == actionObjectScriptData->eventType) + return 0; + + Action* actionObject = static_cast(actionObjectScriptData->nativeObject); + int eventType = *((int*)(actionObjectScriptData->eventType)); + + js_proxy_t * p = jsb_get_native_proxy(actionObject); + if (!p) return 0; + + int ret = 0; + JS::RootedValue retval(_cx); + + if (eventType == kActionUpdate) + { + JS::RootedObject jstarget(_cx, p->obj); + if (isFunctionOverridedInJS(jstarget, "update", js_cocos2dx_Action_update)) + { + JS::RootedValue dataVal(_cx, JS::DoubleValue(*((float *)actionObjectScriptData->param))); + JS::HandleValueArray args(dataVal); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + ret = executeFunctionWithOwner(objVal, "update", args, &retval); + } + } + return ret; +} + +int ScriptingCore::handleNodeEvent(void* data) +{ + if (NULL == data) + return 0; + + BasicScriptData* basicScriptData = static_cast(data); + if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) + return 0; + + Node* node = static_cast(basicScriptData->nativeObject); + int action = *((int*)(basicScriptData->value)); + + js_proxy_t * p = jsb_get_native_proxy(node); + if (!p) return 0; + + int ret = 0; + JS::RootedValue retval(_cx); + JS::RootedValue dataVal(_cx, JS::Int32Value(1)); + JS::HandleValueArray args(dataVal); + + JS::RootedObject jstarget(_cx, p->obj); + JS::RootedValue targetVal(_cx, JS::ObjectOrNullValue(p->obj)); + if (action == kNodeOnEnter) + { + if (isFunctionOverridedInJS(jstarget, "onEnter", js_cocos2dx_Node_onEnter)) + { + ret = executeFunctionWithOwner(targetVal, "onEnter", args, &retval); + } + resumeSchedulesAndActions(p); + } + else if (action == kNodeOnExit) + { + if (isFunctionOverridedInJS(jstarget, "onExit", js_cocos2dx_Node_onExit)) + { + ret = executeFunctionWithOwner(targetVal, "onExit", args, &retval); + } + pauseSchedulesAndActions(p); + } + else if (action == kNodeOnEnterTransitionDidFinish) + { + if (isFunctionOverridedInJS(jstarget, "onEnterTransitionDidFinish", js_cocos2dx_Node_onEnterTransitionDidFinish)) + { + ret = executeFunctionWithOwner(targetVal, "onEnterTransitionDidFinish", args, &retval); + } + } + else if (action == kNodeOnExitTransitionDidStart) + { + if (isFunctionOverridedInJS(jstarget, "onExitTransitionDidStart", js_cocos2dx_Node_onExitTransitionDidStart)) + { + ret = executeFunctionWithOwner(targetVal, "onExitTransitionDidStart", args, &retval); + } + } + else if (action == kNodeOnCleanup) { + cleanupSchedulesAndActions(p); + + if (isFunctionOverridedInJS(jstarget, "cleanup", js_cocos2dx_Node_cleanup)) + { + ret = executeFunctionWithOwner(targetVal, "cleanup", args, &retval); + } + } + + return ret; +} + +int ScriptingCore::handleComponentEvent(void* data) +{ + if (NULL == data) + return 0; + + BasicScriptData* basicScriptData = static_cast(data); + if (NULL == basicScriptData->nativeObject || NULL == basicScriptData->value) + return 0; + + Component* node = static_cast(basicScriptData->nativeObject); + int action = *((int*)(basicScriptData->value)); + + js_proxy_t * p = jsb_get_native_proxy(node); + if (!p) return 0; + + int ret = 0; + JS::RootedValue retval(_cx); + JS::RootedValue dataVal(_cx, JS::Int32Value(1)); + JS::HandleValueArray args(dataVal); + JS::RootedValue nodeValue(_cx, JS::ObjectOrNullValue(p->obj)); + + if (action == kComponentOnAdd) + { + ret = executeFunctionWithOwner(nodeValue, "onAdd", args, &retval); + } + else if (action == kComponentOnRemove) + { + ret = executeFunctionWithOwner(nodeValue, "onRemove", args, &retval); + } + else if (action == kComponentOnEnter) + { + ret = executeFunctionWithOwner(nodeValue, "onEnter", args, &retval); + resumeSchedulesAndActions(p); + } + else if (action == kComponentOnExit) + { + ret = executeFunctionWithOwner(nodeValue, "onExit", args, &retval); + pauseSchedulesAndActions(p); + } + else if (action == kComponentOnUpdate) + { + ret = executeFunctionWithOwner(nodeValue, "update", args, &retval); + } + + return ret; +} + +bool ScriptingCore::handleTouchesEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, const std::vector& touches, cocos2d::Event* event) +{ + JS::RootedValue ret(_cx); + return handleTouchesEvent(nativeObj, eventCode, touches, event, &ret); +} + +bool ScriptingCore::handleTouchesEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, const std::vector& touches, cocos2d::Event* event, JS::MutableHandleValue jsvalRet) +{ + bool ret = false; + std::string funcName = getTouchesFuncName(eventCode); + JS::RootedObject jsretArr(_cx, JS_NewArrayObject(_cx, 0)); + int count = 0; + + for (const auto& touch : touches) + { + JS::RootedObject touchObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_Touch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, touch, jsb_cocos2d_Touch_class, proto, &touchObj, "Touch"); + JS::RootedValue jsret(_cx, JS::ObjectOrNullValue(touchObj)); + if (!JS_SetElement(_cx, jsretArr, count, jsret)) + { + break; + } + ++count; + } + + js_proxy_t* p = jsb_get_native_proxy(nativeObj); + if (p) + { + JS::RootedObject eventObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_EventTouch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, event, jsb_cocos2d_EventTouch_class, proto, &eventObj, "EventTouch"); + JS::RootedValue eventVal(_cx, JS::ObjectOrNullValue(eventObj)); + + JS::AutoValueVector valArr(_cx); + valArr.append(JS::ObjectOrNullValue(jsretArr)); + valArr.append(eventVal); + JS::HandleValueArray args(valArr); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + + ret = executeFunctionWithOwner(objVal, funcName.c_str(), args, jsvalRet); + } + + return ret; +} + +bool ScriptingCore::handleTouchEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, cocos2d::Touch* touch, cocos2d::Event* event) +{ + JS::RootedValue ret(_cx); + return handleTouchEvent(nativeObj, eventCode, touch, event, &ret); +} + +bool ScriptingCore::handleTouchEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, cocos2d::Touch* touch, cocos2d::Event* event, JS::MutableHandleValue jsvalRet) +{ + std::string funcName = getTouchFuncName(eventCode); + bool ret = false; + + js_proxy_t * p = jsb_get_native_proxy(nativeObj); + if (p) + { + JS::RootedObject touchObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_Touch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, touch, jsb_cocos2d_Touch_class, proto, &touchObj, "Touch"); + + JS::RootedObject eventObj(_cx); + proto.set(jsb_cocos2d_EventTouch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, event, jsb_cocos2d_EventTouch_class, proto, &eventObj, "EventTouch"); + JS::RootedValue eventVal(_cx, JS::ObjectOrNullValue(eventObj)); + + JS::AutoValueVector valArr(_cx); + valArr.append(JS::ObjectOrNullValue(touchObj)); + valArr.append(eventVal); + JS::HandleValueArray args(valArr); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + + ret = executeFunctionWithOwner(objVal, funcName.c_str(), args, jsvalRet); + } + + return ret; +} + +bool ScriptingCore::handleMouseEvent(void* nativeObj, cocos2d::EventMouse::MouseEventType eventType, cocos2d::Event* event) +{ + JS::RootedValue ret(_cx); + return handleMouseEvent(nativeObj, eventType, event, &ret); +} + +bool ScriptingCore::handleMouseEvent(void* nativeObj, cocos2d::EventMouse::MouseEventType eventType, cocos2d::Event* event, JS::MutableHandleValue jsvalRet) +{ + std::string funcName = getMouseFuncName(eventType); + bool ret = false; + + js_proxy_t * p = jsb_get_native_proxy(nativeObj); + if (p) + { + JS::RootedObject eventObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_EventMouse_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, event, jsb_cocos2d_EventMouse_class, proto, &eventObj); + JS::RootedValue eventVal(_cx, JS::ObjectOrNullValue(eventObj)); + + JS::HandleValueArray args(eventVal); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + ret = executeFunctionWithOwner(objVal, funcName.c_str(), args, jsvalRet); + } + else CCLOG("ScriptingCore::handleMouseEvent native proxy NOT found"); + + return ret; +} + +bool ScriptingCore::executeFunctionWithObjectData(void* nativeObj, const char *name, JS::HandleValue data) +{ + js_proxy_t * p = jsb_get_native_proxy(nativeObj); + if (!p) return false; + + JS::RootedValue retval(_cx); + JS::RootedValue dataVal(_cx, data); + JS::HandleValueArray args(dataVal); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + + executeFunctionWithOwner(objVal, name, args, &retval); + if (retval.isNull()) { + return false; + } + else if (retval.isBoolean()) { + return retval.toBoolean(); + } + return false; +} + +bool ScriptingCore::executeFunctionWithOwner(JS::HandleValue owner, const char *name, const JS::HandleValueArray& args) +{ + JS::RootedValue ret(_cx); + return executeFunctionWithOwner(owner, name, args, &ret); +} + +bool ScriptingCore::executeFunctionWithOwner(JS::HandleValue owner, const char *name, const JS::HandleValueArray& args, JS::MutableHandleValue retVal) +{ + bool bRet = false; + bool hasFunc; + JSContext* cx = this->_cx; + JS::RootedValue funcVal(cx); + JS::RootedValue ownerval(cx, owner); + JS::RootedObject obj(cx); + if (ownerval.isObject()) + { + obj = ownerval.toObjectOrNull(); + do + { + if (JS_HasProperty(cx, obj, name, &hasFunc) && hasFunc) { + if (!JS_GetProperty(cx, obj, name, &funcVal)) { + break; + } + if (funcVal.isNullOrUndefined()) { + break; + } + + bRet = JS_CallFunctionValue(cx, obj, funcVal, args, retVal); + if (JS_IsExceptionPending(cx)) { + handlePendingException(cx); + } + } + } while(0); + } + return bRet; +} + +std::chrono::steady_clock::time_point ScriptingCore::getEngineStartTime() const +{ + return _engineStartTime; +} + + +bool ScriptingCore::handleKeyboardEvent(void* nativeObj, cocos2d::EventKeyboard::KeyCode keyCode, bool isPressed, cocos2d::Event* event) +{ + js_proxy_t * p = jsb_get_native_proxy(nativeObj); + if (nullptr == p) + return false; + + JS::RootedObject listener(_cx, p->obj); + + bool ret = false; + + JS::AutoValueVector valArr(_cx); + valArr.append( JS::Int32Value((int32_t)keyCode)); + JS::RootedObject eventObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_EventKeyboard_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, event, jsb_cocos2d_EventKeyboard_class, proto, &eventObj, "EventKeyboard"); + valArr.append( JS::ObjectOrNullValue(eventObj)); + JS::HandleValueArray args(valArr); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + + if (isPressed) + { + ret = executeFunctionWithOwner(objVal, "_onKeyPressed", args); + } + else + { + ret = executeFunctionWithOwner(objVal, "_onKeyReleased", args); + } + return ret; +} + +bool ScriptingCore::handleFocusEvent(void* nativeObj, cocos2d::ui::Widget* widgetLoseFocus, cocos2d::ui::Widget* widgetGetFocus) +{ + js_proxy_t * p = jsb_get_native_proxy(nativeObj); + if (nullptr == p) + return false; + + JS::RootedObject proto(_cx, jsb_cocos2d_ui_Widget_prototype->get()); + + JS::AutoValueVector valArr(_cx); + JS::RootedObject widgetObj(_cx); + jsb_get_or_create_weak_jsobject(_cx, widgetLoseFocus, jsb_cocos2d_ui_Widget_class, proto, &widgetObj, "cocos2d::ui::Widget"); + valArr.append(JS::ObjectOrNullValue(widgetObj)); + jsb_get_or_create_weak_jsobject(_cx, widgetGetFocus, jsb_cocos2d_ui_Widget_class, proto, &widgetObj, "cocos2d::ui::Widget"); + valArr.append(JS::ObjectOrNullValue(widgetObj)); + JS::HandleValueArray args(valArr); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(p->obj)); + + bool ret = executeFunctionWithOwner(objVal, "onFocusChanged", args); + + return ret; +} + + +int ScriptingCore::executeCustomTouchesEvent(EventTouch::EventCode eventType, + const std::vector& touches, JS::HandleObject obj) +{ + std::string funcName = getTouchesFuncName(eventType); + + JS::RootedObject jsretArr(_cx, JS_NewArrayObject(_cx, 0)); + JS::RootedValue jsval(_cx); + int count = 0; + for (auto& touch : touches) + { + JS::RootedObject touchObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_Touch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, touch, jsb_cocos2d_Touch_class, proto, &touchObj, "Touch"); + jsval = JS::ObjectOrNullValue(touchObj); + if (!JS_SetElement(this->_cx, jsretArr, count, jsval)) { + break; + } + ++count; + } + JS::RootedValue retArrVal(_cx, JS::ObjectOrNullValue(jsretArr)); + JS::HandleValueArray args(retArrVal); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(obj)); + + executeFunctionWithOwner(objVal, funcName.c_str(), args); + return 1; +} + + +int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, Touch *touch, JS::HandleObject obj) +{ + JS::RootedValue retval(_cx); + std::string funcName = getTouchFuncName(eventType); + JS::RootedObject touchObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_Touch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, touch, jsb_cocos2d_Touch_class, proto, &touchObj, "Touch"); + JS::RootedValue arg(_cx, JS::ObjectOrNullValue(touchObj)); + JS::HandleValueArray args(arg); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(obj)); + + executeFunctionWithOwner(objVal, funcName.c_str(), args, &retval); + return 1; +} + +int ScriptingCore::executeCustomTouchEvent(EventTouch::EventCode eventType, + Touch *touch, JS::HandleObject obj, + JS::MutableHandleValue retval) +{ + std::string funcName = getTouchFuncName(eventType); + JS::RootedObject touchObj(_cx); + JS::RootedObject proto(_cx, jsb_cocos2d_Touch_prototype->get()); + jsb_get_or_create_weak_jsobject(_cx, touch, jsb_cocos2d_Touch_class, proto, &touchObj, "Touch"); + JS::RootedValue arg(_cx, JS::ObjectOrNullValue(touchObj)); + JS::HandleValueArray args(arg); + JS::RootedValue objVal(_cx, JS::ObjectOrNullValue(obj)); + + executeFunctionWithOwner(objVal, funcName.c_str(), args, retval); + return 1; } int ScriptingCore::executeGlobalFunction(const char* functionName) -{ - assert(false); - return 0; +{ + std::string evalStr = functionName; + JS::RootedValue globalVal(_cx, JS::ObjectOrNullValue(_global->get())); + return executeFunctionWithOwner(globalVal, functionName, JS::HandleValueArray::empty()); } -int ScriptingCore::sendEvent(cocos2d::ScriptEvent* evt) +int ScriptingCore::sendEvent(ScriptEvent* evt) { if (NULL == evt) return 0; - // special type, can't use this code after JSAutoCompartment if (evt->type == kRestartGame) { restartVM(); @@ -112,34 +1831,34 @@ int ScriptingCore::sendEvent(cocos2d::ScriptEvent* evt) switch (evt->type) { case kNodeEvent: - { - return handleNodeEvent(evt->data); - } + { + return handleNodeEvent(evt->data); + } break; case kScriptActionEvent: - { - return handleActionEvent(evt->data); - } + { + return handleActionEvent(evt->data); + } + break; + case kMenuClickedEvent: + break; + case kTouchEvent: + { + TouchScriptData* data = (TouchScriptData*)evt->data; + return handleTouchEvent(data->nativeObject, data->actionType, data->touch, data->event); + } + break; + case kTouchesEvent: + { + TouchesScriptData* data = (TouchesScriptData*)evt->data; + return handleTouchesEvent(data->nativeObject, data->actionType, data->touches, data->event); + } + break; + case kComponentEvent: + { + return handleComponentEvent(evt->data); + } break; -// case kMenuClickedEvent: -// break; -// case kTouchEvent: -// { -// TouchScriptData* data = (TouchScriptData*)evt->data; -// return handleTouchEvent(data->nativeObject, data->actionType, data->touch, data->event); -// } -// break; -// case kTouchesEvent: -// { -// TouchesScriptData* data = (TouchesScriptData*)evt->data; -// return handleTouchesEvent(data->nativeObject, data->actionType, data->touches, data->event); -// } -// break; -// case kComponentEvent: -// { -// return handleComponentEvent(evt->data); -// } -// break; default: CCASSERT(false, "Invalid script event."); break; @@ -148,90 +1867,730 @@ int ScriptingCore::sendEvent(cocos2d::ScriptEvent* evt) return 0; } -bool ScriptingCore::parseConfig(ConfigType type, const std::string& str) +bool ScriptingCore::parseConfig(ConfigType type, const std::string &str) { - assert(false); - return false; + JS::AutoValueVector valArr(_cx); + valArr.append(JS::Int32Value(static_cast(type))); + JS::RootedValue argv(_cx); + std_string_to_jsval(_cx, str, &argv); + valArr.append(argv); + JS::HandleValueArray args(valArr); + JS::RootedValue globalVal(_cx, JS::ObjectOrNullValue(_global->get())); + return (true == executeFunctionWithOwner(globalVal, "__onParseConfig", args)); } -// private methods - -int ScriptingCore::handleActionEvent(void* data) +bool ScriptingCore::isObjectValid(JSContext *cx, uint32_t argc, JS::Value *vp) { - if (nullptr == data) - return 0; - - ActionObjectScriptData* actionObjectScriptData = static_cast(data); - if (nullptr == actionObjectScriptData->nativeObject || nullptr == actionObjectScriptData->eventType) - return 0; - - Action* actionObject = static_cast(actionObjectScriptData->nativeObject); - int eventType = *((int*)(actionObjectScriptData->eventType)); - - auto iter = se::NativePtrToObjectMap::find(actionObject); - if (iter == se::NativePtrToObjectMap::end()) - return 0; - - se::ScriptEngine::getInstance()->clearException(); - se::AutoHandleScope hs; - se::Value seActionVal; - seActionVal.setObject(iter->second, true); - - int ret = 0; - - if (eventType == kActionUpdate) - { - se::Value updateVal; - if (seActionVal.toObject()->getProperty("update", &updateVal) && updateVal.isObject() && updateVal.toObject()->isFunction()) - { - se::ValueArray args; - args.push_back(se::Value(*((float *)actionObjectScriptData->param))); - updateVal.toObject()->call(args, seActionVal.toObject()); + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + args.rval().set(JS::FalseHandleValue); + if (argc >= 1) { + if (args.get(0).isObject()) { + JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(cx, tmpObj); + if (proxy && proxy->ptr) { + args.rval().set(JS::TrueHandleValue); + } } } - - return ret; + return true; } -int ScriptingCore::handleNodeEvent(void* data) +void ScriptingCore::rootObject(Ref* ref) { - if (nullptr == data) - return 0; + auto proxy = jsb_get_native_proxy(ref); + if (proxy) { +// JSContext *cx = getGlobalContext(); +// JS::AddNamedObjectRoot(cx, &proxy->obj, typeid(*ref).name()); + ref->_rooted = true; + } + else CCLOG("rootObject: BUG. native not found: %p (%s)", ref, typeid(*ref).name()); +} - BasicScriptData* basicScriptData = static_cast(data); - if (nullptr == basicScriptData->nativeObject || nullptr == basicScriptData->value) - return 0; +void ScriptingCore::unrootObject(Ref* ref) +{ + auto proxy = jsb_get_native_proxy(ref); + if (proxy) { +// JSContext *cx = getGlobalContext(); +// JS::RemoveObjectRoot(cx, &proxy->obj); + ref->_rooted = false; + } + else CCLOG("unrootObject: BUG. native not found: %p (%s)", ref, typeid(*ref).name()); +} - void* node = basicScriptData->nativeObject; - int action = *((int*)(basicScriptData->value)); +void ScriptingCore::removeObjectProxy(void* obj) +{ + auto proxy = jsb_get_native_proxy(obj); + if (proxy) + { +#if ! CC_ENABLE_GC_FOR_NATIVE_OBJECTS + JS::RemoveObjectRoot(_cx, &proxy->obj); +#endif +#if COCOS2D_DEBUG > 1 + CCLOG("------RELEASED------ Cpp: %p - Proxy: %p", obj, proxy); +#endif // COCOS2D_DEBUG + + if (!getFinalizing()) + { + JS::RootedObject jsObj(_cx, proxy->obj); + JS::RootedValue hook(_cx); + JS_GetProperty(_cx, jsObj, "__hook", &hook); + + if (hook.isObject()) + { + JSObject *hookObj = hook.toObjectOrNull(); + JS_SetPrivate(hookObj, nullptr); + } + } + // remove the proxy here, since this was a "stack" object, not heap + // when js_finalize is called, it will fail, but + // the correct solution is to have a new finalize for event + jsb_remove_proxy(proxy); + } +} - bool ret = false; - if (action == kNodeOnEnter) +void ScriptingCore::garbageCollect() +{ +#if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 + JS_MaybeGC(_cx); + JS_MaybeGC(_cx); +#endif +} + +#pragma mark - Debug + +void SimpleRunLoop::update(float dt) +{ + std::string message; + size_t messageCount = 0; + while (true) { - ret = se::ScriptEngine::getInstance()->_onReceiveNodeEvent(node, se::ScriptEngine::NodeEventType::ENTER); + g_qMutex.lock(); + messageCount = g_queue.size(); + if (messageCount > 0) + { + auto first = g_queue.begin(); + message = *first; + g_queue.erase(first); + --messageCount; + } + g_qMutex.unlock(); + + if (!message.empty()) + ScriptingCore::getInstance()->debugProcessInput(message); + + if (messageCount == 0) + break; } - else if (action == kNodeOnExit) +} + +void ScriptingCore::debugProcessInput(const std::string& str) +{ + JS::RootedObject debugGlobal(_cx, _debugGlobal->get()); + JSCompartment *globalCpt = JS_EnterCompartment(_cx, debugGlobal); + + JS::RootedValue globalVal(_cx, JS::ObjectOrNullValue(debugGlobal)); + JS::RootedValue argv(_cx); + std_string_to_jsval(_cx, str, &argv); + JS::HandleValueArray args(argv); + JS::RootedValue outval(_cx); + + executeFunctionWithOwner(globalVal, "processInput", args, &outval); + + JS_LeaveCompartment(_cx, globalCpt); +} + +static bool NS_ProcessNextEvent() +{ + std::string message; + size_t messageCount = 0; + while (true) { - ret = se::ScriptEngine::getInstance()->_onReceiveNodeEvent(node, se::ScriptEngine::NodeEventType::EXIT); + g_qMutex.lock(); + messageCount = g_queue.size(); + if (messageCount > 0) + { + auto first = g_queue.begin(); + message = *first; + g_queue.erase(first); + --messageCount; + } + g_qMutex.unlock(); + + if (!message.empty()) + ScriptingCore::getInstance()->debugProcessInput(message); + + if (messageCount == 0) + break; } - else if (action == kNodeOnEnterTransitionDidFinish) - { - ret = se::ScriptEngine::getInstance()->_onReceiveNodeEvent(node, se::ScriptEngine::NodeEventType::ENTER_TRANSITION_DID_FINISH); +// std::this_thread::yield(); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + + return true; +} + +bool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, JS::Value* vp) +{ + enum { + NS_OK = 0, + NS_ERROR_UNEXPECTED + }; + +#define NS_SUCCEEDED(v) ((v) == NS_OK) + + int rv = NS_OK; + + uint32_t nestLevel = ++s_nestedLoopLevel; + + while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) { + drainJobQueue(); + if (!NS_ProcessNextEvent()) + rv = NS_ERROR_UNEXPECTED; } - else if (action == kNodeOnExitTransitionDidStart) - { - ret = se::ScriptEngine::getInstance()->_onReceiveNodeEvent(node, se::ScriptEngine::NodeEventType::EXIT_TRANSITION_DID_START); + + CCASSERT(s_nestedLoopLevel <= nestLevel, + "nested event didn't unwind properly"); + + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + args.rval().set(JS::Int32Value(s_nestedLoopLevel)); + return true; +} + +bool JSBDebug_exitNestedEventLoop(JSContext* cx, unsigned argc, JS::Value* vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + if (s_nestedLoopLevel > 0) { + --s_nestedLoopLevel; + } else { + args.rval().set(JS::Int32Value(0)); + return true; } - else if (action == kNodeOnCleanup) + args.rval().setUndefined(); + return true; +} + +bool JSBDebug_getEventLoopNestLevel(JSContext* cx, unsigned argc, JS::Value* vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + args.rval().set(JS::Int32Value(s_nestedLoopLevel)); + return true; +} + +//#pragma mark - Debugger + +static void _clientSocketWriteAndClearString(std::string& s) +{ + ::send(clientSocket, s.c_str(), s.length(), 0); + s.clear(); +} + +static void processInput(const std::string& data) { + std::lock_guard lk(g_qMutex); + g_queue.push_back(data); +} + +static void clearBuffers() { + std::lock_guard lk(g_rwMutex); + // only process input if there's something and we're not locked + if (!inData.empty()) { + processInput(inData); + inData.clear(); + } + if (!outData.empty()) { + _clientSocketWriteAndClearString(outData); + } +} + +static void serverEntryPoint(unsigned int port) +{ + // start a server, accept the connection and keep reading data from it + struct addrinfo hints, *result = nullptr, *rp = nullptr; + int s = 0; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; // TCP stream sockets + hints.ai_flags = AI_PASSIVE; // fill in my IP for me + + std::stringstream portstr; + portstr << port; + + int err = 0; + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + WSADATA wsaData; + err = WSAStartup(MAKEWORD(2, 2),&wsaData); +#endif + + if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) { + LOGD("getaddrinfo error : %s\n", gai_strerror(err)); + } + + for (rp = result; rp != NULL; rp = rp->ai_next) { + if ((s = socket(rp->ai_family, rp->ai_socktype, 0)) < 0) { + continue; + } + int optval = 1; + if ((setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval))) < 0) { + cc_closesocket(s); + TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_REUSEADDR"); + return; + } + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + if ((setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval))) < 0) { + close(s); + TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_NOSIGPIPE"); + return; + } +#endif //(CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + + if ((::bind(s, rp->ai_addr, rp->ai_addrlen)) == 0) { + break; + } + cc_closesocket(s); + s = -1; + } + if (s < 0 || rp == NULL) { + TRACE_DEBUGGER_SERVER("debug server : error creating/binding socket"); + return; + } + + freeaddrinfo(result); + + listen(s, 1); + +#define MAX_RECEIVED_SIZE 1024 +#define BUF_SIZE MAX_RECEIVED_SIZE + 1 + + char buf[BUF_SIZE] = {0}; + int readBytes = 0; + while (true) { + clientSocket = accept(s, NULL, NULL); + + if (clientSocket < 0) + { + TRACE_DEBUGGER_SERVER("debug server : error on accept"); + return; + } + else + { + // read/write data + TRACE_DEBUGGER_SERVER("debug server : client connected"); + + inData = "connected"; + // process any input, send any output + clearBuffers(); + + while ((readBytes = (int)::recv(clientSocket, buf, MAX_RECEIVED_SIZE, 0)) > 0) + { + buf[readBytes] = '\0'; + // TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf); + + // no other thread is using this + inData.append(buf); + // process any input, send any output + clearBuffers(); + } // while(read) + + cc_closesocket(clientSocket); + } + } // while(true) + +#undef BUF_SIZE +#undef MAX_RECEIVED_SIZE +} + +bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, JS::Value* vp) +{ + if (argc == 1) { + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedString jsstr(cx, args.get(0).toString()); + JSStringWrapper strWrapper(jsstr); + // this is safe because we're already inside a lock (from clearBuffers) + outData.append(strWrapper.get()); + _clientSocketWriteAndClearString(outData); + } + return true; +} + +void ScriptingCore::enableDebugger(unsigned int port) +{ + if (!_debugGlobal) { - ret = se::ScriptEngine::getInstance()->_onReceiveNodeEvent(node, se::ScriptEngine::NodeEventType::CLEANUP); + JS::CompartmentOptions options; + options.behaviors().setVersion(JSVERSION_LATEST); + options.creationOptions().setSharedMemoryAndAtomicsEnabled(true); + + JS::RootedObject debugGlobal(_cx, JS_NewGlobalObject(_cx, &global_class, nullptr, JS::DontFireOnNewGlobalHook, options)); + _debugGlobal = new (std::nothrow) JS::PersistentRootedObject(_cx, debugGlobal); + + JSCompartment *globalCpt = JS_EnterCompartment(_cx, debugGlobal); + JS_InitStandardClasses(_cx, debugGlobal); + registerDefaultClasses(_cx, debugGlobal); + JS_FireOnNewGlobalObject(_cx, debugGlobal); + JS_DefineDebuggerObject(_cx, debugGlobal); + + // these are used in the debug program + JS_DefineFunction(_cx, debugGlobal, "log", ScriptingCore::log, 0, JSPROP_PERMANENT); +// JS_DefineFunction(_cx, debugGlobal, "require", ScriptingCore::executeScript, 2, JSPROP_PERMANENT); + JS_DefineFunction(_cx, debugGlobal, "_bufferWrite", JSBDebug_BufferWrite, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(_cx, debugGlobal, "_enterNestedEventLoop", JSBDebug_enterNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(_cx, debugGlobal, "_exitNestedEventLoop", JSBDebug_exitNestedEventLoop, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(_cx, debugGlobal, "_getEventLoopNestLevel", JSBDebug_getEventLoopNestLevel, 0, JSPROP_READONLY | JSPROP_PERMANENT); + + JS::RootedObject globalObj(_cx, _global->get()); + JS_WrapObject(_cx, &globalObj); + + runScript("script/jsb_debugger.js", debugGlobal); + + // prepare the debugger + JS::RootedValue owner(_cx, JS::ObjectOrNullValue(debugGlobal)); + JS::RootedValue argv(_cx, JS::ObjectOrNullValue(globalObj)); + JS::HandleValueArray args(argv); + JS::RootedValue outval(_cx); + executeFunctionWithOwner(owner, "_prepareDebugger", args, &outval); + + // start bg thread + auto t = std::thread(&serverEntryPoint, port); + t.detach(); + + Scheduler* scheduler = Director::getInstance()->getScheduler(); + scheduler->scheduleUpdate(this->_runLoop, 0, false); + + JS_LeaveCompartment(_cx, globalCpt); + } +} + +void handlePendingException(JSContext *cx) +{ + JS::RootedValue err(cx); + if (JS_GetPendingException(cx, &err) && err.isObject()) + { + JS_ClearPendingException(cx); + + JS::RootedObject errObj(cx, err.toObjectOrNull()); + JSErrorReport *report = JS_ErrorFromException(cx, errObj); + + ScriptingCore::reportError(cx, report, err); + } +} + +void make_class_extend(JSContext *cx, JS::HandleObject proto) +{ + JS::RootedValue classVal(cx); + if (JS_GetProperty(cx, proto, "constructor", &classVal) && !classVal.isNullOrUndefined()) + { + JS::RootedObject extendObj(cx); + get_or_create_js_obj("cc.Class.extend", &extendObj); + JS::RootedValue extendVal(cx, JS::ObjectOrNullValue(extendObj)); + if (!extendVal.isNullOrUndefined()) { + JS::RootedObject classObj(cx, classVal.toObjectOrNull()); + JS_SetProperty(cx, classObj, "extend", extendVal); + } + } +} + +js_proxy_t* jsb_new_proxy(JSContext *cx, void* nativeObj, JS::HandleObject jsObj) +{ + js_proxy_t* proxy = nullptr; + JS::RootedValue objVal(cx, JS::ObjectOrNullValue(jsObj)); + + if (nativeObj && objVal.isObject()) + { + JS::RootedValue hook(cx); + bool hasHook = JS_GetProperty(cx, jsObj, "__hook", &hook); + + if (!hasHook || !hook.isObject()) + { + CCLOG("BUG: JS object(%p) doesn't have __hook property, can't set private data.", jsObj.get()); + return nullptr; + } + JS::RootedObject hookObj(cx, hook.toObjectOrNull()); + + // native to JS index + proxy = new js_proxy_t(); + CC_ASSERT(proxy && "not enough memory"); + CC_ASSERT(_native_js_global_map->find(nativeObj) == _native_js_global_map->end() && "Native Key should not be present"); + + proxy->ptr = nativeObj; + proxy->obj = jsObj.get(); + + // One Proxy in two entries + (*_native_js_global_map)[nativeObj] = proxy; + JS_SetPrivate(hookObj, proxy); + } + else CCLOG("jsb_new_proxy: Invalid keys"); + + return proxy; +} + +js_proxy_t* jsb_bind_proxy(JSContext *cx, void* nativeObj, JS::HandleObject jsObj) +{ + js_proxy_t* proxy = nullptr; + JS::RootedValue objVal(cx, JS::ObjectOrNullValue(jsObj)); + + if (nativeObj && objVal.isObject()) + { + // native to JS index + proxy = new js_proxy_t(); + CC_ASSERT(proxy && "not enough memory"); + CC_ASSERT(_native_js_global_map->find(nativeObj) == _native_js_global_map->end() && "Native Key should not be present"); + + proxy->ptr = nativeObj; + proxy->obj = jsObj; + (*_native_js_global_map)[nativeObj] = proxy; + } + else CCLOG("jsb_bind_proxy: Invalid keys"); + return proxy; +} + +js_proxy_t* jsb_get_native_proxy(void* nativeObj) +{ + auto search = _native_js_global_map->find(nativeObj); + if(search != _native_js_global_map->end()) + return search->second; + return nullptr; +} + +js_proxy_t* jsb_get_js_proxy(JSContext *cx, JS::HandleObject jsObj) +{ + JS::RootedValue hook(cx); + JS_GetProperty(cx, jsObj, "__hook", &hook); + + if (hook.isObject()) + { + JSObject *hookObj = hook.toObjectOrNull(); + const JSClass *jsClass = JS_GetClass(hookObj); + if (jsClass == jsb_RefFinalizeHook_class || jsClass == jsb_ObjFinalizeHook_class) + { + js_proxy_t *proxy = (js_proxy_t *)JS_GetPrivate(hookObj); + return proxy; + } } - return ret ? 1 : 0; + return nullptr; } -void ScriptingCore::restartVM() +bool jsb_remove_proxy(js_proxy_t* proxy) { - se::ScriptEngine::getInstance()->cleanup(); - Application::getInstance()->applicationDidFinishLaunching(); + bool ok = jsb_unbind_proxy(proxy); + if (ok) + { + CC_SAFE_DELETE(proxy); + } + return ok; +} + +bool jsb_unbind_proxy(js_proxy_t* proxy) +{ + void* nativeKey = proxy->ptr; +#if COCOS2D_DEBUG > 1 + CC_ASSERT(nativeKey && "Invalid nativeKey"); +#else + if (!nativeKey) + return false; +#endif // COCOS2D_DEBUG + + // delete entry in native proxy map + auto it_nat = _native_js_global_map->find(nativeKey); + if (it_nat != _native_js_global_map->end()) + { + _native_js_global_map->erase(it_nat); + return true; + } + else + { +#if COCOS2D_DEBUG > 1 + CCLOG("------UNBINDING------ failed, requested proxy is not present, Cpp: %p - Proxy: %p", nativeKey, proxy); +#endif // COCOS2D_DEBUG + return false; + } +} + +// +// Ref functions +// + +// ref_create +bool jsb_ref_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + jsObj.set(JS_NewObjectWithGivenProto(cx, jsclass, proto)); + jsb_ref_init(cx, jsObj, ref, debug); + jsb_new_proxy(cx, ref, jsObj); + return true; +} + +bool jsb_ref_autoreleased_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + jsObj.set(JS_NewObjectWithGivenProto(cx, jsclass, proto)); + jsb_ref_autoreleased_init(cx, jsObj, ref, debug); + jsb_new_proxy(cx, ref, jsObj); + return true; +} + +bool jsb_create_weak_jsobject(JSContext *cx, void *native, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + jsObj.set(JS_NewObjectWithGivenProto(cx, jsclass, proto)); + js_add_FinalizeHook(cx, jsObj, false); + auto proxy = jsb_new_proxy(cx, native, jsObj); + (void)proxy; + +#if ! CC_ENABLE_GC_FOR_NATIVE_OBJECTS +// JS::AddNamedObjectRoot(cx, &proxy->obj, debug); +#else +#if COCOS2D_DEBUG > 1 + if (debug != nullptr) + { + CCLOG("++++++WEAK_REF++++++ Cpp(%s): %p - Proxy: %p", debug, native, proxy); + } +#endif // COCOS2D_DEBUG +#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS + return true; +} + +// get_or_create +bool jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + auto proxy = jsb_get_native_proxy(ref); + if (proxy) + { + jsObj.set(proxy->obj); + return true; + } + + jsObj.set(JS_NewObjectWithGivenProto(cx, jsclass, proto)); + + JS::RootedObject obj(cx, jsObj); +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + ref->retain(); + js_add_FinalizeHook(cx, jsObj, true); + proxy = jsb_new_proxy(cx, ref, obj); +#if COCOS2D_DEBUG > 1 + if (debug != nullptr) + { + CCLOG("++++++RETAINED++++++ Cpp(%s): %p - Proxy: %p obj: %p", debug, ref, proxy, jsObj.get()); + } +#endif // COCOS2D_DEBUG +#else + // don't auto-release, don't retain. + JS::AddNamedObjectRoot(cx, &newproxy->obj, debug); + jsb_new_proxy(cx, ref, obj); +#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS + + return true; +} + +// get_or_create: Ref is already autoreleased (or created) +bool jsb_ref_autoreleased_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + auto proxy = jsb_get_native_proxy(ref); + if (proxy) + { + jsObj.set(proxy->obj); + return true; + } + // else + return jsb_ref_autoreleased_create_jsobject(cx, ref, jsclass, proto, jsObj, debug); +} + +// get_or_create: when native object isn't a ref object or when the native object life cycle don't need to be managed by js object +bool jsb_get_or_create_weak_jsobject(JSContext *cx, void *native, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug) +{ + auto proxy = jsb_get_native_proxy(native); + if (proxy) + { + jsObj.set(proxy->obj); + return true; + } + + // don't auto-release, don't retain. + jsObj.set(JS_NewObjectWithGivenProto(cx, jsclass, proto)); + +#if ! CC_ENABLE_GC_FOR_NATIVE_OBJECTS +// JS::AddNamedObjectRoot(cx, &proxy->obj, debug); + jsb_new_proxy(cx, native, jsObj); +#else + js_add_FinalizeHook(cx, jsObj, false); + proxy = jsb_new_proxy(cx, native, jsObj); +#if COCOS2D_DEBUG > 1 + if (debug != nullptr) + { + CCLOG("++++++WEAK_REF++++++ Cpp(%s): %p - Proxy: %p", debug, native, proxy); + } +#endif // COCOS2D_DEBUG +#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS + return true; +} + +// ref_init +void jsb_ref_init(JSContext* cx, JS::HandleObject obj, Ref* ref, const char* debug) +{ +// CCLOG("jsb_ref_init: JSObject address = %p. %s", obj->get(), debug); +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + (void)ref; + JS::RootedObject jsObj(cx, obj); + js_add_FinalizeHook(cx, jsObj, true); + // don't retain it, already retained +#if COCOS2D_DEBUG > 1 + CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, ref, jsObj.get()); +#endif // COCOS2D_DEBUG +#else + // autorelease it + ref->autorelease(); +// JS::AddNamedObjectRoot(cx, obj, debug); +#endif +} + +void jsb_ref_autoreleased_init(JSContext* cx, JS::HandleObject obj, Ref* ref, const char* debug) +{ + // CCLOG("jsb_ref_init: JSObject address = %p. %s", obj->get(), debug); +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + (void)cx; + (void)obj; + ref->retain(); + JS::RootedObject jsObj(cx, obj); + js_add_FinalizeHook(cx, jsObj, true); +#if COCOS2D_DEBUG > 1 + CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, ref, jsObj.get()); +#endif // COCOS2D_DEBUG +#else + // don't autorelease it, since it is already autoreleased +// JS::AddNamedObjectRoot(cx, obj, debug); +#endif +} + +// rebind +void jsb_ref_rebind(JSContext* cx, JS::HandleObject jsobj, js_proxy_t *proxy, cocos2d::Ref* oldRef, cocos2d::Ref* newRef, const char* debug) +{ +#if COCOS2D_DEBUG > 1 + CCLOG("------REBOUND------ Cpp(%s): %p - JS: %p", debug, oldRef, jsobj.get()); + CCLOG("++++++REBOUND++++++ Cpp(%s): %p - JS: %p", debug, newRef, jsobj.get()); +#endif // COCOS2D_DEBUG +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + // Release the old reference as it have been retained by jsobj previously, + // and the jsobj won't have any chance to release it in the future + oldRef->release(); +#else +// JS::RemoveObjectRoot(cx, &proxy->obj); +#endif + + jsb_remove_proxy(proxy); + // Rebind js obj with new action + jsb_new_proxy(cx, newRef, jsobj); + +#if !CC_ENABLE_GC_FOR_NATIVE_OBJECTS +// JS::AddNamedObjectRoot(cx, &newProxy->obj, debug); +#endif +} + +void jsb_non_ref_init(JSContext* cx, JS::HandleObject obj, void* native, const char* debug) +{ +// CCLOG("jsb_non_ref_init: JSObject address = %p. %s", obj->get(), debug); +#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS + JS::RootedObject jsObj(cx, obj); + js_add_FinalizeHook(cx, jsObj, false); + // don't retain it, already retained +#if COCOS2D_DEBUG > 1 + CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, native, jsObj.get()); +#endif // COCOS2D_DEBUG +#endif } diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h index 155ced31d8..76cf24f56d 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h @@ -1,5 +1,7 @@ /* - * Copyright (c) 2017 Chukong Technologies Inc. + * Created by Rolando Abarca on 3/14/12. + * Copyright (c) 2012 Zynga Inc. All rights reserved. + * Copyright (c) 2013-2016 Chukong Technologies Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,7 +25,36 @@ #ifndef __SCRIPTING_CORE_H__ #define __SCRIPTING_CORE_H__ -#include "base/CCScriptSupport.h" +#include "jsapi.h" +#include "jsfriendapi.h" + +#include "ui/UIWidget.h" +#include "scripting/js-bindings/manual/js_bindings_config.h" +#include "scripting/js-bindings/manual/spidermonkey_specifics.h" +#include "scripting/js-bindings/manual/js_manual_conversions.h" +#include "mozilla/Maybe.h" +#include "scripting/js-bindings/manual/js-BindingsExport.h" + +#include +#include +#include + +#define ENGINE_VERSION "Cocos Creator v1.6" + +extern std::unordered_map *_js_global_type_map; + +void js_log(const char *format, ...); + +typedef void (*sc_register_sth)(JSContext* cx, JS::HandleObject global); + +void registerDefaultClasses(JSContext* cx, JS::HandleObject global); + + +class SimpleRunLoop : public cocos2d::Ref +{ +public: + void update(float d); +}; /** * @addtogroup jsb @@ -46,23 +77,40 @@ * - Invoke garbage collection of JavaScript context * - etc... */ -class ScriptingCore : public cocos2d::ScriptEngineProtocol +class CC_JS_DLL ScriptingCore : public cocos2d::ScriptEngineProtocol { +private: + JSContext *_cx; + JS::PersistentRootedObject *_global; + JS::PersistentRootedObject *_debugGlobal; + SimpleRunLoop *_runLoop; + JSCompartment *_oldCompartment; + bool _jsInited; + bool _needCleanup; + bool _callFromScript; + bool _finalizing; + + ScriptingCore(); + + std::chrono::steady_clock::time_point _engineStartTime; public: - virtual ~ScriptingCore(); + + static const char* EVENT_RESET; + + ~ScriptingCore(); /**@~english * ScriptingCore is a singleton class, you can retrieve its instance with this function. * @return @~english The ScriptingCore instance. */ static ScriptingCore *getInstance(); - + /**@~english * Gets the script type, for ScriptingCore, it will return `cocos2d::kScriptTypeJavascript` * @return `cocos2d::kScriptTypeJavascript` */ virtual cocos2d::ccScriptType getScriptType() override { return cocos2d::kScriptTypeJavascript; }; - + /** * Reflect the retain relationship to script scope */ @@ -98,13 +146,29 @@ public: * @param obj @~english Object to be removed */ virtual void removeScriptObjectByObject(cocos2d::Ref* obj) override; - + /** * @brief @~english Useless in ScriptingCore, please use evalString * @see evalString */ virtual int executeString(const char* codes) override { return 0; } + /** + * @brief @~english Pause scheduled tasks and actions for an object proxy. + * @param p @~english The object proxy + */ + void pauseSchedulesAndActions(js_proxy_t* p); + /** + * @brief @~english Resume scheduled tasks and actions for an object proxy. + * @param p @~english The object proxy + */ + void resumeSchedulesAndActions(js_proxy_t* p); + /** + * @brief @~english Cleanup scheduled tasks and actions for an object proxy. + * @param p @~english The object proxy + */ + void cleanupSchedulesAndActions(js_proxy_t* p); + /** @brief Useless in ScriptingCore, please use runScript @param filename String object holding the filename of the script file that is to be executed @@ -119,7 +183,7 @@ public: virtual int executeGlobalFunction(const char* functionName) override; virtual int sendEvent(cocos2d::ScriptEvent* message) override; - + virtual bool parseConfig(ConfigType type, const std::string& str) override; /** * @brief @~english Useless in ScriptingCore @@ -130,15 +194,482 @@ public: virtual void setCalledFromScript(bool callFromScript) override { _callFromScript = callFromScript; }; virtual bool isCalledFromScript() override { return _callFromScript; }; - void restartVM(); + /** + * @brief @~english Execute a js function with a JavaScript object as parameter. + * By passing a native object, ScriptingCore will found its JavaScript object with the proxy. + * Then the function will be invoked with the native object's js proxy as caller. + * @param nativeObj @~english The caller object's C++ proxy. + * @param name @~english The function name. + * @param obj @~english The JavaScript object value as parameter. + * @return @~english Return the js function's boolean result if successfully invoked, otherwise return false. + */ + bool executeFunctionWithObjectData(void* nativeObj, const char *name, JS::HandleValue data); -private: - ScriptingCore(); + /** + * @brief @~english Execute a js function with a JavaScript caller, function name, arguments array. + * This is more reliable in js memory management + * @param owner @~english The caller object. + * @param name @~english The function name. + * @param args @~english The arguments array. + * @return @~english Return true if successfully invoked, otherwise return false. + */ + bool executeFunctionWithOwner(JS::HandleValue owner, const char *name, const JS::HandleValueArray& args); - int handleActionEvent(void* data); + /** + * @brief @~english Execute a js function with a JavaScript caller, function name, arguments array and a return value. + * This is more reliable in js memory management + * @param owner @~english The caller object. + * @param name @~english The function name. + * @param args @~english The arguments array. + * @param retVal @~english The js object to save the return value. + * @return @~english Return true if successfully invoked, otherwise return false. + */ + bool executeFunctionWithOwner(JS::HandleValue owner, const char *name, const JS::HandleValueArray& args, JS::MutableHandleValue retVal); + + /** + * @brief @~english Execute a js function with a js this object and the js function object. + * @param thisObj @~english The js this object. + * @param callback @~english The js function object. + * @return @~english Return true if successfully invoked, otherwise return false. + */ + void executeJSFunctionWithThisObj(JS::HandleValue thisObj, JS::HandleValue callback); + /** + * @brief @~english Execute a js function with a js this object, the js function object, arguments and a return value. + * @param thisObj @~english The js this object. + * @param callback @~english The js function object. + * @param vp @~english The arguments array. + * @param retVal @~english The js object to save the return value. + * @return @~english Return true if successfully invoked, otherwise return false. + */ + void executeJSFunctionWithThisObj(JS::HandleValue thisObj, JS::HandleValue callback, const JS::HandleValueArray& vp, JS::MutableHandleValue retVal); + + /**@~english + * Evaluate the specified js code string + * @param string @~english The string with the javascript code to be evaluated + * @param outVal @~english The jsval that will hold the return value of the evaluation. + * @param filename @~english The filename + * @param cx @~english The js context + * @param global @~english The js global object + * @return @~english Return true if successfully invoked, otherwise return false. + */ + bool evalString(const char *string, JS::MutableHandleValue outVal, const char *filename, JSContext* cx, JS::HandleObject global); + + /**@~english + * Evaluate the specified js code string + * @param string @~english The string with the javascript code to be evaluated + * @param outVal @~english The jsval that will hold the return value of the evaluation. + * @return @~english Return true if successfully invoked, otherwise return false. + */ + bool evalString(const char *string, JS::MutableHandleValue outVal); + + /**@~english + * Evaluate the specified js code string + * @param string @~english The string with the javascript code to be evaluated + * @return @~english Return true if successfully invoked, otherwise return false. + */ + bool evalString(const char *string); + + /** + @brief @~english Get script object for the given path + @param path @~english The script file path + @return @~english Script object + */ + bool getScript(const std::string& path, JS::MutableHandleScript script); + + /**@~english + * Compile the specified js file + * @param path @~english The path of the script to be compiled + * @param global @~english The js global object + * @param cx @~english The js context + */ + bool compileScript(const std::string& path, JS::HandleObject global, JS::MutableHandleScript script); + + /**@~english + * Run the specified js file + * @param path @~english The path of the script to be executed + * @return @~english Return true if succeed, otherwise return false. + */ + bool runScript(const std::string& path); + /**@~english + * Run the specified js file + * @param path @~english The path of the script to be executed + * @param global @~english The global object to execute the script + * @param global @~english The context to execute the script + * @return @~english Return true if succeed, otherwise return false. + */ + bool runScript(const std::string& path, JS::HandleObject global, JSContext* cx = NULL); + + /**@~english + * Require the specified js file + * The difference between run and require is that require returns the export object of the script + * @param path @~english The path of the script to be executed + * @param jsvalRet @~english On success, return the value from the last executed expression statement processed in the script + * @return @~english Return true if succeed, otherwise return false. + * @see https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ExecuteScript + */ + bool requireScript(const char *path, JS::MutableHandleValue jsvalRet); + /**@~english + * Require the specified js file + * The difference between run and require is that require returns the export object of the script + * @param path @~english The path of the script to be executed + * @param global @~english The global object to execute the script + * @param global @~english The context to execute the script + * @param jsvalRet @~english On success, return the value from the last executed expression statement processed in the script + * @return @~english Return true if succeed, otherwise return false. + * @see https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ExecuteScript + */ + bool requireScript(const char *path, JS::HandleObject global, JSContext* cx, JS::MutableHandleValue jsvalRet); + + /**@~english + * Clean script object for the specified js file + * @param path @~english The path of the js file to be cleaned + */ + void cleanScript(const char *path); + + /**@~english + * Gets the cached script objects for all executed js file + * @return @~english The cached script object map + */ + std::unordered_map* getFileScript(); + /**@~english + * Clean all script objects + */ + void cleanAllScript(); + + /**@~english + * Gets the time that the ScriptingCore was initalized + */ + std::chrono::steady_clock::time_point getEngineStartTime() const; + + /**@~english + * Initialize everything, including the js context, js global object etc. + */ + void start(); + + /**@~english + * Cleanup everything, including script cache, js context, global object etc. + */ + void cleanup(); + + /**@~english + * Cleanup everything then initialize everything + */ + void reset(); + + /**@~english + * Add the register_sth callback to the list of functions that need to be called after the creation of the context. + * It's normally used to register script bindings in the js context for bound classes + * @param callback @~english The callback to register something to the js context + */ + void addRegisterCallback(sc_register_sth callback); + + /**@~english + * Create a new context. If one is already there, it will destroy the old context and create a new one. + */ + void createGlobalContext(); + + /**@~english + * Removes all rooted object in the given js context, rooted object won't be garbage collected. + * @param cx @~english The js context + */ + static void removeAllProxys(JSContext *cx); + + /**@~english + * Simulate a touch event and dispatch it to a js object. + * @param eventType @~english The touch event type + * @param pTouch @~english The touch object + * @param obj @~english The js object + * @param retval @~english The return value of the touch event callback + * @return @~english Return 1 if succeed, otherwise return 0. + */ + int executeCustomTouchEvent(cocos2d::EventTouch::EventCode eventType, + cocos2d::Touch *pTouch, JS::HandleObject obj, JS::MutableHandleValue retval); + /**@~english + * Simulate a touch event and dispatch it to a js object. + * @param eventType @~english The touch event type + * @param pTouch @~english The touch object + * @param obj @~english The js object + * @return @~english Return 1 if succeed, otherwise return 0. + */ + int executeCustomTouchEvent(cocos2d::EventTouch::EventCode eventType, + cocos2d::Touch *pTouch, JS::HandleObject obj); + /**@~english + * Simulate a multi touch event and dispatch it to a js object. + * @param eventType @~english The touch event type + * @param touches @~english Touches list for multitouch + * @param obj @~english The js object + * @return @~english Return 1 if succeed, otherwise return 0. + */ + int executeCustomTouchesEvent(cocos2d::EventTouch::EventCode eventType, + const std::vector& touches, JS::HandleObject obj); + /**@~english + * Gets the current global context. + * @return @~english the global context + */ + JSContext* getGlobalContext() { + return _cx; + }; + + /**@~english + * Report an error in the js context + * @param cx @~english The js context + * @param message @~english The error message + * @param report @~english The js error report object + */ + static void reportError(JSContext *cx, JSErrorReport *report, JS::HandleValue err); + + /**@~english + * Log something to the js context using CCLog. + * @param cx @~english The js context + * @param argc @~english The arguments count + * @param vp @~english The arguments + * @return @~english Return true if succeed, otherwise return false. + */ + static bool log(JSContext *cx, uint32_t argc, JS::Value *vp); + + /**@~english + * Runs a script from script environment, it should be invoked from script environment + * Bound to `__jsc__.executeScript` and `window.executeScript` + * @param cx @~english The js context + * @param argc @~english The arguments count + * @param vp @~english The arguments + * @return @~english Return true if succeed, otherwise return false. + */ + static bool executeScript(JSContext *cx, uint32_t argc, JS::Value *vp); + /**@~english + * Forces a cycle of garbage collection, it should be invoked from script environment + * Bound to `__jsc__.garbageCollect` and `window.garbageCollect` + * @param cx @~english The js context + * @param argc @~english The arguments count + * @param vp @~english The arguments + */ + static bool forceGC(JSContext *cx, uint32_t argc, JS::Value *vp); + /**@~english + * Dump all named rooted objects, it should be invoked from script environment + * Bound to `__jsc__.dumpRoot` + * @param cx @~english The js context + * @param argc @~english The arguments count + * @param vp @~english The arguments + */ + static bool dumpRoot(JSContext *cx, uint32_t argc, JS::Value *vp); + /**@~english + * Check whether a js object's C++ proxy is still valid, it should be invoked from script environment + * Bound to `window.__isObjectValid` + * @param cx @~english The js context + * @param argc @~english The arguments count + * @param vp @~english The arguments + */ + static bool isObjectValid(JSContext *cx, uint32_t argc, JS::Value *vp); + + /**@~english + * Log a string to the debug environment. + * Enable the debug environment so that it can be invoked. + * @param str @~english The message to log + */ + void debugProcessInput(const std::string& str); + /**@~english + * Enable the debug environment, mozilla Firefox's remote debugger or Code IDE can connect to it. + * @param port @~english The port to connect with the debug environment, default value is 5086 + */ + void enableDebugger(unsigned int port = 5086); + /**@~english + * Gets the debug environment's global object + * @return @~english The debug environment's global object + */ + JSObject* getDebugGlobal() { return _debugGlobal->get(); } + /**@~english + * Gets the global object + * @return @~english The global object + */ + JSObject* getGlobalObject() { return _global->get(); } + + /**@~english + * Checks whether a C++ function is overrided in js prototype chain + * @param obj @~english The js object + * @param name @~english The function name + * @param native @~english The native function + * @return @~english The global object + */ + bool isFunctionOverridedInJS(JS::HandleObject obj, const std::string& name, JSNative native); + + /** + * Roots the associated JSObj. + * The GC won't collected rooted objects. This function is only called + * when compiled with CC_ENABLE_GC_FOR_NATIVE_OBJECTS=1 + */ + virtual void rootObject(cocos2d::Ref* ref) override; + /** + * Unroots the associated JSObj. + * The GC will collect this object the next time the GC + * is called. + * This function is only called when compiled with CC_ENABLE_GC_FOR_NATIVE_OBJECTS=1 + */ + virtual void unrootObject(cocos2d::Ref* ref) override; + + /** Remove proxy for a native object + */ + virtual void removeObjectProxy(void* obj) override; + + /** + * Calls the Garbage Collector + */ + virtual void garbageCollect() override; + + /** + * Sets the js object that is being finalizing in the script engine, internal use only, please do not call this function + */ + void setFinalizing (bool finalizing) {_finalizing = finalizing;}; + + /** + * Gets the js object that is being finalizing in the script engine + */ + bool getFinalizing () {return _finalizing;}; + +public: int handleNodeEvent(void* data); + int handleActionEvent(void* data); + int handleComponentEvent(void* data); - bool _callFromScript; + bool handleTouchesEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, const std::vector& touches, cocos2d::Event* event); + bool handleTouchesEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, const std::vector& touches, cocos2d::Event* event, JS::MutableHandleValue jsvalRet); + + bool handleTouchEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, cocos2d::Touch* touch, cocos2d::Event* event); + bool handleTouchEvent(void* nativeObj, cocos2d::EventTouch::EventCode eventCode, cocos2d::Touch* touch, cocos2d::Event* event, JS::MutableHandleValue jsvalRet); + + bool handleMouseEvent(void* nativeObj, cocos2d::EventMouse::MouseEventType eventType, cocos2d::Event* event); + bool handleMouseEvent(void* nativeObj, cocos2d::EventMouse::MouseEventType eventType, cocos2d::Event* event, JS::MutableHandleValue jsvalRet); + + bool handleKeyboardEvent(void* nativeObj, cocos2d::EventKeyboard::KeyCode keyCode, bool isPressed, cocos2d::Event* event); + bool handleFocusEvent(void* nativeObj, cocos2d::ui::Widget* widgetLoseFocus, cocos2d::ui::Widget* widgetGetFocus); + + void restartVM(); }; +/** + * You don't need to manage the returned pointer. They live for the whole life of + * the app. + */ +template +inline js_type_class_t *js_get_type_from_native(T* native_obj) +{ + bool found = false; + std::string typeName = typeid(*native_obj).name(); + auto typeProxyIter = _js_global_type_map->find(typeName); + if (typeProxyIter == _js_global_type_map->end()) + { + typeName = typeid(T).name(); + typeProxyIter = _js_global_type_map->find(typeName); + if (typeProxyIter != _js_global_type_map->end()) + { + found = true; + } + } + else + { + found = true; + } + return found ? typeProxyIter->second : nullptr; +} + +template +js_type_class_t *jsb_register_class(JSContext *cx, JSClass *jsClass, JS::HandleObject proto) +{ + js_type_class_t *p = nullptr; + std::string typeName = TypeTest::s_name(); + if (_js_global_type_map->find(typeName) == _js_global_type_map->end()) + { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + memset(p, 0, sizeof(js_type_class_t)); + p->jsclass = jsClass; + p->proto = new JS::PersistentRootedObject(cx, proto); + + _js_global_type_map->insert(std::make_pair(typeName, p)); + } + return p; +} + +void handlePendingException(JSContext *cx); + +void make_class_extend(JSContext *cx, JS::HandleObject proto); + +/** creates proxy that associated the nativeObj with the JsObj, add it to the global map and set the proxy to the hook's private slot*/ +js_proxy_t* jsb_new_proxy(JSContext *cx, void* nativeObj, JS::HandleObject jsObj); +/** Add a new native js proxy to the global map */ +js_proxy_t* jsb_bind_proxy(JSContext *cx, void* nativeObj, JS::HandleObject jsHandle); +/** returns the proxy associated with the Native* */ +js_proxy_t* jsb_get_native_proxy(void* nativeObj); +/** returns the proxy associated with the JSObject* */ +js_proxy_t* jsb_get_js_proxy(JSContext *cx, JS::HandleObject jsObj); +/** removes the native proxy from the global map */ +bool jsb_unbind_proxy(js_proxy_t* proxy); +/** removes the proxy */ +bool jsb_remove_proxy(js_proxy_t* proxy); + +/** + * Generic initialization function for subclasses of Ref + */ +void jsb_ref_init(JSContext* cx, JS::HandleObject obj, cocos2d::Ref* ref, const char* debug); + +/** + * Generic initialization function for subclasses of Ref. + * Similar to jsb_ref_init(), but call it if you know that Ref has been autoreleased + * This function should never be called. It is only added as way to fix + * an issue with the static auto-bindings with the "create" function + */ +void jsb_ref_autoreleased_init(JSContext* cx, JS::HandleObject obj, cocos2d::Ref* ref, const char* debug); + +/** + * Disassociates oldRef from jsobj, and associates a new Ref. + * Useful for the EaseActions and others + */ +void jsb_ref_rebind(JSContext* cx, JS::HandleObject jsobj, js_proxy_t *js2native_proxy, cocos2d::Ref* oldRef, cocos2d::Ref* newRef, const char* debug); + +/** + * Generic initialization function for non Ref classes + */ +void jsb_non_ref_init(JSContext* cx, JS::HandleObject obj, void* native, const char* debug); + +/** + * Creates a new JSObject of a certain type (typeClass) and creates a proxy associated with and the Ref + */ +bool jsb_ref_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug); + +/** + * Creates a new JSObject of a certain type (typeClass) and creates a proxy associated with and the Ref + * Similar to jsb_ref_create_jsobject(), but call it if you know that Ref has been autoreleased + * This function should never be called. It is only added as way to fix + * an issue with the static auto-bindings with the "create" function + */ +bool jsb_ref_autoreleased_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug); + +/** + * It will try to get the associated JSObjct for the native object. + * The reference created from JSObject to native object is weak because it won't retain it. + * The behavior is exactly the same with 'jsb_ref_create_jsobject' when CC_ENABLE_GC_FOR_NATIVE_OBJECTS deactivated. + */ +bool jsb_create_weak_jsobject(JSContext *cx, void *native, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug); + +/** + * It will try to get the associated JSObjct for ref. + * If it can't find it, it will create a new one associating it to Ref. + * Call this function for objects that were already created and initialized, when returning `getChild()` + */ +bool jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug=nullptr); + +/** + * It will try to get the associated JSObjct for ref. + * If it can't find it, it will create a new one associating it to Ref + * Call this function for objects that might return an already existing copy when you create them. For example, `Animation3D::create()`; + */ +bool jsb_ref_autoreleased_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug=nullptr); + +/** + * It will try to get the associated JSObjct for the native object. + * If it can't find it, it will create a new one associating it to the native object. + * The reference created from JSObject to native object is weak because it won't retain it. + * The behavior is exactly the same with 'jsb_ref_get_or_create_jsobject' when CC_ENABLE_GC_FOR_NATIVE_OBJECTS deactivated. + */ +bool jsb_get_or_create_weak_jsobject(JSContext *cx, void *native, JSClass *jsclass, JS::HandleObject proto, JS::MutableHandleObject jsObj, const char* debug=nullptr); + + #endif /* __SCRIPTING_CORE_H__ */ diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js index ea18c5beb6..758d06d506 100644 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js @@ -145,7 +145,6 @@ let BreakpointActor = ActorClassWithSpec(breakpointSpec, { * The stack frame that contained the breakpoint. */ hit: function (frame) { - log('....'); // Don't pause if we are currently stepping (in or over) or the frame is // black-boxed. let generatedLocation = this.threadActor.sources.getFrameLocation(frame); diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js index 3d865a6ccc..ced3724138 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js @@ -185,7 +185,6 @@ TabSources.prototype = { let sourceActorStore = this._thread.sourceActorStore; var id = sourceActorStore.getReusableActorId(source, originalUrl); if (id) { - log("++++ source " + originalUrl + ": " + id); actor.actorID = id; } diff --git a/native/cocos/scripting/js-bindings/script/debugger/main.js b/native/cocos/scripting/js-bindings/script/debugger/main.js index 412ed56c36..bacd565861 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/main.js +++ b/native/cocos/scripting/js-bindings/script/debugger/main.js @@ -1645,7 +1645,6 @@ DebuggerServerConnection.prototype = { this.currentPacket = undefined; } } else { - log("...." + actor._originalUrl + ", " + actor.requestTypes); ret = { error: "unrecognizedPacketType", message: ("Actor " + actor.actorID + " does not recognize the packet type " + diff --git a/native/cocos/ui/UIWebView-inl.h b/native/cocos/ui/UIWebView-inl.h index 0557d09a20..586922f4de 100644 --- a/native/cocos/ui/UIWebView-inl.h +++ b/native/cocos/ui/UIWebView-inl.h @@ -156,7 +156,13 @@ namespace experimental{ Widget::onExit(); _impl->setVisible(false); } - + + void WebView::cleanup() + { + ProtectedNode::cleanup(); + _impl->loadURL("about:blank"); + } + void WebView::setBounces(bool bounces) { _impl->setBounces(bounces); diff --git a/native/cocos/ui/UIWebView.h b/native/cocos/ui/UIWebView.h index 1b879521b0..c2fe51b702 100644 --- a/native/cocos/ui/UIWebView.h +++ b/native/cocos/ui/UIWebView.h @@ -211,6 +211,7 @@ public: virtual void setVisible(bool visible) override; virtual void onEnter() override; virtual void onExit() override; + virtual void cleanup() override; protected: virtual cocos2d::ui::Widget* createCloneInstance() override; diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle index ed5f955c60..0d0dbe18ae 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -132,12 +132,12 @@ def copySo() { } afterEvaluate { - externalNativeBuildDebug.doLast { + tasks.findByName('externalNativeBuildDebug')?.doLast { println ('Copying debug .so') copySo() } - externalNativeBuildRelease.doLast { + tasks.findByName('externalNativeBuildRelease')?.doLast { println ('Copying release .so') copySo() } diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle index b041b142c3..2ee236b04f 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -132,12 +132,12 @@ def copySo() { } afterEvaluate { - externalNativeBuildDebug.doLast { + tasks.findByName('externalNativeBuildDebug')?.doLast { println ('Copying debug .so') copySo() } - externalNativeBuildRelease.doLast { + tasks.findByName('externalNativeBuildRelease')?.doLast { println ('Copying release .so') copySo() } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle index ed5f955c60..0d0dbe18ae 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/build.gradle @@ -132,12 +132,12 @@ def copySo() { } afterEvaluate { - externalNativeBuildDebug.doLast { + tasks.findByName('externalNativeBuildDebug')?.doLast { println ('Copying debug .so') copySo() } - externalNativeBuildRelease.doLast { + tasks.findByName('externalNativeBuildRelease')?.doLast { println ('Copying release .so') copySo() }