mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-05 02:52:39 +08:00
Merge pull request #1166 from dumganhar/runtime
[new-renderer] Merge from runtime
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -36,7 +36,7 @@ base/CCRef.cpp \
|
||||
base/CCUserDefault-android.cpp \
|
||||
base/CCUserDefault.cpp \
|
||||
base/CCValue.cpp \
|
||||
base/ObjectFactory.cpp \
|
||||
base/CCThreadPool.cpp \
|
||||
base/TGAlib.cpp \
|
||||
base/ZipUtils.cpp \
|
||||
base/base64.cpp \
|
||||
@@ -84,10 +84,9 @@ scripting/js-bindings/auto/jsb_gfx_auto.cpp \
|
||||
scripting/js-bindings/auto/jsb_cocos2dx_network_auto.cpp \
|
||||
scripting/js-bindings/auto/jsb_renderer_auto.cpp \
|
||||
scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp \
|
||||
scripting/js-bindings/auto/jsb_cocos2dx_audioengine_auto.cpp \
|
||||
scripting/js-bindings/manual/JavaScriptJavaBridge.cpp \
|
||||
scripting/js-bindings/manual/jsb_opengl_functions.cpp \
|
||||
scripting/js-bindings/manual/jsb_opengl_manual.cpp \
|
||||
scripting/js-bindings/manual/jsb_opengl_registration.cpp \
|
||||
scripting/js-bindings/manual/jsb_opengl_utils.cpp \
|
||||
scripting/js-bindings/manual/jsb_classtype.cpp \
|
||||
scripting/js-bindings/manual/jsb_conversions.cpp \
|
||||
@@ -98,6 +97,7 @@ scripting/js-bindings/manual/jsb_renderer_manual.cpp \
|
||||
scripting/js-bindings/manual/jsb_socketio.cpp \
|
||||
scripting/js-bindings/manual/jsb_websocket.cpp \
|
||||
scripting/js-bindings/manual/jsb_xmlhttprequest.cpp \
|
||||
scripting/js-bindings/manual/jsb_platform_android.cpp \
|
||||
scripting/js-bindings/jswrapper/config.cpp \
|
||||
scripting/js-bindings/jswrapper/HandleObject.cpp \
|
||||
scripting/js-bindings/jswrapper/MappingUtils.cpp \
|
||||
@@ -165,7 +165,7 @@ LOCAL_STATIC_LIBRARIES += cocos_webp_static
|
||||
LOCAL_STATIC_LIBRARIES += cocos_zlib_static
|
||||
LOCAL_STATIC_LIBRARIES += uv_static
|
||||
LOCAL_STATIC_LIBRARIES += v8_static
|
||||
# LOCAL_STATIC_LIBRARIES += audioengine_static
|
||||
LOCAL_STATIC_LIBRARIES += audioengine_static
|
||||
LOCAL_STATIC_LIBRARIES += cocos_network_static
|
||||
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dxandroid_static
|
||||
@@ -190,7 +190,7 @@ include $(BUILD_STATIC_LIBRARY)
|
||||
#$(call import-module,.)
|
||||
$(call import-module,android)
|
||||
$(call import-module,platform/android)
|
||||
# $(call import-module,audio/android)
|
||||
$(call import-module,audio/android)
|
||||
$(call import-module,network)
|
||||
$(call import-module,extensions)
|
||||
$(call import-module,android/cpufeatures)
|
||||
|
||||
@@ -26,11 +26,14 @@
|
||||
#include "platform/CCPlatformConfig.h"
|
||||
|
||||
#include "audio/include/AudioEngine.h"
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "base/ccUtils.h"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
|
||||
#include "audio/android/AudioEngine-inl.h"
|
||||
#elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
|
||||
|
||||
@@ -28,6 +28,9 @@ THE SOFTWARE.
|
||||
#include "audio/android/AudioDecoderSLES.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
/* Explicitly requesting SL_IID_ANDROIDSIMPLEBUFFERQUEUE and SL_IID_PREFETCHSTATUS
|
||||
@@ -194,12 +197,12 @@ bool AudioDecoderSLES::decodeToPcm()
|
||||
{
|
||||
off_t start = 0, length = 0;
|
||||
std::string relativePath;
|
||||
size_t position = _url.find("assets/");
|
||||
size_t position = _url.find("@assets/");
|
||||
|
||||
if (0 == position)
|
||||
{
|
||||
// "assets/" is at the beginning of the path and we don't want it
|
||||
relativePath = _url.substr(strlen("assets/"));
|
||||
// "@assets/" is at the beginning of the path and we don't want it
|
||||
relativePath = _url.substr(strlen("@assets/"));
|
||||
} else
|
||||
{
|
||||
relativePath = _url;
|
||||
|
||||
@@ -29,6 +29,8 @@ THE SOFTWARE.
|
||||
#include "audio/android/tinysndfile.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
AudioDecoderWav::AudioDecoderWav()
|
||||
|
||||
@@ -33,20 +33,18 @@
|
||||
#include <sys/types.h>
|
||||
#include <android/asset_manager.h>
|
||||
#include <android/asset_manager_jni.h>
|
||||
|
||||
#include <unordered_map>
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
#include "audio/include/AudioEngine.h"
|
||||
#include "base/CCDirector.h"
|
||||
#include "platform/CCApplication.h"
|
||||
#include "base/CCScheduler.h"
|
||||
#include "base/CCEventDispatcher.h"
|
||||
#include "base/CCEventType.h"
|
||||
#include "base/CCEventListenerCustom.h"
|
||||
#include "base/ccUTF8.h"
|
||||
#include "platform/android/CCFileUtils-android.h"
|
||||
#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
|
||||
#include "platform/android/jni/JniImp.h"
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
|
||||
#include "audio/android/IAudioPlayer.h"
|
||||
#include "audio/android/ICallerThreadUtils.h"
|
||||
@@ -71,7 +69,7 @@ class CallerThreadUtils : public ICallerThreadUtils
|
||||
public:
|
||||
virtual void performFunctionInCallerThread(const std::function<void()>& func)
|
||||
{
|
||||
Director::getInstance()->getScheduler()->performFunctionInCocosThread(func);
|
||||
Application::getInstance()->getScheduler()->performFunctionInCocosThread(func);
|
||||
};
|
||||
|
||||
virtual std::thread::id getCallerThreadId()
|
||||
@@ -147,12 +145,12 @@ AudioEngineImpl::~AudioEngineImpl()
|
||||
|
||||
if (_onPauseListener != nullptr)
|
||||
{
|
||||
Director::getInstance()->getEventDispatcher()->removeEventListener(_onPauseListener);
|
||||
//TODO:cjh Application::getInstance()->getEventDispatcher()->removeEventListener(_onPauseListener);
|
||||
}
|
||||
|
||||
if (_onResumeListener != nullptr)
|
||||
{
|
||||
Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener);
|
||||
//TODO:cjh Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener);
|
||||
}
|
||||
|
||||
__impl = nullptr;
|
||||
@@ -185,11 +183,11 @@ bool AudioEngineImpl::init()
|
||||
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
|
||||
if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the output mix fail"); break; }
|
||||
|
||||
_audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, getDeviceSampleRate(), getDeviceAudioBufferSizeInFrames(), fdGetter, &__callerThreadUtils);
|
||||
_audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, getDeviceSampleRateJNI(), getDeviceAudioBufferSizeInFramesJNI(), fdGetter, &__callerThreadUtils);
|
||||
|
||||
_onPauseListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterBackground, this));
|
||||
_onPauseListener = nullptr;//Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterBackground, this));
|
||||
|
||||
_onResumeListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterForeground, this));
|
||||
_onResumeListener = nullptr;//Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterForeground, this));
|
||||
|
||||
ret = true;
|
||||
}while (false);
|
||||
|
||||
@@ -31,6 +31,8 @@
|
||||
#include <SLES/OpenSLES_Android.h>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
|
||||
#include "base/CCRef.h"
|
||||
#include "base/ccUtils.h"
|
||||
|
||||
|
||||
@@ -358,12 +358,12 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
|
||||
if (audioFilePath[0] != '/')
|
||||
{
|
||||
std::string relativePath;
|
||||
size_t position = audioFilePath.find("assets/");
|
||||
size_t position = audioFilePath.find("@assets/");
|
||||
|
||||
if (0 == position)
|
||||
{
|
||||
// "assets/" is at the beginning of the path and we don't want it
|
||||
relativePath = audioFilePath.substr(strlen("assets/"));
|
||||
// "@assets/" is at the beginning of the path and we don't want it
|
||||
relativePath = audioFilePath.substr(strlen("@assets/"));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "audio/android/ccdandroidUtils.h"
|
||||
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
|
||||
USING_NS_CC;
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
std::string getFullPathWithoutAssetsPrefix(const char* pszFilename) {
|
||||
// Changing file path to full path
|
||||
std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(pszFilename);
|
||||
// Removing `assets` since it isn't needed for the API of playing sound.
|
||||
size_t pos = fullPath.find("assets/");
|
||||
if (pos == 0)
|
||||
{
|
||||
fullPath = fullPath.substr(strlen("assets/"));
|
||||
}
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#ifndef __CCDANDROIDUTILS_H__
|
||||
#define __CCDANDROIDUTILS_H__
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
std::string getFullPathWithoutAssetsPrefix(const char* pszFilename);
|
||||
}
|
||||
}
|
||||
|
||||
#endif //__CCDANDROIDUTILS_H__
|
||||
@@ -33,7 +33,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <OpenAL/alc.h>
|
||||
#include <thread>
|
||||
#include "base/CCDirector.h"
|
||||
#include "platform/CCApplication.h"
|
||||
#include "base/CCScheduler.h"
|
||||
|
||||
#include "audio/apple/AudioDecoder.h"
|
||||
@@ -420,7 +420,7 @@ void AudioCache::invokingLoadCallbacks()
|
||||
}
|
||||
|
||||
auto isDestroyed = _isDestroyed;
|
||||
auto scheduler = Director::getInstance()->getScheduler();
|
||||
auto scheduler = Application::getInstance()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&, isDestroyed](){
|
||||
if (*isDestroyed)
|
||||
{
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
|
||||
#include "audio/include/AudioEngine.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "base/CCDirector.h"
|
||||
#include "platform/CCApplication.h"
|
||||
#include "base/CCScheduler.h"
|
||||
#include "base/ccUtils.h"
|
||||
|
||||
@@ -155,10 +155,10 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
|
||||
NSError *error = nil;
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:&error];
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
if (Director::getInstance()->isPaused())
|
||||
//FIXME:cjh if (Director::getInstance()->isPaused())
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeEnded, director was paused, try to resume it.");
|
||||
Director::getInstance()->resume();
|
||||
//FIXME:cjh Director::getInstance()->resume();
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -197,7 +197,7 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
|
||||
else if (isAudioSessionInterrupted)
|
||||
{
|
||||
ALOGD("Audio session is still interrupted, pause director!");
|
||||
Director::getInstance()->pause();
|
||||
//FIXME:cjh Director::getInstance()->pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,7 +246,7 @@ AudioEngineImpl::~AudioEngineImpl()
|
||||
{
|
||||
if (_scheduler != nullptr)
|
||||
{
|
||||
_scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
|
||||
_scheduler->unschedule("AudioEngine", this);
|
||||
}
|
||||
|
||||
if (s_ALContext) {
|
||||
@@ -355,7 +355,7 @@ bool AudioEngineImpl::init()
|
||||
|
||||
// ================ Workaround end ================ //
|
||||
|
||||
_scheduler = Director::getInstance()->getScheduler();
|
||||
_scheduler = Application::getInstance()->getScheduler();
|
||||
ret = true;
|
||||
ALOGI("OpenAL was initialized successfully!");
|
||||
}
|
||||
@@ -431,7 +431,7 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
|
||||
|
||||
if (_lazyInitLoop) {
|
||||
_lazyInitLoop = false;
|
||||
_scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
|
||||
_scheduler->schedule(CC_CALLBACK_1(AudioEngineImpl::update, this), this, 0.05f, false, "AudioEngine");
|
||||
}
|
||||
|
||||
return _currentAudioID++;
|
||||
@@ -685,7 +685,7 @@ void AudioEngineImpl::update(float dt)
|
||||
|
||||
if(_audioPlayers.empty()){
|
||||
_lazyInitLoop = true;
|
||||
_scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
|
||||
_scheduler->unschedule("AudioEngine", this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
|
||||
#include "audio/win32/AudioCache.h"
|
||||
#include <thread>
|
||||
#include "base/CCDirector.h"
|
||||
#include "platform/CCApplication.h"
|
||||
#include "base/CCScheduler.h"
|
||||
|
||||
#include "audio/win32/AudioDecoderManager.h"
|
||||
@@ -360,7 +360,7 @@ void AudioCache::invokingLoadCallbacks()
|
||||
}
|
||||
|
||||
auto isDestroyed = _isDestroyed;
|
||||
auto scheduler = Director::getInstance()->getScheduler();
|
||||
auto scheduler = Application::getInstance()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&, isDestroyed](){
|
||||
if (*isDestroyed)
|
||||
{
|
||||
|
||||
@@ -444,9 +444,7 @@ void Scheduler::resumeTargets(const std::set<void*>& targetsToResume)
|
||||
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)
|
||||
{
|
||||
_performMutex.lock();
|
||||
|
||||
_functionsToPerform.push_back(function);
|
||||
|
||||
_performMutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
Inspired by https://github.com/vit-vit/CTPL
|
||||
|
||||
****************************************************************************/
|
||||
|
||||
#include "base/CCThreadPool.h"
|
||||
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <android/log.h>
|
||||
#define LOG_TAG "ThreadPool"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,__VA_ARGS__)
|
||||
#else
|
||||
#define LOGD(...) printf(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
#define DEFAULT_THREAD_POOL_MIN_NUM (4)
|
||||
#define DEFAULT_THREAD_POOL_MAX_NUM (20)
|
||||
|
||||
#define DEFAULT_SHRINK_INTERVAL (5.0f)
|
||||
#define DEFAULT_SHRINK_STEP (2)
|
||||
#define DEFAULT_STRETCH_STEP (2)
|
||||
|
||||
static ThreadPool *__defaultThreadPool = nullptr;
|
||||
|
||||
ThreadPool *ThreadPool::getDefaultThreadPool()
|
||||
{
|
||||
if (__defaultThreadPool == nullptr)
|
||||
{
|
||||
__defaultThreadPool = newCachedThreadPool(DEFAULT_THREAD_POOL_MIN_NUM,
|
||||
DEFAULT_THREAD_POOL_MAX_NUM,
|
||||
DEFAULT_SHRINK_INTERVAL, DEFAULT_SHRINK_STEP,
|
||||
DEFAULT_STRETCH_STEP);
|
||||
}
|
||||
|
||||
return __defaultThreadPool;
|
||||
}
|
||||
|
||||
void ThreadPool::destroyDefaultThreadPool()
|
||||
{
|
||||
delete __defaultThreadPool;
|
||||
__defaultThreadPool = nullptr;
|
||||
}
|
||||
|
||||
ThreadPool *ThreadPool::newCachedThreadPool(int minThreadNum, int maxThreadNum, int shrinkInterval,
|
||||
int shrinkStep, int stretchStep)
|
||||
{
|
||||
ThreadPool *pool = new(std::nothrow) ThreadPool(minThreadNum, maxThreadNum);
|
||||
if (pool != nullptr)
|
||||
{
|
||||
pool->setFixedSize(false);
|
||||
pool->setShrinkInterval(shrinkInterval);
|
||||
pool->setShrinkStep(shrinkStep);
|
||||
pool->setStretchStep(stretchStep);
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
ThreadPool *ThreadPool::newFixedThreadPool(int threadNum)
|
||||
{
|
||||
ThreadPool *pool = new(std::nothrow) ThreadPool(threadNum, threadNum);
|
||||
if (pool != nullptr)
|
||||
{
|
||||
pool->setFixedSize(true);
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
ThreadPool *ThreadPool::newSingleThreadPool()
|
||||
{
|
||||
ThreadPool *pool = new(std::nothrow) ThreadPool(1, 1);
|
||||
if (pool != nullptr)
|
||||
{
|
||||
pool->setFixedSize(true);
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
ThreadPool::ThreadPool(int minNum, int maxNum)
|
||||
: _isDone(false), _isStop(false), _idleThreadNum(0), _minThreadNum(minNum),
|
||||
_maxThreadNum(maxNum), _initedThreadNum(0), _shrinkInterval(DEFAULT_SHRINK_INTERVAL),
|
||||
_shrinkStep(DEFAULT_SHRINK_STEP), _stretchStep(DEFAULT_STRETCH_STEP),
|
||||
_isFixedSize(false)
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
// the destructor waits for all the functions in the queue to be finished
|
||||
ThreadPool::~ThreadPool()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
// number of idle threads
|
||||
int ThreadPool::getIdleThreadNum() const
|
||||
{
|
||||
ThreadPool* thiz = const_cast<ThreadPool*>(this);
|
||||
std::lock_guard<std::mutex> lk(thiz->_idleThreadNumMutex);
|
||||
return _idleThreadNum;
|
||||
}
|
||||
|
||||
void ThreadPool::init()
|
||||
{
|
||||
gettimeofday(&_lastShrinkTime, nullptr);
|
||||
|
||||
_maxThreadNum = std::max(_minThreadNum, _maxThreadNum);
|
||||
|
||||
_threads.resize(_maxThreadNum);
|
||||
_abortFlags.resize(_maxThreadNum);
|
||||
_idleFlags.resize(_maxThreadNum);
|
||||
_initedFlags.resize(_maxThreadNum);
|
||||
|
||||
for (int i = 0; i < _maxThreadNum; ++i)
|
||||
{
|
||||
_idleFlags[i] = std::make_shared<std::atomic<bool>>(false);
|
||||
if (i < _minThreadNum)
|
||||
{
|
||||
_abortFlags[i] = std::make_shared<std::atomic<bool>>(false);
|
||||
setThread(i);
|
||||
_initedFlags[i] = std::make_shared<std::atomic<bool>>(true);
|
||||
++_initedThreadNum;
|
||||
}
|
||||
else
|
||||
{
|
||||
_abortFlags[i] = std::make_shared<std::atomic<bool>>(true);
|
||||
_initedFlags[i] = std::make_shared<std::atomic<bool>>(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ThreadPool::tryShrinkPool()
|
||||
{
|
||||
LOGD("shrink pool, _idleThreadNum = %d \n", getIdleThreadNum());
|
||||
|
||||
struct timeval before;
|
||||
gettimeofday(&before, nullptr);
|
||||
|
||||
std::vector<int> threadIDsToJoin;
|
||||
int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep);
|
||||
|
||||
for (int i = 0; i < _maxThreadNum; ++i)
|
||||
{
|
||||
if ((int)threadIDsToJoin.size() >= maxThreadNumToJoin)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (*_idleFlags[i])
|
||||
{
|
||||
*_abortFlags[i] = true;
|
||||
threadIDsToJoin.push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// stop the detached threads that were waiting
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_cv.notify_all();
|
||||
}
|
||||
|
||||
for (const auto& threadID : threadIDsToJoin)
|
||||
{ // wait for the computing threads to finish
|
||||
if (_threads[threadID]->joinable())
|
||||
{
|
||||
_threads[threadID]->join();
|
||||
}
|
||||
|
||||
_threads[threadID].reset();
|
||||
*_initedFlags[threadID] = false;
|
||||
--_initedThreadNum;
|
||||
}
|
||||
|
||||
struct timeval after;
|
||||
gettimeofday(&after, nullptr);
|
||||
|
||||
float seconds = (after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0f;
|
||||
|
||||
LOGD("shrink %d threads, waste: %f seconds\n", (int) threadIDsToJoin.size(), seconds);
|
||||
|
||||
if (_initedThreadNum <= _minThreadNum)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void ThreadPool::stretchPool(int count)
|
||||
{
|
||||
struct timeval before;
|
||||
gettimeofday(&before, nullptr);
|
||||
|
||||
int oldThreadCount = _initedThreadNum;
|
||||
int newThreadCount = 0;
|
||||
|
||||
for (int i = 0; i < _maxThreadNum; ++i)
|
||||
{
|
||||
if (!*_initedFlags[i])
|
||||
{
|
||||
*_abortFlags[i] = false;
|
||||
setThread(i);
|
||||
*_initedFlags[i] = true;
|
||||
++_initedThreadNum;
|
||||
|
||||
if (++newThreadCount >= count)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newThreadCount > 0)
|
||||
{
|
||||
struct timeval after;
|
||||
gettimeofday(&after, nullptr);
|
||||
|
||||
float seconds =
|
||||
(after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0f;
|
||||
|
||||
LOGD("stretch pool from %d to %d, waste %f seconds\n", oldThreadCount, _initedThreadNum,
|
||||
seconds);
|
||||
}
|
||||
}
|
||||
|
||||
void ThreadPool::pushTask(const std::function<void(int)>& runnable,
|
||||
TaskType type/* = DEFAULT*/)
|
||||
{
|
||||
if (!_isFixedSize)
|
||||
{
|
||||
_idleThreadNumMutex.lock();
|
||||
int idleNum = _idleThreadNum;
|
||||
_idleThreadNumMutex.unlock();
|
||||
|
||||
if (idleNum > _minThreadNum)
|
||||
{
|
||||
if (_taskQueue.empty())
|
||||
{
|
||||
struct timeval now;
|
||||
gettimeofday(&now, nullptr);
|
||||
|
||||
float seconds = (now.tv_sec - _lastShrinkTime.tv_sec) +
|
||||
(now.tv_usec - _lastShrinkTime.tv_usec) / 1000000.0f;
|
||||
if (seconds > _shrinkInterval)
|
||||
{
|
||||
tryShrinkPool();
|
||||
_lastShrinkTime = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (idleNum == 0)
|
||||
{
|
||||
stretchPool(_stretchStep);
|
||||
}
|
||||
}
|
||||
|
||||
auto callback = new(std::nothrow) std::function<void(int)>([runnable](int tid) {
|
||||
runnable(tid);
|
||||
});
|
||||
|
||||
Task task;
|
||||
task.type = type;
|
||||
task.callback = callback;
|
||||
_taskQueue.push(std::move(task));
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_cv.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
void ThreadPool::stopAllTasks()
|
||||
{
|
||||
Task task;
|
||||
while (_taskQueue.pop(task))
|
||||
{
|
||||
delete task.callback; // empty the queue
|
||||
}
|
||||
}
|
||||
|
||||
void ThreadPool::stopTasksByType(TaskType type)
|
||||
{
|
||||
Task task;
|
||||
|
||||
std::vector<Task> notStopTasks;
|
||||
notStopTasks.reserve(_taskQueue.size());
|
||||
|
||||
while (_taskQueue.pop(task))
|
||||
{
|
||||
if (task.type == type)
|
||||
{// Delete the task from queue
|
||||
delete task.callback;
|
||||
}
|
||||
else
|
||||
{// If task type isn't match, push it into a vector, then insert to task queue again
|
||||
notStopTasks.push_back(task);
|
||||
}
|
||||
}
|
||||
|
||||
if (!notStopTasks.empty())
|
||||
{
|
||||
for (const auto& t : notStopTasks)
|
||||
{
|
||||
_taskQueue.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ThreadPool::joinThread(int tid)
|
||||
{
|
||||
if (tid < 0 || tid >= (int)_threads.size())
|
||||
{
|
||||
LOGD("Invalid thread id %d\n", tid);
|
||||
return;
|
||||
}
|
||||
|
||||
// wait for the computing threads to finish
|
||||
if (*_initedFlags[tid] && _threads[tid]->joinable())
|
||||
{
|
||||
_threads[tid]->join();
|
||||
*_initedFlags[tid] = false;
|
||||
--_initedThreadNum;
|
||||
}
|
||||
}
|
||||
|
||||
int ThreadPool::getTaskNum() const
|
||||
{
|
||||
return (int) _taskQueue.size();
|
||||
}
|
||||
|
||||
void ThreadPool::setFixedSize(bool isFixedSize)
|
||||
{
|
||||
_isFixedSize = isFixedSize;
|
||||
}
|
||||
|
||||
void ThreadPool::setShrinkInterval(int seconds)
|
||||
{
|
||||
if (seconds >= 0)
|
||||
_shrinkInterval = seconds;
|
||||
}
|
||||
|
||||
void ThreadPool::setShrinkStep(int step)
|
||||
{
|
||||
if (step > 0)
|
||||
_shrinkStep = step;
|
||||
}
|
||||
|
||||
void ThreadPool::setStretchStep(int step)
|
||||
{
|
||||
if (step > 0)
|
||||
_stretchStep = step;
|
||||
}
|
||||
|
||||
void ThreadPool::stop()
|
||||
{
|
||||
if (_isDone || _isStop)
|
||||
return;
|
||||
_isDone = true; // give the waiting threads a command to finish
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_cv.notify_all(); // stop all waiting threads
|
||||
}
|
||||
|
||||
for (int i = 0, n = static_cast<int>(_threads.size()); i < n; ++i)
|
||||
{
|
||||
joinThread(i);
|
||||
}
|
||||
// if there were no threads in the pool but some functors in the queue, the functors are not deleted by the threads
|
||||
// therefore delete them here
|
||||
stopAllTasks();
|
||||
_threads.clear();
|
||||
_abortFlags.clear();
|
||||
}
|
||||
|
||||
void ThreadPool::setThread(int tid)
|
||||
{
|
||||
std::shared_ptr<std::atomic<bool>> abort_ptr(
|
||||
_abortFlags[tid]); // a copy of the shared ptr to the flag
|
||||
auto f = [this, tid, abort_ptr/* a copy of the shared ptr to the abort */]() {
|
||||
std::atomic<bool>& abort = *abort_ptr;
|
||||
Task task;
|
||||
bool isPop = _taskQueue.pop(task);
|
||||
while (true)
|
||||
{
|
||||
while (isPop)
|
||||
{ // if there is anything in the queue
|
||||
std::unique_ptr<std::function<void(int)>> func(
|
||||
task.callback); // at return, delete the function even if an exception occurred
|
||||
(*task.callback)(tid);
|
||||
if (abort)
|
||||
return; // the thread is wanted to stop, return even if the queue is not empty yet
|
||||
else
|
||||
isPop = _taskQueue.pop(task);
|
||||
}
|
||||
// the queue is empty here, wait for the next command
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_idleThreadNumMutex.lock();
|
||||
++_idleThreadNum;
|
||||
_idleThreadNumMutex.unlock();
|
||||
|
||||
*_idleFlags[tid] = true;
|
||||
_cv.wait(lock, [this, &task, &isPop, &abort]() {
|
||||
isPop = _taskQueue.pop(task);
|
||||
return isPop || _isDone || abort;
|
||||
});
|
||||
*_idleFlags[tid] = false;
|
||||
_idleThreadNumMutex.lock();
|
||||
--_idleThreadNum;
|
||||
_idleThreadNumMutex.unlock();
|
||||
|
||||
if (!isPop)
|
||||
return; // if the queue is empty and isDone == true or *flag then return
|
||||
}
|
||||
};
|
||||
_threads[tid].reset(
|
||||
new(std::nothrow) std::thread(f)); // compiler may not support std::make_unique()
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,237 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
Inspired by https://github.com/vit-vit/CTPL
|
||||
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "platform/CCStdC.h"
|
||||
#include "platform/CCPlatformDefine.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
/**
|
||||
* @addtogroup base
|
||||
* @{
|
||||
*/
|
||||
|
||||
class CC_DLL ThreadPool
|
||||
{
|
||||
public:
|
||||
|
||||
enum class TaskType
|
||||
{
|
||||
DEFAULT = 0,
|
||||
NETWORK,
|
||||
IO,
|
||||
AUDIO,
|
||||
USER = 1000
|
||||
};
|
||||
|
||||
/*
|
||||
* Gets the default thread pool which is a cached thread pool with default parameters.
|
||||
*/
|
||||
static ThreadPool *getDefaultThreadPool();
|
||||
|
||||
/*
|
||||
* Destroys the default thread pool
|
||||
*/
|
||||
static void destroyDefaultThreadPool();
|
||||
|
||||
/*
|
||||
* Creates a cached thread pool
|
||||
* @note The return value has to be delete while it doesn't needed
|
||||
*/
|
||||
static ThreadPool *newCachedThreadPool(int minThreadNum, int maxThreadNum, int shrinkInterval,
|
||||
int shrinkStep, int stretchStep);
|
||||
|
||||
/*
|
||||
* Creates a thread pool with fixed thread count
|
||||
* @note The return value has to be delete while it doesn't needed
|
||||
*/
|
||||
static ThreadPool *newFixedThreadPool(int threadNum);
|
||||
|
||||
/*
|
||||
* Creates a thread pool with only one thread in the pool, it could be used to execute multiply tasks serially in just one thread.
|
||||
* @note The return value has to be delete while it doesn't needed
|
||||
*/
|
||||
static ThreadPool *newSingleThreadPool();
|
||||
|
||||
// the destructor waits for all the functions in the queue to be finished
|
||||
~ThreadPool();
|
||||
|
||||
/* Pushs a task to thread pool
|
||||
* @param runnable The callback of the task executed in sub thread
|
||||
* @param type The task type, it's TASK_TYPE_DEFAULT if this argument isn't assigned
|
||||
* @note This function has to be invoked in cocos thread
|
||||
*/
|
||||
void pushTask(const std::function<void(int /*threadId*/)>& runnable, TaskType type = TaskType::DEFAULT);
|
||||
|
||||
// Stops all tasks, it will remove all tasks in queue
|
||||
void stopAllTasks();
|
||||
|
||||
// Stops some tasks by type
|
||||
void stopTasksByType(TaskType type);
|
||||
|
||||
// Gets the minimum thread numbers
|
||||
inline int getMinThreadNum() const
|
||||
{ return _minThreadNum; };
|
||||
|
||||
// Gets the maximum thread numbers
|
||||
inline int getMaxThreadNum() const
|
||||
{ return _maxThreadNum; };
|
||||
|
||||
// Gets the number of idle threads
|
||||
int getIdleThreadNum() const;
|
||||
|
||||
// Gets the number of initialized threads
|
||||
inline int getInitedThreadNum() const
|
||||
{ return _initedThreadNum; };
|
||||
|
||||
// Gets the task number
|
||||
int getTaskNum() const;
|
||||
|
||||
/*
|
||||
* Trys to shrink pool
|
||||
* @note This method is only available for cached thread pool
|
||||
*/
|
||||
bool tryShrinkPool();
|
||||
|
||||
private:
|
||||
ThreadPool(int minNum, int maxNum);
|
||||
|
||||
ThreadPool(const ThreadPool&);
|
||||
|
||||
ThreadPool(ThreadPool&&);
|
||||
|
||||
ThreadPool& operator=(const ThreadPool&);
|
||||
|
||||
ThreadPool& operator=(ThreadPool&&);
|
||||
|
||||
void init();
|
||||
|
||||
void stop();
|
||||
|
||||
void setThread(int tid);
|
||||
|
||||
void joinThread(int tid);
|
||||
|
||||
void setFixedSize(bool isFixedSize);
|
||||
|
||||
void setShrinkInterval(int seconds);
|
||||
|
||||
void setShrinkStep(int step);
|
||||
|
||||
void setStretchStep(int step);
|
||||
|
||||
void stretchPool(int count);
|
||||
|
||||
std::vector<std::unique_ptr<std::thread>> _threads;
|
||||
std::vector<std::shared_ptr<std::atomic<bool>>> _abortFlags;
|
||||
std::vector<std::shared_ptr<std::atomic<bool>>> _idleFlags;
|
||||
std::vector<std::shared_ptr<std::atomic<bool>>> _initedFlags;
|
||||
|
||||
template<typename T>
|
||||
class ThreadSafeQueue
|
||||
{
|
||||
public:
|
||||
bool push(T const& value)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(this->mutex);
|
||||
this->q.push(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
// deletes the retrieved element, do not use for non integral types
|
||||
bool pop(T& v)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(this->mutex);
|
||||
if (this->q.empty())
|
||||
return false;
|
||||
v = this->q.front();
|
||||
this->q.pop();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
auto thiz = const_cast<ThreadSafeQueue*>(this);
|
||||
std::unique_lock<std::mutex> lock(thiz->mutex);
|
||||
return this->q.empty();
|
||||
}
|
||||
|
||||
size_t size() const
|
||||
{
|
||||
auto thiz = const_cast<ThreadSafeQueue*>(this);
|
||||
std::unique_lock<std::mutex> lock(thiz->mutex);
|
||||
return this->q.size();
|
||||
}
|
||||
|
||||
private:
|
||||
std::queue<T> q;
|
||||
std::mutex mutex;
|
||||
};
|
||||
|
||||
struct Task
|
||||
{
|
||||
TaskType type;
|
||||
std::function<void(int)> *callback;
|
||||
};
|
||||
|
||||
ThreadSafeQueue<Task> _taskQueue;
|
||||
std::atomic<bool> _isDone;
|
||||
std::atomic<bool> _isStop;
|
||||
|
||||
//FIXME: std::atomic<int> isn't supported by ndk-r10e while compiling with `armeabi` arch.
|
||||
// So using a mutex here instead.
|
||||
int _idleThreadNum; // how many threads are waiting
|
||||
std::mutex _idleThreadNumMutex;
|
||||
|
||||
std::mutex _mutex;
|
||||
std::condition_variable _cv;
|
||||
|
||||
int _minThreadNum;
|
||||
int _maxThreadNum;
|
||||
int _initedThreadNum;
|
||||
|
||||
struct timeval _lastShrinkTime;
|
||||
float _shrinkInterval;
|
||||
int _shrinkStep;
|
||||
int _stretchStep;
|
||||
bool _isFixedSize;
|
||||
};
|
||||
|
||||
// end of base group
|
||||
/// @}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -1,127 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include <functional>
|
||||
#include "base/ObjectFactory.h"
|
||||
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
ObjectFactory::TInfo::TInfo(void)
|
||||
:_class("")
|
||||
,_fun(nullptr)
|
||||
,_func(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
ObjectFactory::TInfo::TInfo(const std::string& type, Instance ins)
|
||||
:_class(type)
|
||||
,_fun(ins)
|
||||
,_func(nullptr)
|
||||
{
|
||||
ObjectFactory::getInstance()->registerType(*this);
|
||||
}
|
||||
|
||||
ObjectFactory::TInfo::TInfo(const std::string& type, InstanceFunc ins)
|
||||
:_class(type)
|
||||
,_fun(nullptr)
|
||||
,_func(ins)
|
||||
{
|
||||
ObjectFactory::getInstance()->registerType(*this);
|
||||
}
|
||||
|
||||
ObjectFactory::TInfo::TInfo(const TInfo &t)
|
||||
{
|
||||
_class = t._class;
|
||||
_fun = t._fun;
|
||||
_func = t._func;
|
||||
}
|
||||
|
||||
ObjectFactory::TInfo::~TInfo(void)
|
||||
{
|
||||
_class = "";
|
||||
_fun = nullptr;
|
||||
_func = nullptr;
|
||||
}
|
||||
|
||||
ObjectFactory::TInfo& ObjectFactory::TInfo::operator= (const TInfo &t)
|
||||
{
|
||||
_class = t._class;
|
||||
_fun = t._fun;
|
||||
_func = t._func;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
ObjectFactory* ObjectFactory::_sharedFactory = nullptr;
|
||||
|
||||
ObjectFactory::ObjectFactory(void)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
ObjectFactory::~ObjectFactory(void)
|
||||
{
|
||||
_typeMap.clear();
|
||||
}
|
||||
|
||||
ObjectFactory* ObjectFactory::getInstance()
|
||||
{
|
||||
if ( nullptr == _sharedFactory)
|
||||
{
|
||||
_sharedFactory = new (std::nothrow) ObjectFactory();
|
||||
}
|
||||
return _sharedFactory;
|
||||
}
|
||||
|
||||
void ObjectFactory::destroyInstance()
|
||||
{
|
||||
CC_SAFE_DELETE(_sharedFactory);
|
||||
}
|
||||
|
||||
Ref* ObjectFactory::createObject(const std::string &name)
|
||||
{
|
||||
Ref *o = nullptr;
|
||||
do
|
||||
{
|
||||
const TInfo t = _typeMap[name];
|
||||
if (t._fun != nullptr)
|
||||
{
|
||||
o = t._fun();
|
||||
}else if (t._func != nullptr)
|
||||
{
|
||||
o = t._func();
|
||||
}
|
||||
} while (0);
|
||||
|
||||
return o;
|
||||
}
|
||||
|
||||
void ObjectFactory::registerType(const TInfo &t)
|
||||
{
|
||||
_typeMap.insert(std::make_pair(t._class, t));
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
@@ -1,73 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
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
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef __TRIGGERFACTORY_H__
|
||||
#define __TRIGGERFACTORY_H__
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
#include "base/CCRef.h"
|
||||
#include "base/ccMacros.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL ObjectFactory
|
||||
{
|
||||
public:
|
||||
typedef cocos2d::Ref* (*Instance)(void);
|
||||
typedef std::function<cocos2d::Ref* (void)> InstanceFunc;
|
||||
struct CC_DLL TInfo
|
||||
{
|
||||
TInfo(void);
|
||||
TInfo(const std::string& type, Instance ins = nullptr);
|
||||
TInfo(const std::string& type, InstanceFunc ins = nullptr);
|
||||
TInfo(const TInfo &t);
|
||||
~TInfo(void);
|
||||
TInfo& operator= (const TInfo &t);
|
||||
std::string _class;
|
||||
Instance _fun;
|
||||
InstanceFunc _func;
|
||||
};
|
||||
typedef std::unordered_map<std::string, TInfo> FactoryMap;
|
||||
|
||||
static ObjectFactory* getInstance();
|
||||
static void destroyInstance();
|
||||
cocos2d::Ref* createObject(const std::string &name);
|
||||
|
||||
void registerType(const TInfo &t);
|
||||
void removeAll();
|
||||
|
||||
protected:
|
||||
ObjectFactory(void);
|
||||
virtual ~ObjectFactory(void);
|
||||
private:
|
||||
static ObjectFactory *_sharedFactory;
|
||||
FactoryMap _typeMap;
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
||||
@@ -228,7 +228,7 @@ typedef struct unz_file_info_s unz_file_info;
|
||||
*
|
||||
* @param zipFile Zip file name
|
||||
* @param filter The first part of file names, which should be accessible.
|
||||
* For example, "assets/". Other files will be missed.
|
||||
* For example, "@assets/". Other files will be missed.
|
||||
*
|
||||
* @since v2.0.5
|
||||
*/
|
||||
|
||||
@@ -89,6 +89,14 @@ public:
|
||||
void set_strokeStyle(const std::string& strokeStyle);
|
||||
void set_globalCompositeOperation(const std::string& globalCompositeOperation);
|
||||
|
||||
// transform
|
||||
void translate(float x, float y);
|
||||
void scale(float x, float y);
|
||||
void rotate(float angle);
|
||||
|
||||
void transform(float a, float b, float c, float d, float e, float f);
|
||||
void setTransform(float a, float b, float c, float d, float e, float f);
|
||||
|
||||
private:
|
||||
void recreateBuffer();
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@ public:
|
||||
public:
|
||||
DictMaker()
|
||||
: _resultType(SAX_RESULT_NONE)
|
||||
, _state(SAX_NONE)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -131,7 +132,7 @@ public:
|
||||
return _rootArray;
|
||||
}
|
||||
|
||||
void startElement(void *ctx, const char *name, const char **atts)
|
||||
virtual void startElement(void *ctx, const char *name, const char **atts) override
|
||||
{
|
||||
CC_UNUSED_PARAM(ctx);
|
||||
CC_UNUSED_PARAM(atts);
|
||||
@@ -222,7 +223,7 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void endElement(void *ctx, const char *name)
|
||||
virtual void endElement(void *ctx, const char *name) override
|
||||
{
|
||||
CC_UNUSED_PARAM(ctx);
|
||||
SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top();
|
||||
@@ -294,7 +295,7 @@ public:
|
||||
_state = SAX_NONE;
|
||||
}
|
||||
|
||||
void textHandler(void *ctx, const char *ch, int len)
|
||||
virtual void textHandler(void *ctx, const char *ch, int len) override
|
||||
{
|
||||
CC_UNUSED_PARAM(ctx);
|
||||
if (_state == SAX_NONE)
|
||||
@@ -387,12 +388,12 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& ful
|
||||
doc->LinkEndChild(docType);
|
||||
|
||||
tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
|
||||
rootEle->SetAttribute("version", "1.0");
|
||||
if (nullptr == rootEle)
|
||||
{
|
||||
delete doc;
|
||||
return false;
|
||||
}
|
||||
rootEle->SetAttribute("version", "1.0");
|
||||
doc->LinkEndChild(rootEle);
|
||||
|
||||
tinyxml2::XMLElement *innerDict = generateElementForDict(dict, doc);
|
||||
@@ -427,12 +428,12 @@ bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::st
|
||||
doc->LinkEndChild(docType);
|
||||
|
||||
tinyxml2::XMLElement *rootEle = doc->NewElement("plist");
|
||||
rootEle->SetAttribute("version", "1.0");
|
||||
if (nullptr == rootEle)
|
||||
{
|
||||
delete doc;
|
||||
return false;
|
||||
}
|
||||
rootEle->SetAttribute("version", "1.0");
|
||||
doc->LinkEndChild(rootEle);
|
||||
|
||||
tinyxml2::XMLElement *innerDict = generateElementForArray(vecData, doc);
|
||||
@@ -806,7 +807,6 @@ std::string FileUtils::fullPathForFilename(const std::string &filename) const
|
||||
_fullPathCache.insert(std::make_pair(filename, fullpath));
|
||||
return fullpath;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -825,6 +825,11 @@ std::string FileUtils::fullPathFromRelativeFile(const std::string &filename, con
|
||||
|
||||
void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
|
||||
{
|
||||
if (_searchResolutionsOrderArray == searchResolutionsOrder)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool existDefault = false;
|
||||
_fullPathCache.clear();
|
||||
_searchResolutionsOrderArray.clear();
|
||||
@@ -873,41 +878,64 @@ const std::vector<std::string>& FileUtils::getSearchPaths() const
|
||||
return _searchPathArray;
|
||||
}
|
||||
|
||||
const std::vector<std::string>& FileUtils::getOriginalSearchPaths() const
|
||||
{
|
||||
return _originalSearchPaths;
|
||||
}
|
||||
|
||||
void FileUtils::setWritablePath(const std::string& writablePath)
|
||||
{
|
||||
_writablePath = writablePath;
|
||||
}
|
||||
|
||||
const std::string& FileUtils::getDefaultResourceRootPath() const
|
||||
{
|
||||
return _defaultResRootPath;
|
||||
}
|
||||
|
||||
void FileUtils::setDefaultResourceRootPath(const std::string& path)
|
||||
{
|
||||
_defaultResRootPath = path;
|
||||
if (_defaultResRootPath != path)
|
||||
{
|
||||
_fullPathCache.clear();
|
||||
_defaultResRootPath = path;
|
||||
if (!_defaultResRootPath.empty() && _defaultResRootPath[_defaultResRootPath.length()-1] != '/')
|
||||
{
|
||||
_defaultResRootPath += '/';
|
||||
}
|
||||
|
||||
// Updates search paths
|
||||
setSearchPaths(_originalSearchPaths);
|
||||
}
|
||||
}
|
||||
|
||||
void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
|
||||
{
|
||||
bool existDefaultRootPath = false;
|
||||
_originalSearchPaths = searchPaths;
|
||||
|
||||
_fullPathCache.clear();
|
||||
_searchPathArray.clear();
|
||||
for (const auto& iter : searchPaths)
|
||||
|
||||
for (const auto& path : _originalSearchPaths)
|
||||
{
|
||||
std::string prefix;
|
||||
std::string path;
|
||||
std::string fullPath;
|
||||
|
||||
if (!isAbsolutePath(iter))
|
||||
if (!isAbsolutePath(path))
|
||||
{ // Not an absolute path
|
||||
prefix = _defaultResRootPath;
|
||||
}
|
||||
path = prefix + (iter);
|
||||
fullPath = prefix + path;
|
||||
if (!path.empty() && path[path.length()-1] != '/')
|
||||
{
|
||||
path += "/";
|
||||
fullPath += "/";
|
||||
}
|
||||
if (!existDefaultRootPath && path == _defaultResRootPath)
|
||||
{
|
||||
existDefaultRootPath = true;
|
||||
}
|
||||
_searchPathArray.push_back(path);
|
||||
_searchPathArray.push_back(fullPath);
|
||||
}
|
||||
|
||||
if (!existDefaultRootPath)
|
||||
@@ -929,8 +957,10 @@ void FileUtils::addSearchPath(const std::string &searchpath,const bool front)
|
||||
path += "/";
|
||||
}
|
||||
if (front) {
|
||||
_originalSearchPaths.insert(_originalSearchPaths.begin(), searchpath);
|
||||
_searchPathArray.insert(_searchPathArray.begin(), path);
|
||||
} else {
|
||||
_originalSearchPaths.push_back(searchpath);
|
||||
_searchPathArray.push_back(path);
|
||||
}
|
||||
}
|
||||
@@ -1264,9 +1294,9 @@ bool FileUtils::createDirectory(const std::string& path)
|
||||
|
||||
// Create path recursively
|
||||
subpath = "";
|
||||
for (int i = 0; i < dirs.size(); ++i)
|
||||
for (const auto& iter : dirs)
|
||||
{
|
||||
subpath += dirs[i];
|
||||
subpath += iter;
|
||||
dir = opendir(subpath.c_str());
|
||||
|
||||
if (!dir)
|
||||
@@ -1456,7 +1486,7 @@ std::string FileUtils::normalizePath(const std::string& path) const
|
||||
ret = std::regex_replace(ret, std::regex("/\\.$"), "");
|
||||
|
||||
size_t pos;
|
||||
while ((pos = ret.find("..")) != std::string::npos)
|
||||
while ((pos = ret.find("..")) != std::string::npos && pos > 2)
|
||||
{
|
||||
size_t prevSlash = ret.rfind("/", pos-2);
|
||||
if (prevSlash == std::string::npos)
|
||||
|
||||
@@ -405,9 +405,9 @@ public:
|
||||
* @note This method could access relative path and absolute path.
|
||||
* If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path.
|
||||
* For instance:
|
||||
* On Android, the default resource root path is "assets/".
|
||||
* On Android, the default resource root path is "@assets/".
|
||||
* If "/mnt/sdcard/" and "resources-large" were set to the search paths vector,
|
||||
* "resources-large" will be converted to "assets/resources-large" since it was a relative path.
|
||||
* "resources-large" will be converted to "@assets/resources-large" since it was a relative path.
|
||||
*
|
||||
* @param searchPaths The array contains search paths.
|
||||
* @see fullPathForFilename(const char*)
|
||||
@@ -417,6 +417,11 @@ public:
|
||||
*/
|
||||
virtual void setSearchPaths(const std::vector<std::string>& searchPaths);
|
||||
|
||||
/**
|
||||
* Get default resource root path.
|
||||
*/
|
||||
const std::string& getDefaultResourceRootPath() const;
|
||||
|
||||
/**
|
||||
* Set default resource root path.
|
||||
*/
|
||||
@@ -432,12 +437,21 @@ public:
|
||||
/**
|
||||
* Gets the array of search paths.
|
||||
*
|
||||
* @return The array of search paths.
|
||||
* @return The array of search paths which may contain the prefix of default resource root path.
|
||||
* @note In best practise, getter function should return the value of setter function passes in.
|
||||
* But since we should not break the compatibility, we keep using the old logic.
|
||||
* Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead.
|
||||
* @see fullPathForFilename(const char*).
|
||||
* @lua NA
|
||||
*/
|
||||
virtual const std::vector<std::string>& getSearchPaths() const;
|
||||
|
||||
/**
|
||||
* Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'.
|
||||
* @return The array of the original search paths
|
||||
*/
|
||||
virtual const std::vector<std::string>& getOriginalSearchPaths() const;
|
||||
|
||||
/**
|
||||
* Gets the writable path.
|
||||
* @return The path that can be write/read a file in
|
||||
@@ -552,7 +566,7 @@ public:
|
||||
/**
|
||||
* Checks whether the path is an absolute path.
|
||||
*
|
||||
* @note On Android, if the parameter passed in is relative to "assets/", this method will treat it as an absolute path.
|
||||
* @note On Android, if the parameter passed in is relative to "@assets/", this method will treat it as an absolute path.
|
||||
* Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path.
|
||||
*
|
||||
* @param path The path that needs to be checked.
|
||||
@@ -724,11 +738,16 @@ protected:
|
||||
*/
|
||||
std::vector<std::string> _searchPathArray;
|
||||
|
||||
/**
|
||||
* The search paths which was set by 'setSearchPaths' / 'addSearchPath'.
|
||||
*/
|
||||
std::vector<std::string> _originalSearchPaths;
|
||||
|
||||
/**
|
||||
* The default root path of resources.
|
||||
* If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass.
|
||||
* For instance:
|
||||
* On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init().
|
||||
* On Android, the default root path of resources will be assigned with "@assets/" in FileUtilsAndroid::init().
|
||||
* Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
|
||||
*/
|
||||
std::string _defaultResRootPath;
|
||||
|
||||
@@ -27,8 +27,8 @@ public:
|
||||
|
||||
CanvasRenderingContext2DImpl()
|
||||
{
|
||||
_obj = JniHelper::newObject("org/cocos2dx/lib/CanvasRenderingContext2DImpl");
|
||||
JniHelper::getEnv()->NewGlobalRef(_obj);
|
||||
jobject obj = JniHelper::newObject("org/cocos2dx/lib/CanvasRenderingContext2DImpl");
|
||||
_obj = JniHelper::getEnv()->NewGlobalRef(obj);
|
||||
}
|
||||
|
||||
~CanvasRenderingContext2DImpl()
|
||||
@@ -38,6 +38,8 @@ public:
|
||||
|
||||
void recreateBuffer(float w, float h)
|
||||
{
|
||||
if (w < 1.0f || h < 1.0f)
|
||||
return;
|
||||
JniHelper::callObjectVoidMethod(_obj, _className, "recreateBuffer", w, h);
|
||||
}
|
||||
|
||||
@@ -55,18 +57,24 @@ public:
|
||||
|
||||
void fillText(const std::string& text, float x, float y, float maxWidth)
|
||||
{
|
||||
if (text.empty())
|
||||
return;
|
||||
JniHelper::callObjectVoidMethod(_obj, _className, "fillText", text, x, y, maxWidth);
|
||||
fillData();
|
||||
}
|
||||
|
||||
void strokeText(const std::string& text, float x, float y, float maxWidth)
|
||||
{
|
||||
if (text.empty())
|
||||
return;
|
||||
JniHelper::callObjectVoidMethod(_obj, _className, "strokeText", text, x, y, maxWidth);
|
||||
fillData();
|
||||
}
|
||||
|
||||
float measureText(const std::string& text)
|
||||
{
|
||||
if (text.empty())
|
||||
return 0.0f;
|
||||
return JniHelper::callObjectFloatMethod(_obj, _className, "measureText", text);
|
||||
}
|
||||
|
||||
@@ -377,4 +385,32 @@ void CanvasRenderingContext2D::set_globalCompositeOperation(const std::string& g
|
||||
|
||||
}
|
||||
|
||||
// transform
|
||||
//TODO:
|
||||
|
||||
void CanvasRenderingContext2D::translate(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::scale(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::rotate(float angle)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
@@ -103,9 +103,9 @@ public:
|
||||
fullPathOrFontName = FileUtils::getInstance()->fullPathForFilename(textDefinition._fontName);
|
||||
// If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context
|
||||
// requires this portion of the path to be omitted for assets inside the app package.
|
||||
if (fullPathOrFontName.find("assets/") == 0)
|
||||
if (fullPathOrFontName.find("@assets/") == 0)
|
||||
{
|
||||
fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path.
|
||||
fullPathOrFontName = fullPathOrFontName.substr(strlen("@assets/")); // Chop out the 'assets/' portion of the path.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const
|
||||
{
|
||||
const char* s = strFilePath.c_str();
|
||||
|
||||
// Found "assets/" at the beginning of the path and we don't want it
|
||||
// Found "@assets/" at the beginning of the path and we don't want it
|
||||
if (strFilePath.find(_defaultResRootPath) == 0) s += _defaultResRootPath.length();
|
||||
|
||||
if (obbfile && obbfile->fileExists(s))
|
||||
@@ -219,7 +219,7 @@ bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath_) con
|
||||
else
|
||||
{
|
||||
// find it in apk's assets dir
|
||||
// Found "assets/" at the beginning of the path and we don't want it
|
||||
// Found "@assets/" at the beginning of the path and we don't want it
|
||||
CCLOG("find in apk dirPath(%s)", dirPath.c_str());
|
||||
const char* s = dirPath.c_str();
|
||||
if (dirPath.find(_defaultResRootPath) == 0)
|
||||
@@ -268,7 +268,7 @@ FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, Res
|
||||
std::string relativePath;
|
||||
size_t position = fullPath.find(_defaultResRootPath);
|
||||
if (0 == position) {
|
||||
// "assets/" is at the beginning of the path and we don't want it
|
||||
// "@assets/" is at the beginning of the path and we don't want it
|
||||
relativePath += fullPath.substr(_defaultResRootPath.length());
|
||||
} else {
|
||||
relativePath = fullPath;
|
||||
|
||||
+40
-16
@@ -36,6 +36,7 @@ import android.util.Log;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CanvasRenderingContext2DImpl {
|
||||
|
||||
@@ -102,31 +103,54 @@ public class CanvasRenderingContext2DImpl {
|
||||
sContext = null;
|
||||
}
|
||||
|
||||
private static HashMap<String, Typeface> sTypefaceCache = new HashMap<>();
|
||||
|
||||
// url is a full path started with '@assets/'
|
||||
private static void loadTypeface(String familyName, String url) {
|
||||
if (!sTypefaceCache.containsKey(familyName)) {
|
||||
try {
|
||||
Typeface typeface = null;
|
||||
if (url.startsWith("/")) {
|
||||
typeface = Typeface.createFromFile(url);
|
||||
} else if (sContext.get() != null) {
|
||||
final String prefix = "@assets/";
|
||||
if (url.startsWith(prefix)) {
|
||||
url = url.substring(prefix.length());
|
||||
}
|
||||
typeface = Typeface.createFromAsset(sContext.get().getAssets(), url);
|
||||
}
|
||||
|
||||
if (typeface != null) {
|
||||
sTypefaceCache.put(familyName, typeface);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO:cjh: native should clear font cache before exiting game.
|
||||
private static void clearTypefaceCache() {
|
||||
sTypefaceCache.clear();
|
||||
}
|
||||
|
||||
private static TextPaint newPaint(final String fontName, final int fontSize, final boolean enableBold) {
|
||||
final TextPaint paint = new TextPaint();
|
||||
paint.setTextSize(fontSize);
|
||||
paint.setAntiAlias(true);
|
||||
|
||||
// Set type face for paint, now it support .ttf file.
|
||||
if (fontName.endsWith(".ttf")) {
|
||||
try {
|
||||
final Typeface typeFace = Cocos2dxTypefaces.get(sContext.get(), fontName);
|
||||
paint.setTypeface(typeFace);
|
||||
} catch (final Exception e) {
|
||||
Log.e("Cocos2dxBitmap", "error to create ttf type face: "
|
||||
+ fontName);
|
||||
|
||||
// The file may not find, use system font.
|
||||
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
|
||||
}
|
||||
} else {
|
||||
if(enableBold) {
|
||||
paint.setTypeface(Typeface.create(fontName, Typeface.BOLD));
|
||||
Typeface typeFace;
|
||||
if (sTypefaceCache.containsKey(fontName)) {
|
||||
typeFace = sTypefaceCache.get(fontName);
|
||||
} else {
|
||||
if (enableBold) {
|
||||
typeFace = Typeface.create(fontName, Typeface.BOLD);
|
||||
} else {
|
||||
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
|
||||
typeFace = Typeface.create(fontName, Typeface.NORMAL);
|
||||
}
|
||||
}
|
||||
|
||||
paint.setTypeface(typeFace);
|
||||
return paint;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
|
||||
private int mScreenWidth;
|
||||
private int mScreenHeight;
|
||||
private boolean mNativeInitCompleted = false;
|
||||
private String mDefaultResourcePath = "";
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
@@ -65,15 +66,39 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
|
||||
this.mScreenHeight = surfaceHeight;
|
||||
}
|
||||
|
||||
public void setDefaultResourcePath(String path) {
|
||||
if (path == null)
|
||||
return;
|
||||
mDefaultResourcePath = path;
|
||||
}
|
||||
|
||||
public interface OnGameEngineInitializedListener {
|
||||
void onGameEngineInitialized();
|
||||
}
|
||||
|
||||
private OnGameEngineInitializedListener mGameEngineInitializedListener;
|
||||
|
||||
public void setOnGameEngineInitializedListener(OnGameEngineInitializedListener listener) {
|
||||
mGameEngineInitializedListener = listener;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) {
|
||||
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
|
||||
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight, mDefaultResourcePath);
|
||||
this.mLastTickInNanoSeconds = System.nanoTime();
|
||||
mNativeInitCompleted = true;
|
||||
if (mGameEngineInitializedListener != null) {
|
||||
Cocos2dxHelper.getActivity().runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mGameEngineInitializedListener.onGameEngineInitialized();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -117,7 +142,7 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
|
||||
private static native void nativeTouchesCancel(final int[] ids, final float[] xs, final float[] ys);
|
||||
private static native boolean nativeKeyEvent(final int keyCode,boolean isPressed);
|
||||
private static native void nativeRender();
|
||||
private static native void nativeInit(final int width, final int height);
|
||||
private static native void nativeInit(final int width, final int height, final String resourcePath);
|
||||
private static native void nativeOnSurfaceChanged(final int width, final int height);
|
||||
private static native void nativeOnPause();
|
||||
private static native void nativeOnResume();
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
#include "scripting/js-bindings/event/EventDispatcher.h"
|
||||
#include "platform/android/CCFileUtils-android.h"
|
||||
#include "base/CCScheduler.h"
|
||||
#include "base/CCAutoreleasePool.h"
|
||||
|
||||
#define JNI_IMP_LOG_TAG "JniImp"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,JNI_IMP_LOG_TAG,__VA_ARGS__)
|
||||
@@ -125,10 +126,16 @@ extern "C"
|
||||
* Cocos2dxRenderer native functions implementation.
|
||||
*****************************************************/
|
||||
|
||||
JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h)
|
||||
JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h, jstring jDefaultResourcePath)
|
||||
{
|
||||
std::string defaultResourcePath = JniHelper::jstring2string(jDefaultResourcePath);
|
||||
LOGD("CocosRenderer.nativeInit: %d, %d, %s", w, h, defaultResourcePath.c_str());
|
||||
g_width = w;
|
||||
g_height = h;
|
||||
|
||||
if (!defaultResourcePath.empty())
|
||||
FileUtils::getInstance()->setDefaultResourceRootPath(defaultResourcePath);
|
||||
|
||||
se::ScriptEngine* se = se::ScriptEngine::getInstance();
|
||||
se->addRegisterCallback(setCanvasCallback);
|
||||
|
||||
@@ -141,13 +148,16 @@ extern "C"
|
||||
{
|
||||
static std::chrono::steady_clock::time_point prevTime;
|
||||
static std::chrono::steady_clock::time_point now;
|
||||
float dt = 0.f;
|
||||
|
||||
static float dt = 0.f;
|
||||
|
||||
g_app->getScheduler()->update(dt);
|
||||
EventDispatcher::dispatchTickEvent(dt);
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
|
||||
now = std::chrono::steady_clock::now();
|
||||
dt = std::chrono::duration_cast<std::chrono::microseconds>(now - prevTime).count() / 1000000.f;
|
||||
|
||||
prevTime = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause()
|
||||
@@ -195,52 +205,64 @@ extern "C"
|
||||
* Touches native functions implementation.
|
||||
***********************************************************/
|
||||
|
||||
static void dispatchTouchEventWithOnePoint(JNIEnv* env, cocos2d::TouchEvent::Type type, jint id, jfloat x, jfloat y)
|
||||
{
|
||||
cocos2d::TouchEvent touchEvent;
|
||||
touchEvent.type = type;
|
||||
|
||||
cocos2d::TouchInfo touchInfo;
|
||||
touchInfo.index = id;
|
||||
touchInfo.x = x;
|
||||
touchInfo.y = y;
|
||||
touchEvent.touches.push_back(touchInfo);
|
||||
|
||||
cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent);
|
||||
}
|
||||
|
||||
static void dispatchTouchEventWithPoints(JNIEnv* env, cocos2d::TouchEvent::Type type, jintArray ids, jfloatArray xs, jfloatArray ys)
|
||||
{
|
||||
cocos2d::TouchEvent touchEvent;
|
||||
touchEvent.type = type;
|
||||
|
||||
int size = env->GetArrayLength(ids);
|
||||
jint id[size];
|
||||
jfloat x[size];
|
||||
jfloat y[size];
|
||||
|
||||
env->GetIntArrayRegion(ids, 0, size, id);
|
||||
env->GetFloatArrayRegion(xs, 0, size, x);
|
||||
env->GetFloatArrayRegion(ys, 0, size, y);
|
||||
|
||||
for(int i = 0; i < size; i++)
|
||||
{
|
||||
cocos2d::TouchInfo touchInfo;
|
||||
touchInfo.index = id[i];
|
||||
touchInfo.x = x[i];
|
||||
touchInfo.y = y[i];
|
||||
touchEvent.touches.push_back(touchInfo);
|
||||
}
|
||||
|
||||
cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
|
||||
{
|
||||
//TODO
|
||||
dispatchTouchEventWithOnePoint(env, cocos2d::TouchEvent::Type::BEGAN, id, x, y);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y)
|
||||
{
|
||||
//TODO
|
||||
dispatchTouchEventWithOnePoint(env, cocos2d::TouchEvent::Type::ENDED, id, x, y);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
|
||||
{
|
||||
int size = env->GetArrayLength(ids);
|
||||
jint id[size];
|
||||
jfloat x[size];
|
||||
jfloat y[size];
|
||||
|
||||
env->GetIntArrayRegion(ids, 0, size, id);
|
||||
env->GetFloatArrayRegion(xs, 0, size, x);
|
||||
env->GetFloatArrayRegion(ys, 0, size, y);
|
||||
|
||||
intptr_t idlong[size];
|
||||
for(int i = 0; i < size; i++)
|
||||
idlong[i] = id[i];
|
||||
|
||||
//TODO
|
||||
// cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(size, idlong, x, y);
|
||||
dispatchTouchEventWithPoints(env, cocos2d::TouchEvent::Type::MOVED, ids, xs, ys);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
|
||||
{
|
||||
int size = env->GetArrayLength(ids);
|
||||
jint id[size];
|
||||
jfloat x[size];
|
||||
jfloat y[size];
|
||||
|
||||
env->GetIntArrayRegion(ids, 0, size, id);
|
||||
env->GetFloatArrayRegion(xs, 0, size, x);
|
||||
env->GetFloatArrayRegion(ys, 0, size, y);
|
||||
|
||||
intptr_t idlong[size];
|
||||
for(int i = 0; i < size; i++)
|
||||
idlong[i] = id[i];
|
||||
|
||||
//TODO
|
||||
// cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(size, idlong, x, y);
|
||||
dispatchTouchEventWithPoints(env, cocos2d::TouchEvent::Type::CANCELLED, ids, xs, ys);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyEvent(JNIEnv * env, jobject thiz, jint keyCode, jboolean isPressed)
|
||||
@@ -351,12 +373,12 @@ int getObbAssetFileDescriptorJNI(const std::string& path, long* startOffset, lon
|
||||
return fd;
|
||||
}
|
||||
|
||||
int getDeviceSampleRate()
|
||||
int getDeviceSampleRateJNI()
|
||||
{
|
||||
return g_deviceSampleRate;
|
||||
}
|
||||
|
||||
int getDeviceAudioBufferSizeInFrames()
|
||||
int getDeviceAudioBufferSizeInFramesJNI()
|
||||
{
|
||||
return g_deviceAudioBufferSizeInFrames;
|
||||
}
|
||||
|
||||
@@ -26,5 +26,5 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(dir: '../java/libs', include: ['*.jar'])
|
||||
compile fileTree(include: ['*.jar'], dir: '../java/libs')
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
#import "CCApplication.h"
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "base/CCScheduler.h"
|
||||
#include "base/CCAutoreleasePool.h"
|
||||
#import "CCEAGLView-ios.h"
|
||||
#import "renderer/gfx/DeviceGraphics.h"
|
||||
#import "scripting/js-bindings/jswrapper/jsc/ScriptEngine.hpp"
|
||||
@@ -132,12 +133,15 @@
|
||||
{
|
||||
static std::chrono::steady_clock::time_point prevTime;
|
||||
static std::chrono::steady_clock::time_point now;
|
||||
float dt = 0.f;
|
||||
static float dt = 0.f;
|
||||
|
||||
prevTime = std::chrono::steady_clock::now();
|
||||
|
||||
_scheduler->update(dt);
|
||||
cocos2d::EventDispatcher::dispatchTickEvent(dt);
|
||||
|
||||
[(CCEAGLView*)(_application->getView()) swapBuffers];
|
||||
cocos2d::PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
|
||||
now = std::chrono::steady_clock::now();
|
||||
dt = std::chrono::duration_cast<std::chrono::microseconds>(now - prevTime).count() / 1000000.f;
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
#include "base/csscolorparser.hpp"
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_platform.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreText/CoreText.h>
|
||||
|
||||
#include <regex>
|
||||
|
||||
@@ -74,7 +76,7 @@ namespace {
|
||||
@synthesize textBaseLine = _textBaseLine;
|
||||
|
||||
-(id) init {
|
||||
if ([super init]) {
|
||||
if (self = [super init]) {
|
||||
_width = _height = 0;
|
||||
_context = nil;
|
||||
_colorSpace = nil;
|
||||
@@ -99,23 +101,17 @@ namespace {
|
||||
}
|
||||
|
||||
-(UIFont*) _createSystemFont {
|
||||
NSString * fntName = [NSString stringWithString:_fontName];
|
||||
NSString* pathExtension = [fntName pathExtension];
|
||||
id font = NULL;
|
||||
if ([pathExtension length] > 0) {
|
||||
// On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when
|
||||
// calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must
|
||||
// be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just
|
||||
// the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store
|
||||
// the '.ttf' extensions when referring to custom fonts.
|
||||
fntName = [[fntName lastPathComponent] stringByDeletingPathExtension];
|
||||
UIFont* font = [UIFont fontWithName:_fontName size:_fontSize];
|
||||
|
||||
// create the font
|
||||
font = [UIFont fontWithName:fntName size:_fontSize];
|
||||
if (font == nil) {
|
||||
const auto& familyMap = getFontFamilyNameMap();
|
||||
auto iter = familyMap.find([_fontName UTF8String]);
|
||||
if (iter != familyMap.end()) {
|
||||
font = [UIFont fontWithName:[NSString stringWithUTF8String:iter->second.c_str()] size:_fontSize];
|
||||
}
|
||||
}
|
||||
|
||||
if (!font)
|
||||
{
|
||||
if (font == nil) {
|
||||
if (false) { //TODO: enableBold) {
|
||||
font = [UIFont boldSystemFontOfSize:_fontSize];
|
||||
} else {
|
||||
@@ -125,7 +121,7 @@ namespace {
|
||||
return font;
|
||||
}
|
||||
|
||||
-(void) updateFontWithName: (NSString*)fontName fontSize: (CGFloat)fontSize {
|
||||
-(void) updateFontWithName:(NSString*) fontName fontSize:(CGFloat) fontSize {
|
||||
self.fontName = fontName;
|
||||
_fontSize = fontSize;
|
||||
self.font = [self _createSystemFont];
|
||||
@@ -329,13 +325,14 @@ CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height)
|
||||
: __width(width)
|
||||
, __height(height)
|
||||
{
|
||||
SE_LOGD("CanvasGradient constructor: %p, width: %f, height: %f\n", this, width, height);
|
||||
SE_LOGD("CanvasRenderingContext2D constructor: %p, width: %f, height: %f\n", this, width, height);
|
||||
_impl = [[CanvasRenderingContext2DImpl alloc] init];
|
||||
[_impl recreateBufferWithWidth:width height:height];
|
||||
}
|
||||
|
||||
CanvasRenderingContext2D::~CanvasRenderingContext2D()
|
||||
{
|
||||
SE_LOGD("CanvasGradient destructor: %p\n", this);
|
||||
SE_LOGD("CanvasRenderingContext2D destructor: %p\n", this);
|
||||
[_impl release];
|
||||
}
|
||||
|
||||
@@ -548,4 +545,31 @@ void CanvasRenderingContext2D::set_globalCompositeOperation(const std::string& g
|
||||
|
||||
}
|
||||
|
||||
// transform
|
||||
|
||||
void CanvasRenderingContext2D::translate(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::scale(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::rotate(float angle)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
@@ -516,8 +516,6 @@ namespace
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
|
||||
{
|
||||
if (_isKeyboardShown)
|
||||
|
||||
@@ -28,7 +28,8 @@ THE SOFTWARE.
|
||||
#import <algorithm>
|
||||
#import <mutex>
|
||||
|
||||
#import "base/CCScheduler.h"
|
||||
#include "base/CCScheduler.h"
|
||||
#include "base/CCAutoreleasePool.h"
|
||||
#import "platform/CCApplication.h"
|
||||
#import "platform/desktop/CCGLView-desktop.h"
|
||||
#import "scripting/js-bindings/event/EventDispatcher.h"
|
||||
@@ -111,7 +112,8 @@ void Application::start()
|
||||
EventDispatcher::dispatchTickEvent(dt);
|
||||
|
||||
CAST_VIEW(_view)->swapBuffers();
|
||||
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
|
||||
now = std::chrono::steady_clock::now();
|
||||
dt = std::chrono::duration_cast<std::chrono::microseconds>(now - prevTime).count() / 1000000.f;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "base/csscolorparser.hpp"
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_platform.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Cocoa/Cocoa.h>
|
||||
@@ -74,7 +75,7 @@ namespace {
|
||||
@synthesize textBaseLine = _textBaseLine;
|
||||
|
||||
-(id) init {
|
||||
if ([super init]) {
|
||||
if (self = [super init]) {
|
||||
_textAlign = CanvasTextAlign::LEFT;
|
||||
_textBaseLine = CanvasTextBaseline::BOTTOM;
|
||||
[self updateFontWithName:@"Arial" fontSize:30];
|
||||
@@ -93,21 +94,31 @@ namespace {
|
||||
}
|
||||
|
||||
-(NSFont*) _createSystemFont {
|
||||
NSString* fntName = [[_fontName lastPathComponent] stringByDeletingPathExtension];
|
||||
NSFontTraitMask mask = NSUnboldFontMask | NSUnitalicFontMask;
|
||||
|
||||
NSFont *font = [[NSFontManager sharedFontManager]
|
||||
fontWithFamily:fntName
|
||||
NSFont* font = [[NSFontManager sharedFontManager]
|
||||
fontWithFamily:_fontName
|
||||
traits:mask
|
||||
weight:0
|
||||
size:_fontSize];
|
||||
|
||||
if (font == nil) {
|
||||
const auto& familyMap = getFontFamilyNameMap();
|
||||
auto iter = familyMap.find([_fontName UTF8String]);
|
||||
if (iter != familyMap.end()) {
|
||||
font = [[NSFontManager sharedFontManager]
|
||||
fontWithFamily: [NSString stringWithUTF8String:iter->second.c_str()]
|
||||
traits: mask
|
||||
weight: 0
|
||||
size: _fontSize];
|
||||
}
|
||||
}
|
||||
|
||||
if (font == nil) {
|
||||
font = [[NSFontManager sharedFontManager]
|
||||
fontWithFamily:@"Arial"
|
||||
fontWithFamily: @"Arial"
|
||||
traits: mask
|
||||
weight:0
|
||||
size:_fontSize];
|
||||
weight: 0
|
||||
size: _fontSize];
|
||||
}
|
||||
return font;
|
||||
}
|
||||
@@ -221,6 +232,16 @@ namespace {
|
||||
unsigned char* data = [bitmap bitmapData]; //Use the same buffer to improve the performance.
|
||||
|
||||
NSUInteger textureSize = _image.size.width * _image.size.height * 4;
|
||||
|
||||
// For text debugging ...
|
||||
// for (int i = 0; i < textureSize; i += 4) {
|
||||
// if (data[i+3] == 0)
|
||||
// {
|
||||
// data[i+3] = 255;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
|
||||
uint8_t* buffer = (uint8_t*)malloc(sizeof(uint8_t) * textureSize);
|
||||
if (buffer) {
|
||||
memcpy(buffer, data, textureSize);
|
||||
@@ -308,13 +329,14 @@ CanvasRenderingContext2D::CanvasRenderingContext2D(float width, float height)
|
||||
: __width(width)
|
||||
, __height(height)
|
||||
{
|
||||
// SE_LOGD("CanvasGradient constructor: %p, width: %f, height: %f\n", this, width, height);
|
||||
SE_LOGD("CanvasGradient constructor: %p, width: %f, height: %f\n", this, width, height);
|
||||
_impl = [[CanvasRenderingContext2DImpl alloc] init];
|
||||
[_impl recreateBufferWithWidth:width height:height];
|
||||
}
|
||||
|
||||
CanvasRenderingContext2D::~CanvasRenderingContext2D()
|
||||
{
|
||||
SE_LOGD("CanvasGradient destructor: %p\n", this);
|
||||
SE_LOGD("CanvasRenderingContext2D destructor: %p\n", this);
|
||||
[_impl release];
|
||||
}
|
||||
|
||||
@@ -527,4 +549,31 @@ void CanvasRenderingContext2D::set_globalCompositeOperation(const std::string& g
|
||||
|
||||
}
|
||||
|
||||
// transform
|
||||
|
||||
void CanvasRenderingContext2D::translate(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::scale(float x, float y)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::rotate(float angle)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::transform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void CanvasRenderingContext2D::setTransform(float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
@@ -98,6 +98,28 @@ str
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method normalizePath
|
||||
* @param {String} arg0
|
||||
* @return {String}
|
||||
*/
|
||||
normalizePath : function (
|
||||
str
|
||||
)
|
||||
{
|
||||
return ;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getDefaultResourceRootPath
|
||||
* @return {String}
|
||||
*/
|
||||
getDefaultResourceRootPath : function (
|
||||
)
|
||||
{
|
||||
return ;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method loadFilenameLookupDictionaryFromFile
|
||||
* @param {String} arg0
|
||||
@@ -140,6 +162,18 @@ getSearchPaths : function (
|
||||
return new Array();
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getFileDir
|
||||
* @param {String} arg0
|
||||
* @return {String}
|
||||
*/
|
||||
getFileDir : function (
|
||||
str
|
||||
)
|
||||
{
|
||||
return ;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method writeToFile
|
||||
* @param {map_object} arg0
|
||||
@@ -154,6 +188,16 @@ str
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getOriginalSearchPaths
|
||||
* @return {Array}
|
||||
*/
|
||||
getOriginalSearchPaths : function (
|
||||
)
|
||||
{
|
||||
return new Array();
|
||||
},
|
||||
|
||||
/**
|
||||
* @method listFiles
|
||||
* @param {String} arg0
|
||||
@@ -552,6 +596,26 @@ float
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setTransform
|
||||
* @param {float} arg0
|
||||
* @param {float} arg1
|
||||
* @param {float} arg2
|
||||
* @param {float} arg3
|
||||
* @param {float} arg4
|
||||
* @param {float} arg5
|
||||
*/
|
||||
setTransform : function (
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method stroke
|
||||
*/
|
||||
@@ -572,6 +636,18 @@ str
|
||||
return cc.Size;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method scale
|
||||
* @param {float} arg0
|
||||
* @param {float} arg1
|
||||
*/
|
||||
scale : function (
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method clearRect
|
||||
* @param {float} arg0
|
||||
@@ -588,6 +664,26 @@ float
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method transform
|
||||
* @param {float} arg0
|
||||
* @param {float} arg1
|
||||
* @param {float} arg2
|
||||
* @param {float} arg3
|
||||
* @param {float} arg4
|
||||
* @param {float} arg5
|
||||
*/
|
||||
transform : function (
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method fillText
|
||||
* @param {String} arg0
|
||||
@@ -644,6 +740,16 @@ float
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method rotate
|
||||
* @param {float} arg0
|
||||
*/
|
||||
rotate : function (
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method beginPath
|
||||
*/
|
||||
@@ -652,6 +758,18 @@ beginPath : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method translate
|
||||
* @param {float} arg0
|
||||
* @param {float} arg1
|
||||
*/
|
||||
translate : function (
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method createLinearGradient
|
||||
* @param {float} arg0
|
||||
|
||||
@@ -3,6 +3,70 @@
|
||||
*/
|
||||
var renderer = renderer || {};
|
||||
|
||||
/**
|
||||
* @class ProgramLib
|
||||
*/
|
||||
renderer.ProgramLib = {
|
||||
|
||||
/**
|
||||
* @method getProgram
|
||||
* @param {String} arg0
|
||||
* @param {map_object} arg1
|
||||
* @return {cc.renderer::Program}
|
||||
*/
|
||||
getProgram : function (
|
||||
str,
|
||||
map
|
||||
)
|
||||
{
|
||||
return cc.renderer::Program;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method define
|
||||
* @param {String} arg0
|
||||
* @param {String} arg1
|
||||
* @param {String} arg2
|
||||
* @param {Array} arg3
|
||||
*/
|
||||
define : function (
|
||||
str,
|
||||
str,
|
||||
str,
|
||||
array
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getKey
|
||||
* @param {String} arg0
|
||||
* @param {map_object} arg1
|
||||
* @return {unsigned int}
|
||||
*/
|
||||
getKey : function (
|
||||
str,
|
||||
map
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method ProgramLib
|
||||
* @constructor
|
||||
* @param {cc.renderer::DeviceGraphics} arg0
|
||||
* @param {Array} arg1
|
||||
*/
|
||||
ProgramLib : function (
|
||||
devicegraphics,
|
||||
array
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @class Model
|
||||
*/
|
||||
@@ -140,6 +204,16 @@ Model : function (
|
||||
*/
|
||||
renderer.Base = {
|
||||
|
||||
/**
|
||||
* @method getProgramLib
|
||||
* @return {cc.renderer::ProgramLib}
|
||||
*/
|
||||
getProgramLib : function (
|
||||
)
|
||||
{
|
||||
return cc.renderer::ProgramLib;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method init
|
||||
* @param {cc.renderer::DeviceGraphics|cc.renderer::DeviceGraphics} devicegraphics
|
||||
@@ -176,13 +250,15 @@ renderer.ForwardRenderer = {
|
||||
* @method init
|
||||
* @param {cc.renderer::DeviceGraphics} arg0
|
||||
* @param {Array} arg1
|
||||
* @param {int} arg2
|
||||
* @param {cc.renderer::Texture2D} arg2
|
||||
* @param {int} arg3
|
||||
* @param {int} arg4
|
||||
* @return {bool}
|
||||
*/
|
||||
init : function (
|
||||
devicegraphics,
|
||||
array,
|
||||
texture2d,
|
||||
int,
|
||||
int
|
||||
)
|
||||
@@ -480,16 +556,6 @@ Camera : function (
|
||||
*/
|
||||
renderer.Technique = {
|
||||
|
||||
/**
|
||||
* @method getPasses
|
||||
* @return {Array}
|
||||
*/
|
||||
getPasses : function (
|
||||
)
|
||||
{
|
||||
return new Array();
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getStageIDs
|
||||
* @return {unsigned int}
|
||||
@@ -500,6 +566,18 @@ getStageIDs : function (
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setPass
|
||||
* @param {int} arg0
|
||||
* @param {cc.renderer::Pass} arg1
|
||||
*/
|
||||
setPass : function (
|
||||
int,
|
||||
pass
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setStages
|
||||
* @param {Array} arg0
|
||||
@@ -510,6 +588,16 @@ array
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getPasses
|
||||
* @return {Array}
|
||||
*/
|
||||
getPasses : function (
|
||||
)
|
||||
{
|
||||
return new Array();
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getParameters
|
||||
* @return {Array}
|
||||
@@ -576,18 +664,6 @@ clear : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setProperty
|
||||
* @param {String} arg0
|
||||
* @param {cc.renderer::Technique::Parameter} arg1
|
||||
*/
|
||||
setProperty : function (
|
||||
str,
|
||||
parameter
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getTechnique
|
||||
* @param {String} arg0
|
||||
@@ -1136,6 +1212,16 @@ Light : function (
|
||||
*/
|
||||
renderer.Pass = {
|
||||
|
||||
/**
|
||||
* @method getStencilTest
|
||||
* @return {bool}
|
||||
*/
|
||||
getStencilTest : function (
|
||||
)
|
||||
{
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setStencilBack
|
||||
*/
|
||||
@@ -1144,6 +1230,16 @@ setStencilBack : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setStencilTest
|
||||
* @param {bool} arg0
|
||||
*/
|
||||
setStencilTest : function (
|
||||
bool
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setCullMode
|
||||
* @param {cc.renderer::CullMode} arg0
|
||||
|
||||
@@ -164,7 +164,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_setCurrentTime(se::State& s)
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_setCurrentTime : Error processing arguments");
|
||||
bool result = cocos2d::experimental::AudioEngine::setCurrentTime(arg0, arg1);
|
||||
@@ -184,7 +184,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_getVolume(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_getVolume : Error processing arguments");
|
||||
float result = cocos2d::experimental::AudioEngine::getVolume(arg0);
|
||||
ok &= float_to_seval(result, &s.rval());
|
||||
@@ -246,7 +246,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_pause(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_pause : Error processing arguments");
|
||||
cocos2d::experimental::AudioEngine::pause(arg0);
|
||||
return true;
|
||||
@@ -308,7 +308,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_getCurrentTime(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_getCurrentTime : Error processing arguments");
|
||||
float result = cocos2d::experimental::AudioEngine::getCurrentTime(arg0);
|
||||
ok &= float_to_seval(result, &s.rval());
|
||||
@@ -327,7 +327,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_setMaxAudioInstance(se::State& s
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_setMaxAudioInstance : Error processing arguments");
|
||||
bool result = cocos2d::experimental::AudioEngine::setMaxAudioInstance(arg0);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
@@ -346,7 +346,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_isLoop(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_isLoop : Error processing arguments");
|
||||
bool result = cocos2d::experimental::AudioEngine::isLoop(arg0);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
@@ -392,7 +392,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_setVolume(se::State& s)
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_setVolume : Error processing arguments");
|
||||
cocos2d::experimental::AudioEngine::setVolume(arg0, arg1);
|
||||
@@ -545,7 +545,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_getState(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_getState : Error processing arguments");
|
||||
int result = (int)cocos2d::experimental::AudioEngine::getState(arg0);
|
||||
ok &= int32_to_seval(result, &s.rval());
|
||||
@@ -564,7 +564,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_resume(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_resume : Error processing arguments");
|
||||
cocos2d::experimental::AudioEngine::resume(arg0);
|
||||
return true;
|
||||
@@ -581,7 +581,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_stop(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_stop : Error processing arguments");
|
||||
cocos2d::experimental::AudioEngine::stop(arg0);
|
||||
return true;
|
||||
@@ -598,7 +598,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_getDuration(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_getDuration : Error processing arguments");
|
||||
float result = cocos2d::experimental::AudioEngine::getDuration(arg0);
|
||||
ok &= float_to_seval(result, &s.rval());
|
||||
@@ -618,7 +618,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_setLoop(se::State& s)
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
bool arg1;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
ok &= seval_to_boolean(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_audioengine_AudioEngine_setLoop : Error processing arguments");
|
||||
cocos2d::experimental::AudioEngine::setLoop(arg0, arg1);
|
||||
@@ -652,15 +652,15 @@ static bool js_cocos2dx_audioengine_AudioEngine_setFinishCallback(se::State& s)
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
std::function<void (int, const std::basic_string<char> &)> arg1;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
std::function<void (int, const std::string&)> arg1;
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
do {
|
||||
if (args[1].isObject() && args[1].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(s.thisObject());
|
||||
se::Value jsFunc(args[1]);
|
||||
jsFunc.toObject()->root();
|
||||
auto lambda = [=](int larg0, const std::basic_string<char> & larg1) -> void {
|
||||
auto lambda = [=](int larg0, const std::string& larg1) -> void {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
se::AutoHandleScope hs;
|
||||
|
||||
@@ -713,7 +713,7 @@ static bool js_cocos2dx_audioengine_AudioEngine_getProfile(se::State& s)
|
||||
do {
|
||||
if (argc == 1) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
if (!ok) { ok = true; break; }
|
||||
cocos2d::experimental::AudioProfile* result = cocos2d::experimental::AudioEngine::getProfile(arg0);
|
||||
ok &= native_ptr_to_seval<cocos2d::experimental::AudioProfile>((cocos2d::experimental::AudioProfile*)result, &s.rval());
|
||||
|
||||
@@ -179,6 +179,45 @@ static bool js_cocos2dx_FileUtils_renameFile(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_renameFile)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_normalizePath(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_FileUtils_normalizePath : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_normalizePath : Error processing arguments");
|
||||
std::string result = cobj->normalizePath(arg0);
|
||||
ok &= std_string_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_normalizePath : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_normalizePath)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_getDefaultResourceRootPath(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_FileUtils_getDefaultResourceRootPath : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
const std::string& result = cobj->getDefaultResourceRootPath();
|
||||
ok &= std_string_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_getDefaultResourceRootPath : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_getDefaultResourceRootPath)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
@@ -255,6 +294,27 @@ static bool js_cocos2dx_FileUtils_getSearchPaths(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_getSearchPaths)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_getFileDir(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_FileUtils_getFileDir : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_getFileDir : Error processing arguments");
|
||||
std::string result = cobj->getFileDir(arg0);
|
||||
ok &= std_string_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_getFileDir : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_getFileDir)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_writeToFile(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
@@ -278,6 +338,24 @@ static bool js_cocos2dx_FileUtils_writeToFile(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_writeToFile)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_getOriginalSearchPaths(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_FileUtils_getOriginalSearchPaths : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
const std::vector<std::string>& result = cobj->getOriginalSearchPaths();
|
||||
ok &= std_vector_string_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_FileUtils_getOriginalSearchPaths : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_FileUtils_getOriginalSearchPaths)
|
||||
|
||||
static bool js_cocos2dx_FileUtils_listFiles(se::State& s)
|
||||
{
|
||||
cocos2d::FileUtils* cobj = (cocos2d::FileUtils*)s.nativeThisObject();
|
||||
@@ -865,11 +943,15 @@ bool js_register_cocos2dx_FileUtils(se::Object* obj)
|
||||
cls->defineFunction("getDataFromFile", _SE(js_cocos2dx_FileUtils_getDataFromFile));
|
||||
cls->defineFunction("isAbsolutePath", _SE(js_cocos2dx_FileUtils_isAbsolutePath));
|
||||
cls->defineFunction("renameFile", _SE(js_cocos2dx_FileUtils_renameFile));
|
||||
cls->defineFunction("normalizePath", _SE(js_cocos2dx_FileUtils_normalizePath));
|
||||
cls->defineFunction("getDefaultResourceRootPath", _SE(js_cocos2dx_FileUtils_getDefaultResourceRootPath));
|
||||
cls->defineFunction("loadFilenameLookup", _SE(js_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile));
|
||||
cls->defineFunction("isPopupNotify", _SE(js_cocos2dx_FileUtils_isPopupNotify));
|
||||
cls->defineFunction("getValueVectorFromFile", _SE(js_cocos2dx_FileUtils_getValueVectorFromFile));
|
||||
cls->defineFunction("getSearchPaths", _SE(js_cocos2dx_FileUtils_getSearchPaths));
|
||||
cls->defineFunction("getFileDir", _SE(js_cocos2dx_FileUtils_getFileDir));
|
||||
cls->defineFunction("writeToFile", _SE(js_cocos2dx_FileUtils_writeToFile));
|
||||
cls->defineFunction("getOriginalSearchPaths", _SE(js_cocos2dx_FileUtils_getOriginalSearchPaths));
|
||||
cls->defineFunction("listFiles", _SE(js_cocos2dx_FileUtils_listFiles));
|
||||
cls->defineFunction("getValueMapFromFile", _SE(js_cocos2dx_FileUtils_getValueMapFromFile));
|
||||
cls->defineFunction("getFileSize", _SE(js_cocos2dx_FileUtils_getFileSize));
|
||||
@@ -1078,6 +1160,35 @@ static bool js_cocos2dx_CanvasRenderingContext2D_lineTo(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_lineTo)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_setTransform(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_CanvasRenderingContext2D_setTransform : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 6) {
|
||||
float arg0 = 0;
|
||||
float arg1 = 0;
|
||||
float arg2 = 0;
|
||||
float arg3 = 0;
|
||||
float arg4 = 0;
|
||||
float arg5 = 0;
|
||||
ok &= seval_to_float(args[0], &arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
ok &= seval_to_float(args[4], &arg4);
|
||||
ok &= seval_to_float(args[5], &arg5);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_CanvasRenderingContext2D_setTransform : Error processing arguments");
|
||||
cobj->setTransform(arg0, arg1, arg2, arg3, arg4, arg5);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 6);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_setTransform)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_stroke(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
@@ -1114,6 +1225,27 @@ static bool js_cocos2dx_CanvasRenderingContext2D_measureText(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_measureText)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_scale(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_CanvasRenderingContext2D_scale : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
float arg0 = 0;
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[0], &arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_CanvasRenderingContext2D_scale : Error processing arguments");
|
||||
cobj->scale(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_scale)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_clearRect(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
@@ -1139,6 +1271,35 @@ static bool js_cocos2dx_CanvasRenderingContext2D_clearRect(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_clearRect)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_transform(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_CanvasRenderingContext2D_transform : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 6) {
|
||||
float arg0 = 0;
|
||||
float arg1 = 0;
|
||||
float arg2 = 0;
|
||||
float arg3 = 0;
|
||||
float arg4 = 0;
|
||||
float arg5 = 0;
|
||||
ok &= seval_to_float(args[0], &arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
ok &= seval_to_float(args[4], &arg4);
|
||||
ok &= seval_to_float(args[5], &arg5);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_CanvasRenderingContext2D_transform : Error processing arguments");
|
||||
cobj->transform(arg0, arg1, arg2, arg3, arg4, arg5);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 6);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_transform)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_fillText(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
@@ -1251,6 +1412,25 @@ static bool js_cocos2dx_CanvasRenderingContext2D_fillRect(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_fillRect)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_rotate(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_CanvasRenderingContext2D_rotate : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
float arg0 = 0;
|
||||
ok &= seval_to_float(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_CanvasRenderingContext2D_rotate : Error processing arguments");
|
||||
cobj->rotate(arg0);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_rotate)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_beginPath(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
@@ -1266,6 +1446,27 @@ static bool js_cocos2dx_CanvasRenderingContext2D_beginPath(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_beginPath)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_translate(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_CanvasRenderingContext2D_translate : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
float arg0 = 0;
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[0], &arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_CanvasRenderingContext2D_translate : Error processing arguments");
|
||||
cobj->translate(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_CanvasRenderingContext2D_translate)
|
||||
|
||||
static bool js_cocos2dx_CanvasRenderingContext2D_createLinearGradient(se::State& s)
|
||||
{
|
||||
cocos2d::CanvasRenderingContext2D* cobj = (cocos2d::CanvasRenderingContext2D*)s.nativeThisObject();
|
||||
@@ -1350,14 +1551,19 @@ bool js_register_cocos2dx_CanvasRenderingContext2D(se::Object* obj)
|
||||
cls->defineFunction("restore", _SE(js_cocos2dx_CanvasRenderingContext2D_restore));
|
||||
cls->defineFunction("moveTo", _SE(js_cocos2dx_CanvasRenderingContext2D_moveTo));
|
||||
cls->defineFunction("lineTo", _SE(js_cocos2dx_CanvasRenderingContext2D_lineTo));
|
||||
cls->defineFunction("setTransform", _SE(js_cocos2dx_CanvasRenderingContext2D_setTransform));
|
||||
cls->defineFunction("stroke", _SE(js_cocos2dx_CanvasRenderingContext2D_stroke));
|
||||
cls->defineFunction("measureText", _SE(js_cocos2dx_CanvasRenderingContext2D_measureText));
|
||||
cls->defineFunction("scale", _SE(js_cocos2dx_CanvasRenderingContext2D_scale));
|
||||
cls->defineFunction("clearRect", _SE(js_cocos2dx_CanvasRenderingContext2D_clearRect));
|
||||
cls->defineFunction("transform", _SE(js_cocos2dx_CanvasRenderingContext2D_transform));
|
||||
cls->defineFunction("fillText", _SE(js_cocos2dx_CanvasRenderingContext2D_fillText));
|
||||
cls->defineFunction("strokeText", _SE(js_cocos2dx_CanvasRenderingContext2D_strokeText));
|
||||
cls->defineFunction("save", _SE(js_cocos2dx_CanvasRenderingContext2D_save));
|
||||
cls->defineFunction("fillRect", _SE(js_cocos2dx_CanvasRenderingContext2D_fillRect));
|
||||
cls->defineFunction("rotate", _SE(js_cocos2dx_CanvasRenderingContext2D_rotate));
|
||||
cls->defineFunction("beginPath", _SE(js_cocos2dx_CanvasRenderingContext2D_beginPath));
|
||||
cls->defineFunction("translate", _SE(js_cocos2dx_CanvasRenderingContext2D_translate));
|
||||
cls->defineFunction("createLinearGradient", _SE(js_cocos2dx_CanvasRenderingContext2D_createLinearGradient));
|
||||
cls->defineFunction("closePath", _SE(js_cocos2dx_CanvasRenderingContext2D_closePath));
|
||||
cls->defineFinalizeFunction(_SE(js_cocos2d_CanvasRenderingContext2D_finalize));
|
||||
|
||||
@@ -15,11 +15,15 @@ SE_DECLARE_FUNC(js_cocos2dx_FileUtils_removeFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getDataFromFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_isAbsolutePath);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_renameFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_normalizePath);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getDefaultResourceRootPath);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_loadFilenameLookupDictionaryFromFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_isPopupNotify);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getValueVectorFromFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getSearchPaths);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getFileDir);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_writeToFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getOriginalSearchPaths);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_listFiles);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getValueMapFromFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_FileUtils_getFileSize);
|
||||
@@ -71,14 +75,19 @@ bool register_all_cocos2dx(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_restore);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_moveTo);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_lineTo);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_setTransform);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_stroke);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_measureText);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_scale);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_clearRect);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_transform);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_fillText);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_strokeText);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_save);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_fillRect);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_rotate);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_beginPath);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_translate);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_createLinearGradient);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_closePath);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_CanvasRenderingContext2D_CanvasRenderingContext2D);
|
||||
|
||||
@@ -3,6 +3,133 @@
|
||||
#include "scripting/js-bindings/manual/jsb_global.h"
|
||||
#include "renderer/renderer/Renderer.h"
|
||||
|
||||
se::Object* __jsb_cocos2d_renderer_ProgramLib_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_ProgramLib_class = nullptr;
|
||||
|
||||
static bool js_renderer_ProgramLib_getProgram(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::ProgramLib* cobj = (cocos2d::renderer::ProgramLib*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_ProgramLib_getProgram : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
std::string arg0;
|
||||
cocos2d::ValueMap arg1;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
ok &= seval_to_ccvaluemap(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_getProgram : Error processing arguments");
|
||||
cocos2d::renderer::Program* result = cobj->getProgram(arg0, arg1);
|
||||
ok &= native_ptr_to_seval<cocos2d::renderer::Program>((cocos2d::renderer::Program*)result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_getProgram : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_ProgramLib_getProgram)
|
||||
|
||||
static bool js_renderer_ProgramLib_define(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::ProgramLib* cobj = (cocos2d::renderer::ProgramLib*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_ProgramLib_define : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 4) {
|
||||
std::string arg0;
|
||||
std::string arg1;
|
||||
std::string arg2;
|
||||
cocos2d::ValueVector arg3;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
ok &= seval_to_std_string(args[1], &arg1);
|
||||
ok &= seval_to_std_string(args[2], &arg2);
|
||||
ok &= seval_to_ccvaluevector(args[3], &arg3);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_define : Error processing arguments");
|
||||
cobj->define(arg0, arg1, arg2, arg3);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_ProgramLib_define)
|
||||
|
||||
static bool js_renderer_ProgramLib_getKey(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::ProgramLib* cobj = (cocos2d::renderer::ProgramLib*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_ProgramLib_getKey : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
std::string arg0;
|
||||
cocos2d::ValueMap arg1;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
ok &= seval_to_ccvaluemap(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_getKey : Error processing arguments");
|
||||
unsigned int result = cobj->getKey(arg0, arg1);
|
||||
ok &= uint32_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_getKey : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_ProgramLib_getKey)
|
||||
|
||||
SE_DECLARE_FINALIZE_FUNC(js_cocos2d_renderer_ProgramLib_finalize)
|
||||
|
||||
static bool js_renderer_ProgramLib_constructor(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
const auto& args = s.args();
|
||||
cocos2d::renderer::DeviceGraphics* arg0 = nullptr;
|
||||
std::vector<cocos2d::renderer::ProgramLib::Template> arg1;
|
||||
ok &= seval_to_native_ptr(args[0], &arg0);
|
||||
ok &= seval_to_std_vector_ProgramLib_Template(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgramLib_constructor : Error processing arguments");
|
||||
cocos2d::renderer::ProgramLib* cobj = new (std::nothrow) cocos2d::renderer::ProgramLib(arg0, arg1);
|
||||
s.thisObject()->setPrivateData(cobj);
|
||||
se::NonRefNativePtrCreatedByCtorMap::emplace(cobj);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_CTOR(js_renderer_ProgramLib_constructor, __jsb_cocos2d_renderer_ProgramLib_class, js_cocos2d_renderer_ProgramLib_finalize)
|
||||
|
||||
|
||||
|
||||
|
||||
static bool js_cocos2d_renderer_ProgramLib_finalize(se::State& s)
|
||||
{
|
||||
CCLOGINFO("jsbindings: finalizing JS object %p (cocos2d::renderer::ProgramLib)", s.nativeThisObject());
|
||||
auto iter = se::NonRefNativePtrCreatedByCtorMap::find(s.nativeThisObject());
|
||||
if (iter != se::NonRefNativePtrCreatedByCtorMap::end())
|
||||
{
|
||||
se::NonRefNativePtrCreatedByCtorMap::erase(iter);
|
||||
cocos2d::renderer::ProgramLib* cobj = (cocos2d::renderer::ProgramLib*)s.nativeThisObject();
|
||||
delete cobj;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FINALIZE_FUNC(js_cocos2d_renderer_ProgramLib_finalize)
|
||||
|
||||
bool js_register_renderer_ProgramLib(se::Object* obj)
|
||||
{
|
||||
auto cls = se::Class::create("ProgramLib", obj, nullptr, _SE(js_renderer_ProgramLib_constructor));
|
||||
|
||||
cls->defineFunction("getProgram", _SE(js_renderer_ProgramLib_getProgram));
|
||||
cls->defineFunction("define", _SE(js_renderer_ProgramLib_define));
|
||||
cls->defineFunction("getKey", _SE(js_renderer_ProgramLib_getKey));
|
||||
cls->defineFinalizeFunction(_SE(js_cocos2d_renderer_ProgramLib_finalize));
|
||||
cls->install();
|
||||
JSBClassType::registerClass<cocos2d::renderer::ProgramLib>(cls);
|
||||
|
||||
__jsb_cocos2d_renderer_ProgramLib_proto = cls->getProto();
|
||||
__jsb_cocos2d_renderer_ProgramLib_class = cls;
|
||||
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
return true;
|
||||
}
|
||||
|
||||
se::Object* __jsb_cocos2d_renderer_Model_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_Model_class = nullptr;
|
||||
|
||||
@@ -276,6 +403,24 @@ bool js_register_renderer_Model(se::Object* obj)
|
||||
se::Object* __jsb_cocos2d_renderer_BaseRenderer_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_BaseRenderer_class = nullptr;
|
||||
|
||||
static bool js_renderer_BaseRenderer_getProgramLib(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::BaseRenderer* cobj = (cocos2d::renderer::BaseRenderer*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_BaseRenderer_getProgramLib : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
cocos2d::renderer::ProgramLib* result = cobj->getProgramLib();
|
||||
ok &= native_ptr_to_seval<cocos2d::renderer::ProgramLib>((cocos2d::renderer::ProgramLib*)result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_BaseRenderer_getProgramLib : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_BaseRenderer_getProgramLib)
|
||||
|
||||
static bool js_renderer_BaseRenderer_init(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
@@ -350,6 +495,7 @@ bool js_register_renderer_BaseRenderer(se::Object* obj)
|
||||
{
|
||||
auto cls = se::Class::create("Base", obj, nullptr, _SE(js_renderer_BaseRenderer_constructor));
|
||||
|
||||
cls->defineFunction("getProgramLib", _SE(js_renderer_BaseRenderer_getProgramLib));
|
||||
cls->defineFunction("init", _SE(js_renderer_BaseRenderer_init));
|
||||
cls->defineFinalizeFunction(_SE(js_cocos2d_renderer_BaseRenderer_finalize));
|
||||
cls->install();
|
||||
@@ -987,24 +1133,6 @@ bool js_register_renderer_Camera(se::Object* obj)
|
||||
se::Object* __jsb_cocos2d_renderer_Technique_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_Technique_class = nullptr;
|
||||
|
||||
static bool js_renderer_Technique_getPasses(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_Technique_getPasses : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
const cocos2d::Vector<cocos2d::renderer::Pass *>& result = cobj->getPasses();
|
||||
ok &= Vector_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_Technique_getPasses : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Technique_getPasses)
|
||||
|
||||
static bool js_renderer_Technique_getStageIDs(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
@@ -1023,6 +1151,27 @@ static bool js_renderer_Technique_getStageIDs(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Technique_getStageIDs)
|
||||
|
||||
static bool js_renderer_Technique_setPass(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_Technique_setPass : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
cocos2d::renderer::Pass* arg1 = nullptr;
|
||||
do { int32_t tmp = 0; ok &= seval_to_int32(args[0], &tmp); arg0 = (int)tmp; } while(false);
|
||||
ok &= seval_to_native_ptr(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_Technique_setPass : Error processing arguments");
|
||||
cobj->setPass(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Technique_setPass)
|
||||
|
||||
static bool js_renderer_Technique_setStages(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
@@ -1042,6 +1191,24 @@ static bool js_renderer_Technique_setStages(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Technique_setStages)
|
||||
|
||||
static bool js_renderer_Technique_getPasses(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_Technique_getPasses : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
const cocos2d::Vector<cocos2d::renderer::Pass *>& result = cobj->getPasses();
|
||||
ok &= Vector_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_Technique_getPasses : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Technique_getPasses)
|
||||
|
||||
static bool js_renderer_Technique_getParameters(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Technique* cobj = (cocos2d::renderer::Technique*)s.nativeThisObject();
|
||||
@@ -1098,9 +1265,10 @@ bool js_register_renderer_Technique(se::Object* obj)
|
||||
{
|
||||
auto cls = se::Class::create("Technique", obj, nullptr, _SE(js_renderer_Technique_constructor));
|
||||
|
||||
cls->defineFunction("getPasses", _SE(js_renderer_Technique_getPasses));
|
||||
cls->defineFunction("getStageIDs", _SE(js_renderer_Technique_getStageIDs));
|
||||
cls->defineFunction("setPass", _SE(js_renderer_Technique_setPass));
|
||||
cls->defineFunction("setStages", _SE(js_renderer_Technique_setStages));
|
||||
cls->defineFunction("getPasses", _SE(js_renderer_Technique_getPasses));
|
||||
cls->defineFunction("getParameters", _SE(js_renderer_Technique_getParameters));
|
||||
cls->defineFinalizeFunction(_SE(js_cocos2d_renderer_Technique_finalize));
|
||||
cls->install();
|
||||
@@ -2275,6 +2443,24 @@ bool js_register_renderer_Light(se::Object* obj)
|
||||
se::Object* __jsb_cocos2d_renderer_Pass_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_Pass_class = nullptr;
|
||||
|
||||
static bool js_renderer_Pass_getStencilTest(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Pass* cobj = (cocos2d::renderer::Pass*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_Pass_getStencilTest : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
bool result = cobj->getStencilTest();
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_Pass_getStencilTest : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Pass_getStencilTest)
|
||||
|
||||
static bool js_renderer_Pass_setStencilBack(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Pass* cobj = (cocos2d::renderer::Pass*)s.nativeThisObject();
|
||||
@@ -2382,6 +2568,25 @@ static bool js_renderer_Pass_setStencilBack(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Pass_setStencilBack)
|
||||
|
||||
static bool js_renderer_Pass_setStencilTest(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Pass* cobj = (cocos2d::renderer::Pass*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_Pass_setStencilTest : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
bool arg0;
|
||||
ok &= seval_to_boolean(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_Pass_setStencilTest : Error processing arguments");
|
||||
cobj->setStencilTest(arg0);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_Pass_setStencilTest)
|
||||
|
||||
static bool js_renderer_Pass_setCullMode(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::Pass* cobj = (cocos2d::renderer::Pass*)s.nativeThisObject();
|
||||
@@ -2692,7 +2897,9 @@ bool js_register_renderer_Pass(se::Object* obj)
|
||||
{
|
||||
auto cls = se::Class::create("Pass", obj, nullptr, _SE(js_renderer_Pass_constructor));
|
||||
|
||||
cls->defineFunction("getStencilTest", _SE(js_renderer_Pass_getStencilTest));
|
||||
cls->defineFunction("setStencilBack", _SE(js_renderer_Pass_setStencilBack));
|
||||
cls->defineFunction("setStencilTest", _SE(js_renderer_Pass_setStencilTest));
|
||||
cls->defineFunction("setCullMode", _SE(js_renderer_Pass_setCullMode));
|
||||
cls->defineFunction("setBlend", _SE(js_renderer_Pass_setBlend));
|
||||
cls->defineFunction("setStencilFront", _SE(js_renderer_Pass_setStencilFront));
|
||||
@@ -3111,47 +3318,6 @@ bool js_register_renderer_Scene(se::Object* obj)
|
||||
return true;
|
||||
}
|
||||
|
||||
se::Object* __jsb_cocos2d_renderer_ProgramLib_proto = nullptr;
|
||||
se::Class* __jsb_cocos2d_renderer_ProgramLib_class = nullptr;
|
||||
|
||||
static bool js_renderer_ProgamLib_getProgram(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::ProgramLib* cobj = (cocos2d::renderer::ProgramLib*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_renderer_ProgamLib_getProgam : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
std::string arg0;
|
||||
cocos2d::ValueMap arg1;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgamLib_getProgam : Error processing arguments 0");
|
||||
ok &= seval_to_ccvaluemap(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_renderer_ProgamLib_getProgam : Error processing arguments 1");
|
||||
auto result = cobj->getProgram(arg0, arg1);
|
||||
native_ptr_to_seval<cocos2d::renderer::Program>(result, &s.rval());
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_renderer_ProgamLib_getProgram)
|
||||
|
||||
bool js_register_renderer_ProgramLib(se::Object* obj)
|
||||
{
|
||||
auto cls = se::Class::create("ProgramLib", obj, nullptr, nullptr);
|
||||
|
||||
cls->defineFunction("getProgram", _SE(js_renderer_ProgamLib_getProgram));
|
||||
cls->install();
|
||||
JSBClassType::registerClass<cocos2d::renderer::ProgramLib>(cls);
|
||||
|
||||
__jsb_cocos2d_renderer_ProgramLib_proto = cls->getProto();
|
||||
__jsb_cocos2d_renderer_ProgramLib_class = cls;
|
||||
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool register_all_renderer(se::Object* obj)
|
||||
{
|
||||
// Get the ns
|
||||
@@ -3164,6 +3330,7 @@ bool register_all_renderer(se::Object* obj)
|
||||
}
|
||||
se::Object* ns = nsVal.toObject();
|
||||
|
||||
js_register_renderer_ProgramLib(ns);
|
||||
js_register_renderer_Light(ns);
|
||||
js_register_renderer_Technique(ns);
|
||||
js_register_renderer_Effect(ns);
|
||||
@@ -3175,7 +3342,6 @@ bool register_all_renderer(se::Object* obj)
|
||||
js_register_renderer_Model(ns);
|
||||
js_register_renderer_ForwardRenderer(ns);
|
||||
js_register_renderer_View(ns);
|
||||
js_register_renderer_ProgramLib(ns);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,16 @@
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
|
||||
extern se::Object* __jsb_cocos2d_renderer_ProgramLib_proto;
|
||||
extern se::Class* __jsb_cocos2d_renderer_ProgramLib_class;
|
||||
|
||||
bool js_register_cocos2d_renderer_ProgramLib(se::Object* obj);
|
||||
bool register_all_renderer(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_renderer_ProgramLib_getProgram);
|
||||
SE_DECLARE_FUNC(js_renderer_ProgramLib_define);
|
||||
SE_DECLARE_FUNC(js_renderer_ProgramLib_getKey);
|
||||
SE_DECLARE_FUNC(js_renderer_ProgramLib_ProgramLib);
|
||||
|
||||
extern se::Object* __jsb_cocos2d_renderer_Model_proto;
|
||||
extern se::Class* __jsb_cocos2d_renderer_Model_class;
|
||||
|
||||
@@ -27,6 +37,7 @@ extern se::Class* __jsb_cocos2d_renderer_BaseRenderer_class;
|
||||
|
||||
bool js_register_cocos2d_renderer_BaseRenderer(se::Object* obj);
|
||||
bool register_all_renderer(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_renderer_BaseRenderer_getProgramLib);
|
||||
SE_DECLARE_FUNC(js_renderer_BaseRenderer_init);
|
||||
SE_DECLARE_FUNC(js_renderer_BaseRenderer_BaseRenderer);
|
||||
|
||||
@@ -80,9 +91,10 @@ extern se::Class* __jsb_cocos2d_renderer_Technique_class;
|
||||
|
||||
bool js_register_cocos2d_renderer_Technique(se::Object* obj);
|
||||
bool register_all_renderer(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_getPasses);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_getStageIDs);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_setPass);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_setStages);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_getPasses);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_getParameters);
|
||||
SE_DECLARE_FUNC(js_renderer_Technique_Technique);
|
||||
|
||||
@@ -163,7 +175,9 @@ extern se::Class* __jsb_cocos2d_renderer_Pass_class;
|
||||
|
||||
bool js_register_cocos2d_renderer_Pass(se::Object* obj);
|
||||
bool register_all_renderer(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_getStencilTest);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_setStencilBack);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_setStencilTest);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_setCullMode);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_setBlend);
|
||||
SE_DECLARE_FUNC(js_renderer_Pass_setStencilFront);
|
||||
@@ -195,8 +209,3 @@ SE_DECLARE_FUNC(js_renderer_Scene_addLight);
|
||||
SE_DECLARE_FUNC(js_renderer_Scene_removeLight);
|
||||
SE_DECLARE_FUNC(js_renderer_Scene_Scene);
|
||||
|
||||
extern se::Object* __jsb_cocos2d_renderer_ProgramLib_proto;
|
||||
extern se::Class* __jsb_cocos2d_renderer_ProgramLib_class;
|
||||
bool js_register_renderer_ProgramLib(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_renderer_ProgramLib_getProgram);
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ namespace cocos2d
|
||||
|
||||
void EventDispatcher::dispatchTouchEvent(const struct TouchEvent& touchEvent)
|
||||
{
|
||||
se::AutoHandleScope scope;
|
||||
assert(_inited);
|
||||
if (_jsbNameSpaceObj == nullptr)
|
||||
{
|
||||
@@ -152,7 +153,7 @@ void EventDispatcher::dispatchTickEvent(float dt)
|
||||
|
||||
if (_tickVal.isUndefined())
|
||||
{
|
||||
jsb_run_script("jsb/index.js", &_tickVal);
|
||||
se::ScriptEngine::getInstance()->getGlobalObject()->getProperty("gameTick", &_tickVal);
|
||||
}
|
||||
|
||||
prevTime = std::chrono::steady_clock::now();
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <JavaScriptCore/JavaScriptCore.h>
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
NSString *JSValueToNSString( JSContextRef ctx, JSValueRef v );
|
||||
JSValueRef NSStringToJSValue( JSContextRef ctx, NSString *string );
|
||||
double JSValueToNumberFast( JSContextRef ctx, JSValueRef v );
|
||||
void JSValueUnprotectSafe( JSContextRef ctx, JSValueRef v );
|
||||
JSValueRef NSObjectToJSValue( JSContextRef ctx, NSObject *obj );
|
||||
NSObject *JSValueToNSObject( JSContextRef ctx, JSValueRef value );
|
||||
|
||||
static inline void *JSValueGetPrivate(JSValueRef v) {
|
||||
// On 64bit systems we can not safely call JSObjectGetPrivate with any
|
||||
// JSValueRef. Doing so with immediate values (numbers, null, bool,
|
||||
// undefined) will crash the app. So we check for these first.
|
||||
|
||||
#if __LP64__
|
||||
return !((int64_t)v & 0xffff000000000002ll)
|
||||
? JSObjectGetPrivate((JSObjectRef)v)
|
||||
: NULL;
|
||||
#else
|
||||
return JSObjectGetPrivate((JSObjectRef)v);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,173 @@
|
||||
#import "EJConvert.h"
|
||||
|
||||
NSString *JSValueToNSString( JSContextRef ctx, JSValueRef v ) {
|
||||
JSStringRef jsString = JSValueToStringCopy( ctx, v, NULL );
|
||||
if( !jsString ) return nil;
|
||||
|
||||
NSString *string = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, jsString );
|
||||
[string autorelease];
|
||||
JSStringRelease( jsString );
|
||||
|
||||
return string;
|
||||
}
|
||||
|
||||
JSValueRef NSStringToJSValue( JSContextRef ctx, NSString *string ) {
|
||||
JSStringRef jstr = JSStringCreateWithCFString((CFStringRef)string);
|
||||
JSValueRef ret = JSValueMakeString(ctx, jstr);
|
||||
JSStringRelease(jstr);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
// JSValueToNumberFast blindly assumes that the given JSValueRef is a
|
||||
// a number. Everything else will be silently converted to 0.
|
||||
// This functions comes in a 64bit and 32bit flavor, since the NaN-Boxing
|
||||
// in JSC works a bit differently on each platforms. For an explanation
|
||||
// of the taggging refer to JSC/runtime/JSCJSValue.h
|
||||
// The 32bit version just calls the normal JSValueToNumber() function
|
||||
// and is thus a lot slower.
|
||||
|
||||
double JSValueToNumberFast(JSContextRef ctx, JSValueRef v) {
|
||||
#if __LP64__ // arm64 version
|
||||
union {
|
||||
int64_t asInt64;
|
||||
double asDouble;
|
||||
struct { int32_t asInt; int32_t tag; } asBits;
|
||||
} taggedValue = { .asInt64 = (int64_t)v };
|
||||
|
||||
#define DoubleEncodeOffset 0x1000000000000ll
|
||||
#define TagTypeNumber 0xffff0000
|
||||
#define ValueTrue 0x7
|
||||
|
||||
if( (taggedValue.asBits.tag & TagTypeNumber) == TagTypeNumber ) {
|
||||
return taggedValue.asBits.asInt;
|
||||
}
|
||||
else if( taggedValue.asBits.tag & TagTypeNumber ) {
|
||||
taggedValue.asInt64 -= DoubleEncodeOffset;
|
||||
return taggedValue.asDouble;
|
||||
}
|
||||
else if( taggedValue.asBits.asInt == ValueTrue ) {
|
||||
return 1.0;
|
||||
}
|
||||
else {
|
||||
return 0; // false, undefined, null, object
|
||||
}
|
||||
#else // armv7 version
|
||||
return JSValueToNumber(ctx, v, NULL);
|
||||
#endif
|
||||
}
|
||||
|
||||
void JSValueUnprotectSafe( JSContextRef ctx, JSValueRef v ) {
|
||||
if( ctx && v ) {
|
||||
JSValueUnprotect(ctx, v);
|
||||
}
|
||||
}
|
||||
|
||||
JSValueRef NSObjectToJSValue( JSContextRef ctx, NSObject *obj ) {
|
||||
JSValueRef ret = NULL;
|
||||
|
||||
// String
|
||||
if( [obj isKindOfClass:NSString.class] ) {
|
||||
ret = NSStringToJSValue(ctx, (NSString *)obj);
|
||||
}
|
||||
|
||||
// Number or Bool
|
||||
else if( [obj isKindOfClass:NSNumber.class] ) {
|
||||
NSNumber *number = (NSNumber *)obj;
|
||||
if( strcmp(number.objCType, @encode(BOOL)) == 0 ) {
|
||||
ret = JSValueMakeBoolean(ctx, number.boolValue);
|
||||
}
|
||||
else {
|
||||
ret = JSValueMakeNumber(ctx, number.doubleValue);
|
||||
}
|
||||
}
|
||||
|
||||
// Date
|
||||
else if( [obj isKindOfClass:NSDate.class] ) {
|
||||
NSDate *date = (NSDate *)obj;
|
||||
JSValueRef timestamp = JSValueMakeNumber(ctx, date.timeIntervalSince1970 * 1000.0);
|
||||
ret = JSObjectMakeDate(ctx, 1, ×tamp, NULL);
|
||||
}
|
||||
|
||||
// Array
|
||||
else if( [obj isKindOfClass:NSArray.class] ) {
|
||||
NSArray *array = (NSArray *)obj;
|
||||
JSValueRef *args = malloc(array.count * sizeof(JSValueRef));
|
||||
for( int i = 0; i < array.count; i++ ) {
|
||||
args[i] = NSObjectToJSValue(ctx, array[i] );
|
||||
}
|
||||
ret = JSObjectMakeArray(ctx, array.count, args, NULL);
|
||||
free(args);
|
||||
}
|
||||
|
||||
// Dictionary
|
||||
else if( [obj isKindOfClass:NSDictionary.class] ) {
|
||||
NSDictionary *dict = (NSDictionary *)obj;
|
||||
ret = JSObjectMake(ctx, NULL, NULL);
|
||||
for( NSString *key in dict ) {
|
||||
JSStringRef jsKey = JSStringCreateWithUTF8CString(key.UTF8String);
|
||||
JSValueRef value = NSObjectToJSValue(ctx, dict[key]);
|
||||
JSObjectSetProperty(ctx, (JSObjectRef)ret, jsKey, value, NULL, NULL);
|
||||
JSStringRelease(jsKey);
|
||||
}
|
||||
}
|
||||
|
||||
return ret ? ret : JSValueMakeNull(ctx);
|
||||
}
|
||||
|
||||
NSObject *JSValueToNSObject( JSContextRef ctx, JSValueRef value ) {
|
||||
JSType type = JSValueGetType(ctx, value);
|
||||
|
||||
switch( type ) {
|
||||
case kJSTypeString: return JSValueToNSString(ctx, value);
|
||||
case kJSTypeBoolean: return [NSNumber numberWithBool:JSValueToBoolean(ctx, value)];
|
||||
case kJSTypeNumber: return [NSNumber numberWithDouble:JSValueToNumberFast(ctx, value)];
|
||||
case kJSTypeNull: return nil;
|
||||
case kJSTypeUndefined: return nil;
|
||||
case kJSTypeObject: break;
|
||||
}
|
||||
|
||||
if( type == kJSTypeObject ) {
|
||||
JSObjectRef jsObj = (JSObjectRef)value;
|
||||
|
||||
// Get the Array constructor to check if this Object is an Array
|
||||
JSStringRef arrayName = JSStringCreateWithUTF8CString("Array");
|
||||
JSObjectRef arrayConstructor = (JSObjectRef)JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), arrayName, NULL);
|
||||
JSStringRelease(arrayName);
|
||||
|
||||
if( JSValueIsInstanceOfConstructor(ctx, jsObj, arrayConstructor, NULL) ) {
|
||||
// Array
|
||||
JSStringRef lengthName = JSStringCreateWithUTF8CString("length");
|
||||
int count = JSValueToNumberFast(ctx, JSObjectGetProperty(ctx, jsObj, lengthName, NULL));
|
||||
JSStringRelease(lengthName);
|
||||
|
||||
NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
|
||||
for( int i = 0; i < count; i++ ) {
|
||||
NSObject *obj = JSValueToNSObject(ctx, JSObjectGetPropertyAtIndex(ctx, jsObj, i, NULL));
|
||||
[array addObject:(obj ? obj : NSNull.null)];
|
||||
}
|
||||
return array;
|
||||
}
|
||||
else {
|
||||
// Plain Object
|
||||
JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames(ctx, jsObj);
|
||||
size_t count = JSPropertyNameArrayGetCount(properties);
|
||||
|
||||
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:count];
|
||||
for( size_t i = 0; i < count; i++ ) {
|
||||
JSStringRef jsName = JSPropertyNameArrayGetNameAtIndex(properties, i);
|
||||
NSObject *obj = JSValueToNSObject(ctx, JSObjectGetProperty(ctx, jsObj, jsName, NULL));
|
||||
|
||||
NSString *name = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, jsName );
|
||||
dict[name] = obj ? obj : NSNull.null;
|
||||
[name release];
|
||||
}
|
||||
|
||||
JSPropertyNameArrayRelease(properties);
|
||||
return dict;
|
||||
}
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <JavaScriptCore/JavaScriptCore.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*!
|
||||
@enum JSType
|
||||
@abstract A constant identifying the Typed Array type of a JSValue.
|
||||
@constant kEJJSTypedArrayTypeNone Not a Typed Array.
|
||||
@constant kEJJSTypedArrayTypeInt8Array Int8Array
|
||||
@constant kEJJSTypedArrayTypeInt16Array Int16Array
|
||||
@constant kEJJSTypedArrayTypeInt32Array Int32Array
|
||||
@constant kEJJSTypedArrayTypeUint8Array Int8Array
|
||||
@constant kEJJSTypedArrayTypeUint8ClampedArray Int8ClampedArray
|
||||
@constant kEJJSTypedArrayTypeUint16Array Uint16Array
|
||||
@constant kEJJSTypedArrayTypeUint32Array Uint32Array
|
||||
@constant kEJJSTypedArrayTypeFloat32Array Float32Array
|
||||
@constant kEJJSTypedArrayTypeFloat64Array Float64Array
|
||||
@constant kEJJSTypedArrayTypeArrayBuffer ArrayBuffer
|
||||
*/
|
||||
typedef enum {
|
||||
kEJJSTypedArrayTypeNone = 0,
|
||||
kEJJSTypedArrayTypeInt8Array = 1,
|
||||
kEJJSTypedArrayTypeInt16Array = 2,
|
||||
kEJJSTypedArrayTypeInt32Array = 3,
|
||||
kEJJSTypedArrayTypeUint8Array = 4,
|
||||
kEJJSTypedArrayTypeUint8ClampedArray = 5,
|
||||
kEJJSTypedArrayTypeUint16Array = 6,
|
||||
kEJJSTypedArrayTypeUint32Array = 7,
|
||||
kEJJSTypedArrayTypeFloat32Array = 8,
|
||||
kEJJSTypedArrayTypeFloat64Array = 9,
|
||||
kEJJSTypedArrayTypeArrayBuffer = 10
|
||||
} EJJSTypedArrayType;
|
||||
|
||||
/*!
|
||||
@function
|
||||
@abstract Setup the JSContext for use of the Typed Array functions.
|
||||
@param ctx The execution context to use
|
||||
*/
|
||||
void EJJSContextPrepareTypedArrayAPI(JSContextRef ctx);
|
||||
|
||||
/*!
|
||||
@function
|
||||
@abstract Returns a JavaScript value's Typed Array type
|
||||
@param ctx The execution context to use.
|
||||
@param value The JSObject whose Typed Array type you want to obtain.
|
||||
@result A value of type EJJSTypedArrayType that identifies value's Typed Array type
|
||||
*/
|
||||
EJJSTypedArrayType EJJSObjectGetTypedArrayType(JSContextRef ctx, JSObjectRef object);
|
||||
|
||||
/*!
|
||||
@function
|
||||
@abstract Creates an empty JavaScript Typed Array with the given number of elements
|
||||
@param ctx The execution context to use.
|
||||
@param arrayType A value of type EJJSTypedArrayType identifying the type of array you want to create
|
||||
@param numElements The number of elements for the array.
|
||||
@result A JSObjectRef that is a Typed Array or NULL if there was an error
|
||||
*/
|
||||
JSObjectRef EJJSObjectMakeTypedArray(JSContextRef ctx, EJJSTypedArrayType arrayType, size_t numElements);
|
||||
|
||||
/*!
|
||||
@function
|
||||
@abstract Returns a copy of the Typed Array's data
|
||||
@param ctx The execution context to use.
|
||||
@param value The JSObject whose Typed Array data you want to obtain.
|
||||
@result A copy of the Typed Array's data or NULL if the JSObject is not a Typed Array
|
||||
*/
|
||||
NSMutableData *EJJSObjectGetTypedArrayData(JSContextRef ctx, JSObjectRef object);
|
||||
|
||||
/*!
|
||||
@function
|
||||
@abstract Replaces a Typed Array's data
|
||||
@param ctx The execution context to use.
|
||||
@param value The JSObject whose Typed Array data you want to replace
|
||||
*/
|
||||
void EJJSObjectSetTypedArrayData(JSContextRef ctx, JSObjectRef object, NSData *data);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
#import "EJConvertTypedArray.h"
|
||||
#import "EJConvert.h"
|
||||
|
||||
#if defined __ARM_NEON__
|
||||
#include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
// These functions deal with getting and setting a JavaScript Typed Array's data.
|
||||
// The process in which this is done is extremely backwards, prohibitively
|
||||
// memory inefficient and painfully slow.
|
||||
|
||||
// JavaScriptCore still doesn't have an API to deal with Typed Arrays directly
|
||||
// and nobody seems to care. See this WebKit bug for the details:
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=120112
|
||||
|
||||
// The naive method of getting the array's data would be to read the "length"
|
||||
// property and call JSObjectGetPropertyAtIndex() for each element. This function
|
||||
// returns a JSValue and since the array's data is just a raw memory pointer
|
||||
// internally, this JSValue has be constructed first by JSC. Afterwards this
|
||||
// JSValue has to be converted back into an int and stored in a native buffer.
|
||||
// This ordeal takes about 1200ms per megabyte on an iPhone5S.
|
||||
|
||||
// So, instead of extracting each byte on its own, we create Int32 view on the
|
||||
// Array, so that we can extract 4 bytes at a time. Now, the fastest method to
|
||||
// get to the values is to call a function with .apply(null, theInt32Array).
|
||||
// This causes the typed array to be converted into plain JSValues - we can then
|
||||
// iterate all function arguments and convert each JSValue into a Int32.
|
||||
|
||||
// There's one big caveat, though: a function can only be called with 64k
|
||||
// arguments at once, or it will blow the stack. So we have to divide the Int32
|
||||
// Array into smaller subarrays and convert the data in chunks.
|
||||
|
||||
// Setting the Array's data works about the same. We can create a plain JS
|
||||
// Array in reasonable time by treating the data as 32bit ints. This plain
|
||||
// Array can then be used to call .set() on an Int32 View of the Typed Array.
|
||||
|
||||
// To be able to quickly determine the type of a typed array, we install an
|
||||
// enum with the type id ("__ejTypedArrayType") onto each array constructor's
|
||||
// prototype.
|
||||
|
||||
// This all brings the time down to about 7ms per megabyte for reading and about
|
||||
// 20ms per megabyte for writing. Even though this 7ms/MB number may not sound
|
||||
// all too bad, keep in mind that it's still 7ms slower than what we would have
|
||||
// with a better API.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Array Types to constructor names. We need to obtain the Constructors from
|
||||
// the JSGlobalObject when creating Typed Arrays and when attaching our methods
|
||||
// to them.
|
||||
|
||||
const static char *ConstructorNames[] = {
|
||||
[kEJJSTypedArrayTypeNone] = NULL,
|
||||
[kEJJSTypedArrayTypeInt8Array] = "Int8Array",
|
||||
[kEJJSTypedArrayTypeInt16Array] = "Int16Array",
|
||||
[kEJJSTypedArrayTypeInt32Array] = "Int32Array",
|
||||
[kEJJSTypedArrayTypeUint8Array] = "Uint8Array",
|
||||
[kEJJSTypedArrayTypeUint8ClampedArray] = "Uint8ClampedArray",
|
||||
[kEJJSTypedArrayTypeUint16Array] = "Uint16Array",
|
||||
[kEJJSTypedArrayTypeUint32Array] = "Uint32Array",
|
||||
[kEJJSTypedArrayTypeFloat32Array] = "Float32Array",
|
||||
[kEJJSTypedArrayTypeFloat64Array] = "Float64Array",
|
||||
[kEJJSTypedArrayTypeArrayBuffer] = "ArrayBuffer"
|
||||
};
|
||||
|
||||
|
||||
// Data from Typed Arrays smaller than CopyInChunksThreshold will be extracted
|
||||
// one byte at a time.
|
||||
|
||||
const static int CopyInChunksThreshold = 32;
|
||||
|
||||
|
||||
// For large arrays, copy the data in Chunks of 16k elements, so that we don't
|
||||
// blow the stack.
|
||||
|
||||
const static int CopyChunkSize = 0x4000;
|
||||
|
||||
|
||||
|
||||
// Hobo version to get an Int32 from a JSValueRef. This is even faster than
|
||||
// JSValueToNumberFast() because it blindly assumes the value is an Int32.
|
||||
// A number stored as double will produce a bogus Int value. JSC stores all
|
||||
// values that are outside of the Int32 range as double.
|
||||
|
||||
// This function is only fast on 64bit systems. On 32bit systems we can't
|
||||
// easily access the integer value.
|
||||
// See JavaScriptCore/runtime/JSCJSValue.h for an explanation of the NaN-
|
||||
// boxing used in JSC.
|
||||
|
||||
// Use with extreme caution!
|
||||
|
||||
static inline int32_t GetInt32(JSContextRef ctx, JSValueRef v) {
|
||||
#if __LP64__
|
||||
return (int32_t)(0x00000000ffffffffll & (uint64_t)v);
|
||||
#else
|
||||
return JSValueToNumber(ctx, v, NULL);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
// Hobo version to create an Int32 fast. Falls back to JSValueMakeNumber()
|
||||
// on 32bit systems.
|
||||
|
||||
static inline JSValueRef MakeInt32(JSContextRef ctx, int32_t number) {
|
||||
#if __LP64__
|
||||
return (0xffff000000000000ll | (uint64_t)number);
|
||||
#else
|
||||
return JSValueMakeNumber(ctx, number);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
// Shorthand to get a property by name
|
||||
|
||||
static JSValueRef GetPropertyNamed(JSContextRef ctx, JSObjectRef object, const char *name) {
|
||||
JSStringRef jsPropertyName = JSStringCreateWithUTF8CString(name);
|
||||
JSValueRef value = JSObjectGetProperty(ctx, object, jsPropertyName, NULL);
|
||||
JSStringRelease(jsPropertyName);
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
// Shorthand to get the Constructor for the given EJJSTypedArrayType
|
||||
|
||||
static JSObjectRef GetConstructor(JSContextRef ctx, EJJSTypedArrayType type) {
|
||||
if( type <= kEJJSTypedArrayTypeNone || type > kEJJSTypedArrayTypeArrayBuffer ) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char *constructorName = ConstructorNames[type];
|
||||
JSObjectRef global = JSContextGetGlobalObject(ctx);
|
||||
return (JSObjectRef)GetPropertyNamed(ctx, global, constructorName);
|
||||
}
|
||||
|
||||
|
||||
// Create a typed array view from another typed array or arraybuffer
|
||||
|
||||
static JSObjectRef GetView(JSContextRef ctx, JSObjectRef object, EJJSTypedArrayType type, size_t count) {
|
||||
EJJSTypedArrayType currentType = EJJSObjectGetTypedArrayType(ctx, object);
|
||||
if( currentType == kEJJSTypedArrayTypeNone ) {
|
||||
return NULL;
|
||||
}
|
||||
else if( currentType == type ) {
|
||||
return object;
|
||||
}
|
||||
|
||||
JSValueRef args[3];
|
||||
if( currentType == kEJJSTypedArrayTypeArrayBuffer ) {
|
||||
args[0] = object;
|
||||
args[1] = MakeInt32(ctx, 0);
|
||||
args[2] = MakeInt32(ctx, (int)count);
|
||||
}
|
||||
else {
|
||||
args[0] = GetPropertyNamed(ctx, object, "buffer");
|
||||
args[1] = GetPropertyNamed(ctx, object, "byteOffset");
|
||||
args[2] = MakeInt32(ctx, (int)count);
|
||||
}
|
||||
JSObjectRef constructor = GetConstructor(ctx, type);
|
||||
return JSObjectCallAsConstructor(ctx, constructor, 3, args, NULL);
|
||||
}
|
||||
|
||||
|
||||
// The callback called from JSObjectGetTypedArrayData with chunks of data. This writes
|
||||
// into the state's data.
|
||||
|
||||
typedef struct {
|
||||
int32_t *currentDataPtr;
|
||||
JSObjectRef jsGetCallback;
|
||||
JSObjectRef jsGetCallbackApply;
|
||||
} AppendDataCallbackState;
|
||||
|
||||
static JSValueRef AppendDataCallback(
|
||||
JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
|
||||
size_t argc, const JSValueRef argv[], JSValueRef* exception
|
||||
) {
|
||||
AppendDataCallbackState *state = JSObjectGetPrivate(thisObject);
|
||||
int32_t *dst = state->currentDataPtr;
|
||||
int remainderStart = 0;
|
||||
|
||||
// On 64bit systems where ARM_NEON instructions are available we can use
|
||||
// some SIMD intrinsics to extract the lower 32bit of each JSValueRef.
|
||||
// Hopefully the JSValueRef encodes an Int32 so the lower 32bit corresponds
|
||||
// to that Int32 exactly.
|
||||
|
||||
#if __LP64__ && defined __ARM_NEON__
|
||||
// Iterate over the arguments in packs of 4.
|
||||
// Load arguments as 2 lanes of 4 int32 values and store the first
|
||||
// lane (the lower 32bit) into the dst buffer.
|
||||
|
||||
int argPacks4 = (int)argc/4;
|
||||
int32_t *src = (int32_t*)argv;
|
||||
|
||||
for(int i = 0; i < argPacks4; i++ ) {
|
||||
const int32x4x2_t lanes32 = vld2q_s32(src);
|
||||
vst1q_s32(dst, lanes32.val[0]);
|
||||
src += 8;
|
||||
dst += 4;
|
||||
}
|
||||
remainderStart = argPacks4 * 4;
|
||||
#endif
|
||||
|
||||
for( int i = remainderStart; i < argc; i++ ) {
|
||||
*(dst++) = GetInt32(ctx, argv[i]);
|
||||
}
|
||||
|
||||
state->currentDataPtr += argc;
|
||||
return MakeInt32(ctx, (int)argc);
|
||||
}
|
||||
|
||||
|
||||
// To store the AppendDataCallbackState and access it _per context_, we create
|
||||
// a plain JSObject where we can store a pointer to the state in the private
|
||||
// data.
|
||||
|
||||
static void FinalizeAppendDataCallbackState(JSObjectRef object) {
|
||||
AppendDataCallbackState *state = JSObjectGetPrivate(object);
|
||||
free(state);
|
||||
}
|
||||
|
||||
static JSObjectRef CreateAppendDataCallbackState(JSContextRef ctx) {
|
||||
// Create a JS function that calls the AppendDataCallback
|
||||
JSObjectRef jsAppendDataCallback = JSObjectMakeFunctionWithCallback(ctx, NULL, AppendDataCallback);
|
||||
JSValueProtect(ctx, jsAppendDataCallback);
|
||||
|
||||
// Allocate and create the state and attach the AppendDataCallback
|
||||
// function and its .apply property.
|
||||
AppendDataCallbackState *state = malloc(sizeof(AppendDataCallbackState));
|
||||
state->currentDataPtr = NULL;
|
||||
state->jsGetCallback = jsAppendDataCallback;
|
||||
state->jsGetCallbackApply = (JSObjectRef)GetPropertyNamed(ctx, jsAppendDataCallback, "apply");
|
||||
|
||||
|
||||
// Create the empty js object that holds the state in its Private data
|
||||
JSClassDefinition internalStateClassDef = kJSClassDefinitionEmpty;
|
||||
internalStateClassDef.finalize = FinalizeAppendDataCallbackState;
|
||||
|
||||
JSClassRef internalStateClass = JSClassCreate(&internalStateClassDef);
|
||||
JSObjectRef internalStateObject = JSObjectMake(ctx, internalStateClass, state);
|
||||
JSClassRelease(internalStateClass);
|
||||
return internalStateObject;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void EJJSContextPrepareTypedArrayAPI(JSContextRef ctx) {
|
||||
// The __ejTypedArrayType property is read only, not enumerable
|
||||
JSPropertyAttributes attributes =
|
||||
kJSPropertyAttributeReadOnly |
|
||||
kJSPropertyAttributeDontEnum |
|
||||
kJSPropertyAttributeDontDelete;
|
||||
|
||||
// Install the __ejTypedArrayType property on each Typed Array prototype
|
||||
JSStringRef jsTypeName = JSStringCreateWithUTF8CString("__ejTypedArrayType");
|
||||
|
||||
for( int type = kEJJSTypedArrayTypeInt8Array; type <= kEJJSTypedArrayTypeArrayBuffer; type++ ) {
|
||||
JSObjectRef jsConstructor = GetConstructor(ctx, type);
|
||||
JSObjectRef jsPrototype = (JSObjectRef)GetPropertyNamed(ctx, jsConstructor, "prototype");
|
||||
|
||||
JSValueRef jsType = MakeInt32(ctx, type);
|
||||
JSObjectSetProperty(ctx, jsPrototype, jsTypeName, jsType, attributes, NULL);
|
||||
}
|
||||
|
||||
JSStringRelease(jsTypeName);
|
||||
|
||||
|
||||
// Create the state object for the AppendData Callback and attach it to the global
|
||||
// object
|
||||
JSObjectRef jsCallbackStateObject = CreateAppendDataCallbackState(ctx);
|
||||
|
||||
JSStringRef jsInternalStateName = JSStringCreateWithUTF8CString("__ejTypedArrayState");
|
||||
JSObjectRef global = JSContextGetGlobalObject(ctx);
|
||||
JSObjectSetProperty(ctx, global, jsInternalStateName, jsCallbackStateObject, attributes, NULL);
|
||||
JSStringRelease(jsInternalStateName);
|
||||
}
|
||||
|
||||
|
||||
EJJSTypedArrayType EJJSObjectGetTypedArrayType(JSContextRef ctx, JSObjectRef object) {
|
||||
JSValueRef jsType = GetPropertyNamed(ctx, object, "__ejTypedArrayType");
|
||||
return jsType ? GetInt32(ctx, jsType) : kEJJSTypedArrayTypeNone;
|
||||
}
|
||||
|
||||
JSObjectRef EJJSObjectMakeTypedArray(JSContextRef ctx, EJJSTypedArrayType arrayType, size_t numElements) {
|
||||
JSObjectRef jsConstructor = GetConstructor(ctx, arrayType);
|
||||
if( !jsConstructor ) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JSValueRef jsNumElements = MakeInt32(ctx, (int)numElements);
|
||||
return JSObjectCallAsConstructor(ctx, jsConstructor, 1, (JSValueRef[]){jsNumElements}, NULL);
|
||||
}
|
||||
|
||||
|
||||
NSMutableData *EJJSObjectGetTypedArrayData(JSContextRef ctx, JSObjectRef object) {
|
||||
size_t length = GetInt32(ctx, GetPropertyNamed(ctx, object, "byteLength"));
|
||||
if( !length ) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size_t int32Count = length / 4;
|
||||
size_t uint8Count = length % 4;
|
||||
|
||||
// For very small typed arrays it's faster to read all bytes individually
|
||||
// instead of doing the callback dance.
|
||||
if( length < CopyInChunksThreshold ) {
|
||||
int32Count = 0;
|
||||
uint8Count = length;
|
||||
}
|
||||
|
||||
NSMutableData *data = [NSMutableData dataWithLength:length];
|
||||
|
||||
// Read data in large chunks of 32bit values
|
||||
if( int32Count ) {
|
||||
JSObjectRef int32View = GetView(ctx, object, kEJJSTypedArrayTypeInt32Array, int32Count);
|
||||
if( !int32View ) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JSObjectRef jsState = (JSObjectRef)GetPropertyNamed(ctx, JSContextGetGlobalObject(ctx), "__ejTypedArrayState");
|
||||
AppendDataCallbackState *state = JSObjectGetPrivate(jsState);
|
||||
state->currentDataPtr = data.mutableBytes;
|
||||
|
||||
|
||||
// If the whole data is smaller than the chunk size, we only have to call our callback once, otherwise
|
||||
// we have to create subarrays and call the callback with these.
|
||||
if( int32Count < CopyChunkSize ) {
|
||||
JSValueRef getArgs[] = {jsState, int32View};
|
||||
JSObjectCallAsFunction(ctx, state->jsGetCallbackApply, state->jsGetCallback, 2, getArgs, NULL);
|
||||
}
|
||||
else {
|
||||
JSObjectRef subarrayFunc = (JSObjectRef)GetPropertyNamed(ctx, int32View, "subarray");
|
||||
|
||||
for( int i = 0; i < int32Count; i+= CopyChunkSize) {
|
||||
JSValueRef subarrayArgs[] = {MakeInt32(ctx, i), MakeInt32(ctx, i + CopyChunkSize)};
|
||||
JSObjectRef jsSubarray = (JSObjectRef)JSObjectCallAsFunction(ctx, subarrayFunc, int32View, 2, subarrayArgs, NULL);
|
||||
|
||||
JSValueRef getArgs[] = {jsState, jsSubarray};
|
||||
JSObjectCallAsFunction(ctx, state->jsGetCallbackApply, state->jsGetCallback, 2, getArgs, NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read remaining bytes directly
|
||||
if( uint8Count ) {
|
||||
uint8_t *values8 = data.mutableBytes;
|
||||
JSObjectRef uint8View = GetView(ctx, object, kEJJSTypedArrayTypeUint8Array, length);
|
||||
for( int i = 0; i < uint8Count; i++ ) {
|
||||
int index = (int)int32Count * 4 + i;
|
||||
values8[index] = GetInt32(ctx, JSObjectGetPropertyAtIndex(ctx, uint8View, index, NULL));
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
void EJJSObjectSetTypedArrayData(JSContextRef ctx, JSObjectRef object, NSData *data) {
|
||||
size_t int32Count = data.length / 4;
|
||||
size_t uint8Count = data.length % 4;
|
||||
|
||||
if( int32Count ) {
|
||||
JSObjectRef int32View = GetView(ctx, object, kEJJSTypedArrayTypeInt32Array, int32Count);
|
||||
if( !int32View ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Construct the JSValues and create the plain JSArray
|
||||
JSValueRef *jsValues = malloc(int32Count * sizeof(JSValueRef));
|
||||
|
||||
const int32_t *values32 = data.bytes;
|
||||
for(int i = 0; i < int32Count; i++) {
|
||||
jsValues[i] = MakeInt32(ctx, values32[i]);
|
||||
}
|
||||
JSObjectRef jsArray = JSObjectMakeArray(ctx, int32Count, jsValues, NULL);
|
||||
|
||||
free(jsValues);
|
||||
|
||||
// Call the .set() function on the Typed Array
|
||||
JSObjectRef setFunction = (JSObjectRef)GetPropertyNamed(ctx, int32View, "set");
|
||||
JSObjectCallAsFunction(ctx, setFunction, int32View, 1, (JSValueRef[]){jsArray}, NULL);
|
||||
}
|
||||
|
||||
// Set remaining bytes directly
|
||||
if( uint8Count ) {
|
||||
const uint8_t *values8 = data.bytes;
|
||||
JSObjectRef uint8View = GetView(ctx, object, kEJJSTypedArrayTypeUint8Array, data.length);
|
||||
for( int i = 0; i < uint8Count; i++ ) {
|
||||
int index = (int)int32Count * 4 + i;
|
||||
JSObjectSetPropertyAtIndex(ctx, uint8View, index, MakeInt32(ctx, values8[index]), NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -394,9 +394,6 @@ namespace se {
|
||||
void* _privateData;
|
||||
JSObjectFinalizeCallback _finalizeCb;
|
||||
|
||||
mutable uint8_t* _arrayBuffer;
|
||||
mutable size_t _arrayBufferSize;
|
||||
|
||||
uint32_t _rootCount;
|
||||
uint32_t _currentVMId;
|
||||
#if SE_DEBUG > 0
|
||||
|
||||
+138
-264
@@ -32,6 +32,8 @@
|
||||
#include "PlatformUtils.h"
|
||||
#include "../MappingUtils.hpp"
|
||||
|
||||
#include "EJConvertTypedArray.h"
|
||||
|
||||
namespace se {
|
||||
|
||||
namespace {
|
||||
@@ -60,8 +62,6 @@ namespace se {
|
||||
, _obj(nullptr)
|
||||
, _privateData(nullptr)
|
||||
, _finalizeCb(nullptr)
|
||||
, _arrayBuffer(nullptr)
|
||||
, _arrayBufferSize(0)
|
||||
, _rootCount(0)
|
||||
#if SE_DEBUG > 0
|
||||
, _id(++__id)
|
||||
@@ -75,10 +75,6 @@ namespace se {
|
||||
Object::~Object()
|
||||
{
|
||||
_cleanup();
|
||||
if (_arrayBuffer != nullptr)
|
||||
{
|
||||
free(_arrayBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
Object* Object::createPlainObject()
|
||||
@@ -127,55 +123,19 @@ namespace se {
|
||||
}
|
||||
|
||||
Object* obj = Object::_createJSObject(nullptr, jsobj);
|
||||
if (obj != nullptr)
|
||||
obj->_type = Type::ARRAY_BUFFER;
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
HandleObject arr(Object::createArrayObject(byteLength));
|
||||
if (!arr.isEmpty())
|
||||
{
|
||||
uint8_t* p = (uint8_t*)data;
|
||||
for (size_t i = 0; i < byteLength; ++i)
|
||||
{
|
||||
arr->setArrayElement((uint32_t)i, se::Value(p[i]));
|
||||
}
|
||||
JSObjectRef ret = EJJSObjectMakeTypedArray(__cx, kEJJSTypedArrayTypeArrayBuffer, byteLength);
|
||||
NSData* nsData = [NSData dataWithBytes:data length:byteLength];
|
||||
EJJSObjectSetTypedArrayData(__cx, ret, nsData);
|
||||
|
||||
ValueArray args;
|
||||
args.push_back(Value(arr));
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_createArrayBufferObject", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
Value ret;
|
||||
ok = func.toObject()->call(args, nullptr, &ret);
|
||||
if (ok && ret.isObject())
|
||||
{
|
||||
Object* obj = Object::_createJSObject(nullptr, ret.toObject()->_obj);
|
||||
if (obj != nullptr)
|
||||
obj->_type = Type::ARRAY_BUFFER;
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static bool _setArrayElement(Object* arr, void* data, size_t byteLength)
|
||||
{
|
||||
T* p = (T*)data;
|
||||
size_t count = byteLength / sizeof(T);
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
{
|
||||
if (!arr->setArrayElement((uint32_t)i, se::Value(p[i])))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
Object* obj = Object::_createJSObject(nullptr, ret);
|
||||
if (obj != nullptr)
|
||||
obj->_type = Type::ARRAY_BUFFER;
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength)
|
||||
@@ -203,29 +163,42 @@ namespace se {
|
||||
|
||||
JSValueRef exception = nullptr;
|
||||
JSTypedArrayType jscTypedArrayType = kJSTypedArrayTypeNone;
|
||||
Type objectType = Type::UNKNOWN;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
objectType = Type::TYPED_ARRAY_INT8;
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt8Array;
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
objectType = Type::TYPED_ARRAY_INT16;
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt16Array;
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
objectType = Type::TYPED_ARRAY_INT32;
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt32Array;
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
objectType = Type::TYPED_ARRAY_UINT8;
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint8Array;
|
||||
break;
|
||||
case TypedArrayType::UINT8_CLAMPED:
|
||||
objectType = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint8ClampedArray;
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
objectType = Type::TYPED_ARRAY_UINT16;
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint16Array;
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
objectType = Type::TYPED_ARRAY_UINT32;
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint32Array;
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
objectType = Type::TYPED_ARRAY_FLOAT32;
|
||||
jscTypedArrayType = kJSTypedArrayTypeFloat32Array;
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
objectType = Type::TYPED_ARRAY_FLOAT64;
|
||||
jscTypedArrayType = kJSTypedArrayTypeFloat64Array;
|
||||
break;
|
||||
default:
|
||||
@@ -238,88 +211,72 @@ namespace se {
|
||||
return nullptr;
|
||||
}
|
||||
Object* obj = Object::_createJSObject(nullptr, jsobj);
|
||||
if (obj != nullptr)
|
||||
obj->_type = objectType;
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
HandleObject arr(Object::createArrayObject(byteLength));
|
||||
Type objectType = Type::UNKNOWN;
|
||||
|
||||
if (!arr.isEmpty())
|
||||
{
|
||||
const char* typedArrayCtor = nullptr;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
typedArrayCtor = "Int8Array";
|
||||
objectType = Type::TYPED_ARRAY_INT8;
|
||||
_setArrayElement<int8_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
typedArrayCtor = "Int16Array";
|
||||
objectType = Type::TYPED_ARRAY_INT16;
|
||||
_setArrayElement<int16_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
typedArrayCtor = "Int32Array";
|
||||
objectType = Type::TYPED_ARRAY_INT32;
|
||||
_setArrayElement<int32_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
typedArrayCtor = "Uint8Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT8;
|
||||
_setArrayElement<uint8_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
typedArrayCtor = "Uint16Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT16;
|
||||
_setArrayElement<uint16_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
typedArrayCtor = "Uint32Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT32;
|
||||
_setArrayElement<uint32_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
typedArrayCtor = "Float32Array";
|
||||
objectType = Type::TYPED_ARRAY_FLOAT32;
|
||||
_setArrayElement<float>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
typedArrayCtor = "Float64Array";
|
||||
objectType = Type::TYPED_ARRAY_FLOAT64;
|
||||
_setArrayElement<double>(arr.get(), data, byteLength);
|
||||
break;
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty(typedArrayCtor, &func);
|
||||
// On <= iOS 9, typed array constructor is an object rather than a function.
|
||||
// Therefore, don't check whether typed array constructor is a function here.
|
||||
if (ok && func.isObject()/* && func.toObject()->isFunction() */)
|
||||
{
|
||||
JSValueRef exception = nullptr;
|
||||
JSObjectRef ret = JSObjectCallAsConstructor(__cx, func.toObject()->_obj, 1, &arr->_obj, &exception);
|
||||
if (exception == nullptr)
|
||||
{
|
||||
Object* obj = Object::_createJSObject(nullptr, ret);
|
||||
if (obj != nullptr)
|
||||
obj->_type = objectType;
|
||||
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
{
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
size_t numElements = 0;
|
||||
EJJSTypedArrayType jscTypedArrayType = kEJJSTypedArrayTypeNone;
|
||||
Type objectType = Type::UNKNOWN;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
objectType = Type::TYPED_ARRAY_INT8;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeInt8Array;
|
||||
numElements = byteLength;
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
objectType = Type::TYPED_ARRAY_INT16;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeInt16Array;
|
||||
numElements = byteLength / 2;
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
objectType = Type::TYPED_ARRAY_INT32;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeInt32Array;
|
||||
numElements = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
objectType = Type::TYPED_ARRAY_UINT8;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeUint8Array;
|
||||
numElements = byteLength;
|
||||
break;
|
||||
case TypedArrayType::UINT8_CLAMPED:
|
||||
objectType = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeUint8ClampedArray;
|
||||
numElements = byteLength;
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
objectType = Type::TYPED_ARRAY_UINT16;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeUint16Array;
|
||||
numElements = byteLength / 2;
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
objectType = Type::TYPED_ARRAY_UINT32;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeUint32Array;
|
||||
numElements = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
objectType = Type::TYPED_ARRAY_FLOAT32;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeFloat32Array;
|
||||
numElements = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
objectType = Type::TYPED_ARRAY_FLOAT64;
|
||||
jscTypedArrayType = kEJJSTypedArrayTypeFloat64Array;
|
||||
numElements = byteLength / 8;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
JSObjectRef ret = EJJSObjectMakeTypedArray(__cx, jscTypedArrayType, numElements);
|
||||
NSData* nsData = [NSData dataWithBytes:data length:byteLength];
|
||||
EJJSObjectSetTypedArrayData(__cx, ret, nsData);
|
||||
|
||||
Object* obj = Object::_createJSObject(nullptr, ret);
|
||||
if (obj != nullptr)
|
||||
obj->_type = objectType;
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount)
|
||||
@@ -711,7 +668,9 @@ namespace se {
|
||||
return ret;
|
||||
}
|
||||
#endif
|
||||
return isInstanceOfConstructor(__cx, _obj, "__jscTypedArrayConstructor");
|
||||
|
||||
EJJSTypedArrayType typedArrayType = EJJSObjectGetTypedArrayType(__cx, _obj);
|
||||
return typedArrayType >= kEJJSTypedArrayTypeInt8Array && typedArrayType <= kEJJSTypedArrayTypeFloat64Array;
|
||||
}
|
||||
|
||||
Object::TypedArrayType Object::getTypedArrayType() const
|
||||
@@ -788,50 +747,48 @@ namespace se {
|
||||
return typedArrayType;
|
||||
}
|
||||
#endif
|
||||
if (isInstanceOfConstructor(__cx, _obj, "Int8Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT8;
|
||||
typedArrayType = TypedArrayType::INT8;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Int16Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT16;
|
||||
typedArrayType = TypedArrayType::INT16;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Int32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT32;
|
||||
typedArrayType = TypedArrayType::INT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint8Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT8;
|
||||
typedArrayType = TypedArrayType::UINT8;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint8ClampedArray"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
typedArrayType = TypedArrayType::UINT8_CLAMPED;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint16Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT16;
|
||||
typedArrayType = TypedArrayType::UINT16;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT32;
|
||||
typedArrayType = TypedArrayType::UINT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Float32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_FLOAT32;
|
||||
typedArrayType = TypedArrayType::FLOAT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Float64Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_FLOAT64;
|
||||
typedArrayType = TypedArrayType::FLOAT64;
|
||||
EJJSTypedArrayType ejTypedArrayType = EJJSObjectGetTypedArrayType(__cx, _obj);
|
||||
|
||||
switch (ejTypedArrayType) {
|
||||
case kEJJSTypedArrayTypeInt8Array:
|
||||
_type = Type::TYPED_ARRAY_INT8;
|
||||
typedArrayType = TypedArrayType::INT8;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeInt16Array:
|
||||
_type = Type::TYPED_ARRAY_INT16;
|
||||
typedArrayType = TypedArrayType::INT16;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeInt32Array:
|
||||
_type = Type::TYPED_ARRAY_INT32;
|
||||
typedArrayType = TypedArrayType::INT32;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeUint8Array:
|
||||
_type = Type::TYPED_ARRAY_UINT8;
|
||||
typedArrayType = TypedArrayType::UINT8;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeUint8ClampedArray:
|
||||
_type = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
typedArrayType = TypedArrayType::UINT8_CLAMPED;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeUint16Array:
|
||||
_type = Type::TYPED_ARRAY_UINT16;
|
||||
typedArrayType = TypedArrayType::UINT16;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeUint32Array:
|
||||
_type = Type::TYPED_ARRAY_UINT32;
|
||||
typedArrayType = TypedArrayType::UINT32;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeFloat32Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT32;
|
||||
typedArrayType = TypedArrayType::FLOAT32;
|
||||
break;
|
||||
case kEJJSTypedArrayTypeFloat64Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT64;
|
||||
typedArrayType = TypedArrayType::FLOAT64;
|
||||
break;
|
||||
default:
|
||||
typedArrayType = TypedArrayType::NONE;
|
||||
break;
|
||||
}
|
||||
|
||||
return typedArrayType;
|
||||
@@ -876,53 +833,11 @@ namespace se {
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getTypedArrayData", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
ValueArray args;
|
||||
args.push_back(Value((Object*)this));
|
||||
|
||||
Value rval;
|
||||
ok = func.toObject()->call(args, nullptr, &rval);
|
||||
if (ok && rval.isObject() && rval.toObject()->isArray())
|
||||
{
|
||||
uint32_t len = 0;
|
||||
Object* arrObj = rval.toObject();
|
||||
if (arrObj->getArrayLength(&len))
|
||||
{
|
||||
if (len > 0)
|
||||
{
|
||||
Value tmp;
|
||||
if (_arrayBuffer == nullptr)
|
||||
{
|
||||
_arrayBuffer = (uint8_t*)malloc(len);
|
||||
}
|
||||
else if (_arrayBufferSize != len)
|
||||
{
|
||||
_arrayBuffer = (uint8_t*)realloc(_arrayBuffer, len);
|
||||
}
|
||||
|
||||
*length = _arrayBufferSize = len;
|
||||
*ptr = _arrayBuffer;
|
||||
for (uint32_t i = 0; i < len; ++i)
|
||||
{
|
||||
if (arrObj->getArrayElement(i, &tmp) && tmp.isNumber())
|
||||
{
|
||||
_arrayBuffer[i] = tmp.toUint8();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
NSMutableData* data = EJJSObjectGetTypedArrayData(__cx, _obj);
|
||||
*ptr = (uint8_t*)data.mutableBytes;
|
||||
*length = data.length;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Object::_isNativeFunction() const
|
||||
@@ -1009,52 +924,11 @@ namespace se {
|
||||
|
||||
return (*ptr != nullptr);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getArrayBufferData", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
ValueArray args;
|
||||
args.push_back(Value((Object*)this));
|
||||
|
||||
Value rval;
|
||||
ok = func.toObject()->call(args, nullptr, &rval);
|
||||
if (ok && rval.isObject() && rval.toObject()->isArray())
|
||||
{
|
||||
uint32_t len = 0;
|
||||
Object* arrObj = rval.toObject();
|
||||
if (arrObj->getArrayLength(&len))
|
||||
{
|
||||
if (len > 0)
|
||||
{
|
||||
Value tmp;
|
||||
if (_arrayBuffer == nullptr)
|
||||
{
|
||||
_arrayBuffer = (uint8_t*)malloc(len);
|
||||
}
|
||||
else if (_arrayBufferSize != len)
|
||||
{
|
||||
_arrayBuffer = (uint8_t*)realloc(_arrayBuffer, len);
|
||||
}
|
||||
|
||||
*length = _arrayBufferSize = len;
|
||||
*ptr = _arrayBuffer;
|
||||
for (uint32_t i = 0; i < len; ++i)
|
||||
{
|
||||
if (arrObj->getArrayElement(i, &tmp) && tmp.isNumber())
|
||||
{
|
||||
_arrayBuffer[i] = tmp.toUint8();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
NSMutableData* data = EJJSObjectGetTypedArrayData(__cx, _obj);
|
||||
*ptr = (uint8_t*)data.mutableBytes;
|
||||
*length = data.length;
|
||||
return true;
|
||||
}
|
||||
|
||||
void* Object::getPrivateData() const
|
||||
+6
@@ -31,6 +31,9 @@
|
||||
#include "Utils.hpp"
|
||||
#include "../State.hpp"
|
||||
#include "../MappingUtils.hpp"
|
||||
#include "PlatformUtils.h"
|
||||
|
||||
#import "EJConvertTypedArray.h"
|
||||
|
||||
#if SE_DEBUG > 0
|
||||
extern "C" JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef);
|
||||
@@ -255,6 +258,9 @@ namespace se {
|
||||
_globalObj->root();
|
||||
_globalObj->setProperty("window", Value(_globalObj));
|
||||
|
||||
if (!isSupportTypedArrayAPI())
|
||||
EJJSContextPrepareTypedArrayAPI(_cx);
|
||||
|
||||
if (_globalObj->getProperty("console", &__consoleVal) && __consoleVal.isObject())
|
||||
{
|
||||
__consoleVal.toObject()->getProperty("log", &__oldConsoleLog);
|
||||
@@ -719,119 +719,6 @@ static bool js_gfx_IndexBuffer_prop_getBytes(se::State& s)
|
||||
}
|
||||
SE_BIND_PROP_GET(js_gfx_IndexBuffer_prop_getBytes)
|
||||
|
||||
static bool js_gfx_getImageInfo(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_gfx_getImageInfo : Error processing arguments");
|
||||
|
||||
se::HandleObject retObj(se::Object::createPlainObject());
|
||||
|
||||
Data data;
|
||||
Image* img = new (std::nothrow) Image();
|
||||
if (img->initWithImageFile(arg0))
|
||||
{
|
||||
data.copy(img->getData(), img->getDataLen());
|
||||
// Convert to RGBA8888 because Web engine only supports it.
|
||||
//FIX ME: How to handle other formats?
|
||||
if (Image::PixelFormat::RGB888 == img->getRenderFormat())
|
||||
{
|
||||
unsigned char convertedData[img->getWidth() * img->getHeight() * 4];
|
||||
auto dataT = data.getBytes();
|
||||
for (size_t i = 0, len = data.getSize() / 3; i < len; ++i)
|
||||
{
|
||||
convertedData[i * 4] = *dataT++;
|
||||
convertedData[i * 4 + 1] = *dataT++;
|
||||
convertedData[i * 4 + 2] = *dataT++;
|
||||
convertedData[i * 4 + 3] = 255;
|
||||
}
|
||||
data.copy(convertedData, sizeof(convertedData));
|
||||
}
|
||||
|
||||
se::Value dataVal;
|
||||
ok &= Data_to_seval(data, &dataVal);
|
||||
SE_PRECONDITION2(ok, false, "js_gfx_getImageInfo : Error processing arguments");
|
||||
retObj->setProperty("data", dataVal);
|
||||
retObj->setProperty("width", se::Value(img->getWidth()));
|
||||
retObj->setProperty("height", se::Value(img->getHeight()));
|
||||
retObj->setProperty("premultiplyAlpha", se::Value(img->hasPremultipliedAlpha()));
|
||||
retObj->setProperty("bpp", se::Value(32));
|
||||
retObj->setProperty("hasAlpha", se::Value(img->hasAlpha()));
|
||||
retObj->setProperty("compressed", se::Value(img->isCompressed()));
|
||||
retObj->setProperty("numberOfMipmaps", se::Value(img->getNumberOfMipmaps()));
|
||||
|
||||
const auto& pixelFormatInfo = img->getPixelFormatInfo();
|
||||
retObj->setProperty("glFormat", se::Value(GL_RGBA));
|
||||
retObj->setProperty("glInternalFormat", se::Value(GL_RGBA));
|
||||
retObj->setProperty("glType", se::Value(pixelFormatInfo.type));
|
||||
}
|
||||
else
|
||||
{
|
||||
SE_REPORT_ERROR("initWithImageFile: %s failed!", arg0.c_str());
|
||||
assert(false);
|
||||
}
|
||||
|
||||
img->release();
|
||||
|
||||
s.rval().setObject(retObj);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_gfx_getImageInfo)
|
||||
|
||||
static bool js_gfx_getTextTextureInfo(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 3) {
|
||||
|
||||
/*
|
||||
const char * text,
|
||||
const FontDefinition& textDefinition,
|
||||
TextAlign align,
|
||||
int &width,
|
||||
int &height,
|
||||
bool& hasPremultipliedAlpha
|
||||
*/
|
||||
|
||||
std::string text;
|
||||
ok = seval_to_std_string(args[0], &text);
|
||||
SE_PRECONDITION2(ok, false, "Convert arg0 text failed!");
|
||||
FontDefinition fontDef;
|
||||
ok = seval_to_FontDefinition(args[1], &fontDef);
|
||||
SE_PRECONDITION2(ok, false, "Convert arg1 fontDef failed!");
|
||||
int32_t align;
|
||||
ok = seval_to_int32(args[2], &align);
|
||||
Device::TextAlign textAlign = (Device::TextAlign)align;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool hasPremultipliedAlpha = false;
|
||||
Data data = Device::getTextureDataForText(text.c_str(), fontDef, textAlign, width, height, hasPremultipliedAlpha);
|
||||
|
||||
se::HandleObject retObj(se::Object::createPlainObject());
|
||||
se::Value dataVal;
|
||||
if (Data_to_seval(data, &dataVal))
|
||||
retObj->setProperty("data", dataVal);
|
||||
|
||||
retObj->setProperty("width", se::Value(width));
|
||||
retObj->setProperty("height", se::Value(height));
|
||||
retObj->setProperty("hasPremultipliedAlpha", se::Value(hasPremultipliedAlpha));
|
||||
|
||||
s.rval().setObject(retObj);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_gfx_getTextTextureInfo)
|
||||
|
||||
static bool js_gfx_FrameBuffer_init(se::State& s)
|
||||
{
|
||||
cocos2d::renderer::FrameBuffer* cobj = (cocos2d::renderer::FrameBuffer*)s.nativeThisObject();
|
||||
@@ -929,9 +816,6 @@ bool jsb_register_gfx_manual(se::Object* global)
|
||||
__jsb_cocos2d_renderer_Texture2D_proto->defineFunction("init", _SE(js_gfx_Texture2D_init));
|
||||
__jsb_cocos2d_renderer_FrameBuffer_proto->defineFunction("init", _SE(js_gfx_FrameBuffer_init));
|
||||
|
||||
global->defineFunction("getImageInfo", _SE(js_gfx_getImageInfo));
|
||||
global->defineFunction("getTextTextureInfo", _SE(js_gfx_getTextTextureInfo));
|
||||
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,15 +6,22 @@
|
||||
#include "jsb_conversions.hpp"
|
||||
#include "xxtea/xxtea.h"
|
||||
|
||||
#include "base/CCScheduler.h"
|
||||
#include "base/CCThreadPool.h"
|
||||
#include "platform/CCApplication.h"
|
||||
|
||||
#include <regex>
|
||||
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
se::Object* __jscObj = nullptr;
|
||||
se::Object* __ccObj = nullptr;
|
||||
se::Object* __jsbObj = nullptr;
|
||||
se::Object* __glObj = nullptr;
|
||||
|
||||
static ThreadPool* __threadPool = nullptr;
|
||||
|
||||
static std::string xxteaKey = "";
|
||||
void jsb_set_xxtea_key(const std::string& key)
|
||||
{
|
||||
@@ -197,16 +204,16 @@ namespace {
|
||||
|
||||
std::unordered_map<std::string, se::Value> __moduleCache;
|
||||
|
||||
// static bool require(se::State& s)
|
||||
// {
|
||||
// const auto& args = s.args();
|
||||
// int argc = (int)args.size();
|
||||
// assert(argc >= 1);
|
||||
// assert(args[0].isString());
|
||||
//
|
||||
// return jsb_run_script(args[0].toString(), &s.rval());
|
||||
// }
|
||||
// SE_BIND_FUNC(require)
|
||||
static bool require(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
int argc = (int)args.size();
|
||||
assert(argc >= 1);
|
||||
assert(args[0].isString());
|
||||
|
||||
return jsb_run_script(args[0].toString(), &s.rval());
|
||||
}
|
||||
SE_BIND_FUNC(require)
|
||||
|
||||
static bool doModuleRequire(const std::string& path, se::Value* ret, const std::string& prevScriptFileDir)
|
||||
{
|
||||
@@ -269,7 +276,7 @@ namespace {
|
||||
snprintf(suffix, sizeof(suffix), "\nwindow.module.exports = window.module.exports || exports;\n})('%s'); ", currentScriptFileDir.c_str());
|
||||
|
||||
// Add current script path to require function invocation
|
||||
scriptBuffer = prefix + std::regex_replace(scriptBuffer, std::regex("([^A-Za-z0-9]|^)require\\((.*?)\\)"), "$1require($2, currentScriptDir)") + suffix;
|
||||
scriptBuffer = prefix + std::regex_replace(scriptBuffer, std::regex("([^A-Za-z0-9]|^)requireModule\\((.*?)\\)"), "$1requireModule($2, currentScriptDir)") + suffix;
|
||||
|
||||
// FILE* fp = fopen("/Users/james/Downloads/test.txt", "wb");
|
||||
// fwrite(scriptBuffer.c_str(), scriptBuffer.length(), 1, fp);
|
||||
@@ -296,7 +303,7 @@ namespace {
|
||||
auto se = se::ScriptEngine::getInstance();
|
||||
bool succeed = se->evalString(scriptBuffer.c_str(), scriptBuffer.length(), nullptr, reletivePath.c_str());
|
||||
se::Value moduleVal;
|
||||
if (se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject())
|
||||
if (succeed && se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject())
|
||||
{
|
||||
se::Value exportsVal;
|
||||
if (moduleVal.toObject()->getProperty("exports", &exportsVal))
|
||||
@@ -337,412 +344,15 @@ namespace {
|
||||
return doModuleRequire(args[0].toString(), &s.rval(), args[1].toString());
|
||||
}
|
||||
SE_BIND_FUNC(moduleRequire)
|
||||
|
||||
static bool ccpAdd(se::State& s)
|
||||
{
|
||||
if (s.args().size() == 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1 + pt2;
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpAdd)
|
||||
|
||||
static bool ccpDistanceSQ(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt1.getDistanceSq(pt2);
|
||||
s.rval().setFloat(result);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpDistanceSQ)
|
||||
|
||||
static bool ccpDistance(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt1.getDistance(pt2);
|
||||
s.rval().setFloat(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpDistance)
|
||||
|
||||
static bool ccpSub(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1 - pt2;
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpSub)
|
||||
|
||||
static bool ccpNeg(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
pt = -pt;
|
||||
ok = Vec2_to_seval(pt, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpNeg)
|
||||
|
||||
static bool ccpMult(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
SE_ASSERT(args[1].isNumber(), "Error processing arguments");
|
||||
Vec2 result = pt * args[1].toFloat();
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpMult)
|
||||
|
||||
static bool ccpMidpoint(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1.getMidpoint(pt2);
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpMidpoint)
|
||||
|
||||
static bool ccpDot(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt1.dot(pt2);
|
||||
s.rval().setFloat(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpDot)
|
||||
|
||||
static bool ccpCross(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt1.cross(pt2);
|
||||
s.rval().setFloat(result);
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpCross)
|
||||
|
||||
static bool ccpPerp(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt.getPerp();
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpPerp)
|
||||
|
||||
static bool ccpRPerp(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt.getRPerp();
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpRPerp)
|
||||
|
||||
static bool ccpProject(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1.project(pt2);
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpProject)
|
||||
|
||||
static bool ccpRotate(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 2)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1.rotate(pt2);
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpRotate)
|
||||
|
||||
static bool ccpNormalize(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
pt.normalize();
|
||||
ok = Vec2_to_seval(pt, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpNormalize)
|
||||
|
||||
static bool ccpClamp(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 3)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt1, pt2, pt3;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt1);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt2);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
ok = seval_to_Vec2(args[1], &pt3);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
Vec2 result = pt1.getClampPoint(pt2, pt3);
|
||||
ok = Vec2_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 3);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpClamp)
|
||||
|
||||
static bool ccpLengthSQ(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt.getLengthSq();
|
||||
s.rval().setFloat(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpLengthSQ)
|
||||
|
||||
static bool ccpLength(se::State& s)
|
||||
{
|
||||
if (s.args().size()== 1)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
Vec2 pt;
|
||||
bool ok = false;
|
||||
ok = seval_to_Vec2(args[0], &pt);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
float result = pt.getLength();
|
||||
s.rval().setFloat(result);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccpLength)
|
||||
|
||||
static bool ccassert(se::State& s)
|
||||
{
|
||||
const se::ValueArray& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc >= 1)
|
||||
{
|
||||
if (argc == 1)
|
||||
{
|
||||
SE_ASSERT(args[0].toBoolean(), "NO MESSAGE");
|
||||
}
|
||||
else
|
||||
{
|
||||
SE_ASSERT(args[0].toBoolean(), "%s", args[1].toString().c_str());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)s.args().size(), 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(ccassert)
|
||||
|
||||
bool jsb_register_var_under_cc()
|
||||
{
|
||||
// Vec2 Math
|
||||
__ccObj->defineFunction("pAdd", _SE(ccpAdd));
|
||||
__ccObj->defineFunction("pDistanceSQ", _SE(ccpDistanceSQ));
|
||||
__ccObj->defineFunction("pDistance", _SE(ccpDistance));
|
||||
__ccObj->defineFunction("pSub", _SE(ccpSub));
|
||||
__ccObj->defineFunction("pNeg", _SE(ccpNeg));
|
||||
__ccObj->defineFunction("pMult", _SE(ccpMult));
|
||||
__ccObj->defineFunction("pMidpoint", _SE(ccpMidpoint));
|
||||
__ccObj->defineFunction("pDot", _SE(ccpDot));
|
||||
__ccObj->defineFunction("pCross", _SE(ccpCross));
|
||||
__ccObj->defineFunction("pPerp", _SE(ccpPerp));
|
||||
__ccObj->defineFunction("pRPerp", _SE(ccpRPerp));
|
||||
__ccObj->defineFunction("pProject", _SE(ccpProject));
|
||||
__ccObj->defineFunction("pRotate", _SE(ccpRotate));
|
||||
__ccObj->defineFunction("pNormalize", _SE(ccpNormalize));
|
||||
__ccObj->defineFunction("pClamp", _SE(ccpClamp));
|
||||
__ccObj->defineFunction("pLengthSQ", _SE(ccpLengthSQ));
|
||||
__ccObj->defineFunction("pLength", _SE(ccpLength));
|
||||
|
||||
//
|
||||
__ccObj->defineFunction("assert", _SE(ccassert));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace {
|
||||
|
||||
bool jsb_run_script(const std::string& filePath, se::Value* rval/* = nullptr */)
|
||||
{
|
||||
se::AutoHandleScope hs;
|
||||
return se::ScriptEngine::getInstance()->runScript(filePath, rval);
|
||||
}
|
||||
|
||||
bool jsb_run_script_module(const std::string& filePath, se::Value* rval/* = nullptr */)
|
||||
{
|
||||
return doModuleRequire(filePath, rval, "");
|
||||
}
|
||||
@@ -951,14 +561,174 @@ static bool js_performance_now(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_performance_now)
|
||||
|
||||
static bool js_loadImage(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
std::string path;
|
||||
ok &= seval_to_std_string(args[0], &path);
|
||||
SE_PRECONDITION2(ok, false, "js_loadImage : Error processing arguments");
|
||||
|
||||
se::Value callbackVal = args[1];
|
||||
assert(callbackVal.isObject());
|
||||
assert(callbackVal.toObject()->isFunction());
|
||||
|
||||
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
|
||||
if (fullPath.empty())
|
||||
{
|
||||
SE_REPORT_ERROR("File (%s) doesn't exist!", path.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
Image* img = new (std::nothrow) Image();
|
||||
|
||||
__threadPool->pushTask([=](int tid){
|
||||
// NOTE: FileUtils::getInstance()->fullPathForFilename isn't a threadsafe method,
|
||||
// Image::initWithImageFile will call fullPathForFilename internally which may
|
||||
// cause thread race issues. Therefore, we get the full path of file before
|
||||
// going into task callback.
|
||||
// Be careful of invoking any Cocos2d-x interface in a sub-thread.
|
||||
bool loadSucceed = img->initWithImageFile(fullPath);
|
||||
|
||||
Application::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
|
||||
if (loadSucceed)
|
||||
{
|
||||
se::AutoHandleScope hs;
|
||||
se::HandleObject retObj(se::Object::createPlainObject());
|
||||
Data data;
|
||||
data.copy(img->getData(), img->getDataLen());
|
||||
|
||||
#ifdef CC_NEW_RENDERER
|
||||
// Convert to RGBA8888 because Web engine only supports it.
|
||||
//FIX ME: How to handle other formats?
|
||||
if (Image::PixelFormat::RGB888 == img->getRenderFormat())
|
||||
{
|
||||
unsigned char convertedData[img->getWidth() * img->getHeight() * 4];
|
||||
auto dataT = data.getBytes();
|
||||
for (size_t i = 0, len = data.getSize() / 3; i < len; ++i)
|
||||
{
|
||||
convertedData[i * 4] = *dataT++;
|
||||
convertedData[i * 4 + 1] = *dataT++;
|
||||
convertedData[i * 4 + 2] = *dataT++;
|
||||
convertedData[i * 4 + 3] = 255;
|
||||
}
|
||||
data.copy(convertedData, sizeof(convertedData));
|
||||
}
|
||||
|
||||
se::Value dataVal;
|
||||
Data_to_seval(data, &dataVal);
|
||||
SE_PRECONDITION2(ok, false, "js_gfx_getImageInfo : Error processing arguments");
|
||||
retObj->setProperty("data", dataVal);
|
||||
retObj->setProperty("width", se::Value(img->getWidth()));
|
||||
retObj->setProperty("height", se::Value(img->getHeight()));
|
||||
retObj->setProperty("premultiplyAlpha", se::Value(img->hasPremultipliedAlpha()));
|
||||
retObj->setProperty("bpp", se::Value(32));
|
||||
retObj->setProperty("hasAlpha", se::Value(img->hasAlpha()));
|
||||
retObj->setProperty("compressed", se::Value(img->isCompressed()));
|
||||
retObj->setProperty("numberOfMipmaps", se::Value(img->getNumberOfMipmaps()));
|
||||
|
||||
const auto& pixelFormatInfo = img->getPixelFormatInfo();
|
||||
retObj->setProperty("glFormat", se::Value(GL_RGBA));
|
||||
retObj->setProperty("glInternalFormat", se::Value(GL_RGBA));
|
||||
retObj->setProperty("glType", se::Value(pixelFormatInfo.type));
|
||||
#else
|
||||
se::Value dataVal;
|
||||
Data_to_seval(data, &dataVal);
|
||||
retObj->setProperty("data", dataVal);
|
||||
retObj->setProperty("width", se::Value(img->getWidth()));
|
||||
retObj->setProperty("height", se::Value(img->getHeight()));
|
||||
retObj->setProperty("premultiplyAlpha", se::Value(img->hasPremultipliedAlpha()));
|
||||
retObj->setProperty("bpp", se::Value(img->getBitPerPixel()));
|
||||
retObj->setProperty("hasAlpha", se::Value(img->hasAlpha()));
|
||||
retObj->setProperty("compressed", se::Value(img->isCompressed()));
|
||||
retObj->setProperty("numberOfMipmaps", se::Value(img->getNumberOfMipmaps()));
|
||||
|
||||
const auto& pixelFormatInfo = img->getPixelFormatInfo();
|
||||
retObj->setProperty("glFormat", se::Value(pixelFormatInfo.format));
|
||||
retObj->setProperty("glInternalFormat", se::Value(pixelFormatInfo.internalFormat));
|
||||
retObj->setProperty("glType", se::Value(pixelFormatInfo.type));
|
||||
#endif
|
||||
|
||||
se::ValueArray seArgs;
|
||||
seArgs.push_back(se::Value(retObj));
|
||||
callbackVal.toObject()->call(seArgs, nullptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
SE_REPORT_ERROR("initWithImageFile: %s failed!", path.c_str());
|
||||
assert(false);
|
||||
}
|
||||
|
||||
img->release();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_loadImage)
|
||||
|
||||
static bool js_getTextTextureInfo(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 3) {
|
||||
|
||||
/*
|
||||
const char * text,
|
||||
const FontDefinition& textDefinition,
|
||||
TextAlign align,
|
||||
int &width,
|
||||
int &height,
|
||||
bool& hasPremultipliedAlpha
|
||||
*/
|
||||
|
||||
std::string text;
|
||||
ok = seval_to_std_string(args[0], &text);
|
||||
SE_PRECONDITION2(ok, false, "Convert arg0 text failed!");
|
||||
FontDefinition fontDef;
|
||||
ok = seval_to_FontDefinition(args[1], &fontDef);
|
||||
SE_PRECONDITION2(ok, false, "Convert arg1 fontDef failed!");
|
||||
int32_t align;
|
||||
ok = seval_to_int32(args[2], &align);
|
||||
Device::TextAlign textAlign = (Device::TextAlign)align;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool hasPremultipliedAlpha = false;
|
||||
Data data = Device::getTextureDataForText(text.c_str(), fontDef, textAlign, width, height, hasPremultipliedAlpha);
|
||||
|
||||
se::HandleObject retObj(se::Object::createPlainObject());
|
||||
se::Value dataVal;
|
||||
if (Data_to_seval(data, &dataVal))
|
||||
retObj->setProperty("data", dataVal);
|
||||
|
||||
retObj->setProperty("width", se::Value(width));
|
||||
retObj->setProperty("height", se::Value(height));
|
||||
retObj->setProperty("hasPremultipliedAlpha", se::Value(hasPremultipliedAlpha));
|
||||
|
||||
s.rval().setObject(retObj);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_getTextTextureInfo)
|
||||
|
||||
bool jsb_register_global_variables(se::Object* global)
|
||||
{
|
||||
global->defineFunction("require", _SE(moduleRequire));
|
||||
__threadPool = ThreadPool::newFixedThreadPool(3);
|
||||
|
||||
global->defineFunction("require", _SE(require));
|
||||
global->defineFunction("requireModule", _SE(moduleRequire));
|
||||
|
||||
getOrCreatePlainObject_r("cc", global, &__ccObj);
|
||||
|
||||
jsb_register_var_under_cc();
|
||||
|
||||
getOrCreatePlainObject_r("jsb", global, &__jsbObj);
|
||||
getOrCreatePlainObject_r("__jsc__", global, &__jscObj);
|
||||
getOrCreatePlainObject_r("gl", global, &__glObj);
|
||||
@@ -966,6 +736,8 @@ bool jsb_register_global_variables(se::Object* global)
|
||||
__jscObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect));
|
||||
__jscObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap));
|
||||
|
||||
__jsbObj->defineFunction("loadImage", _SE(js_loadImage));
|
||||
|
||||
global->defineFunction("__getPlatform", _SE(JSBCore_platform));
|
||||
global->defineFunction("__getOS", _SE(JSBCore_os));
|
||||
global->defineFunction("__getVersion", _SE(JSBCore_version));
|
||||
@@ -980,8 +752,17 @@ bool jsb_register_global_variables(se::Object* global)
|
||||
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
|
||||
se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){
|
||||
delete __threadPool;
|
||||
__threadPool = nullptr;
|
||||
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
});
|
||||
|
||||
se::ScriptEngine::getInstance()->addAfterCleanupHook([](){
|
||||
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
|
||||
__moduleCache.clear();
|
||||
|
||||
__ccObj->decRef();
|
||||
|
||||
@@ -18,5 +18,6 @@ void jsb_init_file_operation_delegate();
|
||||
bool jsb_enable_debugger(const std::string& debuggerServerAddr, uint32_t port);
|
||||
bool jsb_set_extend_property(const char* ns, const char* clsName);
|
||||
bool jsb_run_script(const std::string& filePath, se::Value* rval = nullptr);
|
||||
bool jsb_run_script_module(const std::string& filePath, se::Value* rval = nullptr);
|
||||
|
||||
void jsb_set_xxtea_key(const std::string& key);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,157 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
|
||||
SE_DECLARE_FUNC(JSB_glActiveTexture);
|
||||
SE_DECLARE_FUNC(JSB_glAttachShader);
|
||||
SE_DECLARE_FUNC(JSB_glBindAttribLocation);
|
||||
SE_DECLARE_FUNC(JSB_glBindBuffer);
|
||||
SE_DECLARE_FUNC(JSB_glBindFramebuffer);
|
||||
SE_DECLARE_FUNC(JSB_glBindRenderbuffer);
|
||||
SE_DECLARE_FUNC(JSB_glBindTexture);
|
||||
SE_DECLARE_FUNC(JSB_glBlendColor);
|
||||
SE_DECLARE_FUNC(JSB_glBlendEquation);
|
||||
SE_DECLARE_FUNC(JSB_glBlendEquationSeparate);
|
||||
SE_DECLARE_FUNC(JSB_glBlendFunc);
|
||||
SE_DECLARE_FUNC(JSB_glBlendFuncSeparate);
|
||||
SE_DECLARE_FUNC(JSB_glBufferData);
|
||||
SE_DECLARE_FUNC(JSB_glBufferSubData);
|
||||
SE_DECLARE_FUNC(JSB_glCheckFramebufferStatus);
|
||||
SE_DECLARE_FUNC(JSB_glClear);
|
||||
SE_DECLARE_FUNC(JSB_glClearColor);
|
||||
SE_DECLARE_FUNC(JSB_glClearDepthf);
|
||||
SE_DECLARE_FUNC(JSB_glClearStencil);
|
||||
SE_DECLARE_FUNC(JSB_glColorMask);
|
||||
SE_DECLARE_FUNC(JSB_glCompileShader);
|
||||
SE_DECLARE_FUNC(JSB_glCompressedTexImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glCompressedTexSubImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glCopyTexImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glCopyTexSubImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glCreateProgram);
|
||||
SE_DECLARE_FUNC(JSB_glCreateShader);
|
||||
SE_DECLARE_FUNC(JSB_glCullFace);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteBuffers);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteFramebuffers);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteProgram);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteRenderbuffers);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteShader);
|
||||
SE_DECLARE_FUNC(JSB_glDeleteTextures);
|
||||
SE_DECLARE_FUNC(JSB_glDepthFunc);
|
||||
SE_DECLARE_FUNC(JSB_glDepthMask);
|
||||
SE_DECLARE_FUNC(JSB_glDepthRangef);
|
||||
SE_DECLARE_FUNC(JSB_glDetachShader);
|
||||
SE_DECLARE_FUNC(JSB_glDisable);
|
||||
SE_DECLARE_FUNC(JSB_glDisableVertexAttribArray);
|
||||
SE_DECLARE_FUNC(JSB_glDrawArrays);
|
||||
SE_DECLARE_FUNC(JSB_glDrawElements);
|
||||
SE_DECLARE_FUNC(JSB_glEnable);
|
||||
SE_DECLARE_FUNC(JSB_glEnableVertexAttribArray);
|
||||
SE_DECLARE_FUNC(JSB_glFinish);
|
||||
SE_DECLARE_FUNC(JSB_glFlush);
|
||||
SE_DECLARE_FUNC(JSB_glFramebufferRenderbuffer);
|
||||
SE_DECLARE_FUNC(JSB_glFramebufferTexture2D);
|
||||
SE_DECLARE_FUNC(JSB_glFrontFace);
|
||||
SE_DECLARE_FUNC(JSB_glGenBuffers);
|
||||
SE_DECLARE_FUNC(JSB_glGenFramebuffers);
|
||||
SE_DECLARE_FUNC(JSB_glGenRenderbuffers);
|
||||
SE_DECLARE_FUNC(JSB_glGenTextures);
|
||||
SE_DECLARE_FUNC(JSB_glGenerateMipmap);
|
||||
SE_DECLARE_FUNC(JSB_glGetActiveAttrib);
|
||||
SE_DECLARE_FUNC(JSB_glGetActiveUniform);
|
||||
SE_DECLARE_FUNC(JSB_glGetAttachedShaders);
|
||||
SE_DECLARE_FUNC(JSB_glGetAttribLocation);
|
||||
SE_DECLARE_FUNC(JSB_glGetError);
|
||||
SE_DECLARE_FUNC(JSB_glGetProgramInfoLog);
|
||||
SE_DECLARE_FUNC(JSB_glGetProgramiv);
|
||||
SE_DECLARE_FUNC(JSB_glGetShaderInfoLog);
|
||||
SE_DECLARE_FUNC(JSB_glGetShaderSource);
|
||||
SE_DECLARE_FUNC(JSB_glGetShaderiv);
|
||||
SE_DECLARE_FUNC(JSB_glGetTexParameterfv);
|
||||
SE_DECLARE_FUNC(JSB_glGetUniformLocation);
|
||||
SE_DECLARE_FUNC(JSB_glGetUniformfv);
|
||||
SE_DECLARE_FUNC(JSB_glHint);
|
||||
SE_DECLARE_FUNC(JSB_glIsBuffer);
|
||||
SE_DECLARE_FUNC(JSB_glIsEnabled);
|
||||
SE_DECLARE_FUNC(JSB_glIsFramebuffer);
|
||||
SE_DECLARE_FUNC(JSB_glIsProgram);
|
||||
SE_DECLARE_FUNC(JSB_glIsRenderbuffer);
|
||||
SE_DECLARE_FUNC(JSB_glIsShader);
|
||||
SE_DECLARE_FUNC(JSB_glIsTexture);
|
||||
SE_DECLARE_FUNC(JSB_glLineWidth);
|
||||
SE_DECLARE_FUNC(JSB_glLinkProgram);
|
||||
SE_DECLARE_FUNC(JSB_glPixelStorei);
|
||||
SE_DECLARE_FUNC(JSB_glPolygonOffset);
|
||||
SE_DECLARE_FUNC(JSB_glReadPixels);
|
||||
SE_DECLARE_FUNC(JSB_glReleaseShaderCompiler);
|
||||
SE_DECLARE_FUNC(JSB_glRenderbufferStorage);
|
||||
SE_DECLARE_FUNC(JSB_glSampleCoverage);
|
||||
SE_DECLARE_FUNC(JSB_glScissor);
|
||||
SE_DECLARE_FUNC(JSB_glShaderSource);
|
||||
SE_DECLARE_FUNC(JSB_glStencilFunc);
|
||||
SE_DECLARE_FUNC(JSB_glStencilFuncSeparate);
|
||||
SE_DECLARE_FUNC(JSB_glStencilMask);
|
||||
SE_DECLARE_FUNC(JSB_glStencilMaskSeparate);
|
||||
SE_DECLARE_FUNC(JSB_glStencilOp);
|
||||
SE_DECLARE_FUNC(JSB_glStencilOpSeparate);
|
||||
SE_DECLARE_FUNC(JSB_glTexImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glTexParameterf);
|
||||
SE_DECLARE_FUNC(JSB_glTexParameteri);
|
||||
SE_DECLARE_FUNC(JSB_glTexSubImage2D);
|
||||
SE_DECLARE_FUNC(JSB_glUniform1f);
|
||||
SE_DECLARE_FUNC(JSB_glUniform1fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform1i);
|
||||
SE_DECLARE_FUNC(JSB_glUniform1iv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform2f);
|
||||
SE_DECLARE_FUNC(JSB_glUniform2fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform2i);
|
||||
SE_DECLARE_FUNC(JSB_glUniform2iv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform3f);
|
||||
SE_DECLARE_FUNC(JSB_glUniform3fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform3i);
|
||||
SE_DECLARE_FUNC(JSB_glUniform3iv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform4f);
|
||||
SE_DECLARE_FUNC(JSB_glUniform4fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniform4i);
|
||||
SE_DECLARE_FUNC(JSB_glUniform4iv);
|
||||
SE_DECLARE_FUNC(JSB_glUniformMatrix2fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniformMatrix3fv);
|
||||
SE_DECLARE_FUNC(JSB_glUniformMatrix4fv);
|
||||
SE_DECLARE_FUNC(JSB_glUseProgram);
|
||||
SE_DECLARE_FUNC(JSB_glValidateProgram);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib1f);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib1fv);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib2f);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib2fv);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib3f);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib3fv);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib4f);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttrib4fv);
|
||||
SE_DECLARE_FUNC(JSB_glVertexAttribPointer);
|
||||
SE_DECLARE_FUNC(JSB_glViewport);
|
||||
SE_DECLARE_FUNC(JSB_glGetParameter);
|
||||
SE_DECLARE_FUNC(JSB_glGetShaderPrecisionFormat);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
namespace se {
|
||||
class Object;
|
||||
}
|
||||
|
||||
// forward declaration of new functions
|
||||
SE_DECLARE_FUNC(JSB_glGetSupportedExtensions);
|
||||
bool JSB_register_opengl(se::Object* obj);
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "jsb_opengl_registration.hpp"
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_global.h"
|
||||
#include "scripting/js-bindings/manual/jsb_opengl_functions.hpp"
|
||||
#include "scripting/js-bindings/manual/jsb_opengl_manual.hpp"
|
||||
|
||||
bool JSB_register_opengl(se::Object* obj)
|
||||
{
|
||||
// New WebGL functions, not present on OpenGL ES 2.0
|
||||
__glObj->defineFunction("getSupportedExtensions", _SE(JSB_glGetSupportedExtensions));
|
||||
__glObj->defineFunction("activeTexture", _SE(JSB_glActiveTexture));
|
||||
__glObj->defineFunction("_attachShader", _SE(JSB_glAttachShader));
|
||||
__glObj->defineFunction("_bindAttribLocation", _SE(JSB_glBindAttribLocation));
|
||||
__glObj->defineFunction("_bindBuffer", _SE(JSB_glBindBuffer));
|
||||
__glObj->defineFunction("_bindFramebuffer", _SE(JSB_glBindFramebuffer));
|
||||
__glObj->defineFunction("_bindRenderbuffer", _SE(JSB_glBindRenderbuffer));
|
||||
__glObj->defineFunction("_bindTexture", _SE(JSB_glBindTexture));
|
||||
__glObj->defineFunction("blendColor", _SE(JSB_glBlendColor));
|
||||
__glObj->defineFunction("blendEquation", _SE(JSB_glBlendEquation));
|
||||
__glObj->defineFunction("blendEquationSeparate", _SE(JSB_glBlendEquationSeparate));
|
||||
__glObj->defineFunction("blendFunc", _SE(JSB_glBlendFunc));
|
||||
__glObj->defineFunction("blendFuncSeparate", _SE(JSB_glBlendFuncSeparate));
|
||||
__glObj->defineFunction("bufferData", _SE(JSB_glBufferData));
|
||||
__glObj->defineFunction("bufferSubData", _SE(JSB_glBufferSubData));
|
||||
__glObj->defineFunction("checkFramebufferStatus", _SE(JSB_glCheckFramebufferStatus));
|
||||
__glObj->defineFunction("clear", _SE(JSB_glClear));
|
||||
__glObj->defineFunction("clearColor", _SE(JSB_glClearColor));
|
||||
__glObj->defineFunction("clearDepth", _SE(JSB_glClearDepthf));
|
||||
__glObj->defineFunction("clearStencil", _SE(JSB_glClearStencil));
|
||||
__glObj->defineFunction("colorMask", _SE(JSB_glColorMask));
|
||||
__glObj->defineFunction("_compileShader", _SE(JSB_glCompileShader));
|
||||
__glObj->defineFunction("compressedTexImage2D", _SE(JSB_glCompressedTexImage2D));
|
||||
__glObj->defineFunction("compressedTexSubImage2D", _SE(JSB_glCompressedTexSubImage2D));
|
||||
__glObj->defineFunction("copyTexImage2D", _SE(JSB_glCopyTexImage2D));
|
||||
__glObj->defineFunction("copyTexSubImage2D", _SE(JSB_glCopyTexSubImage2D));
|
||||
__glObj->defineFunction("_createProgram", _SE(JSB_glCreateProgram));
|
||||
__glObj->defineFunction("_createShader", _SE(JSB_glCreateShader));
|
||||
__glObj->defineFunction("cullFace", _SE(JSB_glCullFace));
|
||||
__glObj->defineFunction("_deleteBuffer", _SE(JSB_glDeleteBuffers));
|
||||
__glObj->defineFunction("_deleteFramebuffer", _SE(JSB_glDeleteFramebuffers));
|
||||
__glObj->defineFunction("_deleteProgram", _SE(JSB_glDeleteProgram));
|
||||
__glObj->defineFunction("_deleteRenderbuffer", _SE(JSB_glDeleteRenderbuffers));
|
||||
__glObj->defineFunction("_deleteShader", _SE(JSB_glDeleteShader));
|
||||
__glObj->defineFunction("_deleteTexture", _SE(JSB_glDeleteTextures));
|
||||
__glObj->defineFunction("depthFunc", _SE(JSB_glDepthFunc));
|
||||
__glObj->defineFunction("depthMask", _SE(JSB_glDepthMask));
|
||||
__glObj->defineFunction("depthRange", _SE(JSB_glDepthRangef));
|
||||
__glObj->defineFunction("detachShader", _SE(JSB_glDetachShader));
|
||||
__glObj->defineFunction("disable", _SE(JSB_glDisable));
|
||||
__glObj->defineFunction("disableVertexAttribArray", _SE(JSB_glDisableVertexAttribArray));
|
||||
__glObj->defineFunction("drawArrays", _SE(JSB_glDrawArrays));
|
||||
__glObj->defineFunction("drawElements", _SE(JSB_glDrawElements));
|
||||
__glObj->defineFunction("enable", _SE(JSB_glEnable));
|
||||
__glObj->defineFunction("enableVertexAttribArray", _SE(JSB_glEnableVertexAttribArray));
|
||||
__glObj->defineFunction("finish", _SE(JSB_glFinish));
|
||||
__glObj->defineFunction("flush", _SE(JSB_glFlush));
|
||||
__glObj->defineFunction("framebufferRenderbuffer", _SE(JSB_glFramebufferRenderbuffer));
|
||||
__glObj->defineFunction("framebufferTexture2D", _SE(JSB_glFramebufferTexture2D));
|
||||
__glObj->defineFunction("frontFace", _SE(JSB_glFrontFace));
|
||||
__glObj->defineFunction("_createBuffer", _SE(JSB_glGenBuffers));
|
||||
__glObj->defineFunction("_createFramebuffer", _SE(JSB_glGenFramebuffers));
|
||||
__glObj->defineFunction("_createRenderbuffer", _SE(JSB_glGenRenderbuffers));
|
||||
__glObj->defineFunction("_createTexture", _SE(JSB_glGenTextures));
|
||||
__glObj->defineFunction("generateMipmap", _SE(JSB_glGenerateMipmap));
|
||||
__glObj->defineFunction("_getActiveAttrib", _SE(JSB_glGetActiveAttrib));
|
||||
__glObj->defineFunction("_getActiveUniform", _SE(JSB_glGetActiveUniform));
|
||||
__glObj->defineFunction("_getAttachedShaders", _SE(JSB_glGetAttachedShaders));
|
||||
__glObj->defineFunction("_getAttribLocation", _SE(JSB_glGetAttribLocation));
|
||||
__glObj->defineFunction("getError", _SE(JSB_glGetError));
|
||||
__glObj->defineFunction("_getProgramInfoLog", _SE(JSB_glGetProgramInfoLog));
|
||||
__glObj->defineFunction("_getProgramParameter", _SE(JSB_glGetProgramiv));
|
||||
__glObj->defineFunction("_getShaderInfoLog", _SE(JSB_glGetShaderInfoLog));
|
||||
__glObj->defineFunction("_getShaderSource", _SE(JSB_glGetShaderSource));
|
||||
__glObj->defineFunction("_getShaderParameter", _SE(JSB_glGetShaderiv));
|
||||
__glObj->defineFunction("getTexParameter", _SE(JSB_glGetTexParameterfv));
|
||||
__glObj->defineFunction("_getUniformLocation", _SE(JSB_glGetUniformLocation));
|
||||
__glObj->defineFunction("_getUniform", _SE(JSB_glGetUniformfv));
|
||||
__glObj->defineFunction("hint", _SE(JSB_glHint));
|
||||
__glObj->defineFunction("isBuffer", _SE(JSB_glIsBuffer));
|
||||
__glObj->defineFunction("isEnabled", _SE(JSB_glIsEnabled));
|
||||
__glObj->defineFunction("isFramebuffer", _SE(JSB_glIsFramebuffer));
|
||||
__glObj->defineFunction("isProgram", _SE(JSB_glIsProgram));
|
||||
__glObj->defineFunction("isRenderbuffer", _SE(JSB_glIsRenderbuffer));
|
||||
__glObj->defineFunction("isShader", _SE(JSB_glIsShader));
|
||||
__glObj->defineFunction("isTexture", _SE(JSB_glIsTexture));
|
||||
__glObj->defineFunction("lineWidth", _SE(JSB_glLineWidth));
|
||||
__glObj->defineFunction("_linkProgram", _SE(JSB_glLinkProgram));
|
||||
__glObj->defineFunction("pixelStorei", _SE(JSB_glPixelStorei));
|
||||
__glObj->defineFunction("polygonOffset", _SE(JSB_glPolygonOffset));
|
||||
__glObj->defineFunction("readPixels", _SE(JSB_glReadPixels));
|
||||
__glObj->defineFunction("releaseShaderCompiler", _SE(JSB_glReleaseShaderCompiler));
|
||||
__glObj->defineFunction("renderbufferStorage", _SE(JSB_glRenderbufferStorage));
|
||||
__glObj->defineFunction("sampleCoverage", _SE(JSB_glSampleCoverage));
|
||||
__glObj->defineFunction("scissor", _SE(JSB_glScissor));
|
||||
__glObj->defineFunction("_shaderSource", _SE(JSB_glShaderSource));
|
||||
__glObj->defineFunction("stencilFunc", _SE(JSB_glStencilFunc));
|
||||
__glObj->defineFunction("stencilFuncSeparate", _SE(JSB_glStencilFuncSeparate));
|
||||
__glObj->defineFunction("stencilMask", _SE(JSB_glStencilMask));
|
||||
__glObj->defineFunction("stencilMaskSeparate", _SE(JSB_glStencilMaskSeparate));
|
||||
__glObj->defineFunction("stencilOp", _SE(JSB_glStencilOp));
|
||||
__glObj->defineFunction("stencilOpSeparate", _SE(JSB_glStencilOpSeparate));
|
||||
__glObj->defineFunction("texImage2D", _SE(JSB_glTexImage2D));
|
||||
__glObj->defineFunction("texParameterf", _SE(JSB_glTexParameterf));
|
||||
__glObj->defineFunction("texParameteri", _SE(JSB_glTexParameteri));
|
||||
__glObj->defineFunction("texSubImage2D", _SE(JSB_glTexSubImage2D));
|
||||
__glObj->defineFunction("uniform1f", _SE(JSB_glUniform1f));
|
||||
__glObj->defineFunction("uniform1fv", _SE(JSB_glUniform1fv));
|
||||
__glObj->defineFunction("uniform1i", _SE(JSB_glUniform1i));
|
||||
__glObj->defineFunction("uniform1iv", _SE(JSB_glUniform1iv));
|
||||
__glObj->defineFunction("uniform2f", _SE(JSB_glUniform2f));
|
||||
__glObj->defineFunction("uniform2fv", _SE(JSB_glUniform2fv));
|
||||
__glObj->defineFunction("uniform2i", _SE(JSB_glUniform2i));
|
||||
__glObj->defineFunction("uniform2iv", _SE(JSB_glUniform2iv));
|
||||
__glObj->defineFunction("uniform3f", _SE(JSB_glUniform3f));
|
||||
__glObj->defineFunction("uniform3fv", _SE(JSB_glUniform3fv));
|
||||
__glObj->defineFunction("uniform3i", _SE(JSB_glUniform3i));
|
||||
__glObj->defineFunction("uniform3iv", _SE(JSB_glUniform3iv));
|
||||
__glObj->defineFunction("uniform4f", _SE(JSB_glUniform4f));
|
||||
__glObj->defineFunction("uniform4fv", _SE(JSB_glUniform4fv));
|
||||
__glObj->defineFunction("uniform4i", _SE(JSB_glUniform4i));
|
||||
__glObj->defineFunction("uniform4iv", _SE(JSB_glUniform4iv));
|
||||
__glObj->defineFunction("uniformMatrix2fv", _SE(JSB_glUniformMatrix2fv));
|
||||
__glObj->defineFunction("uniformMatrix3fv", _SE(JSB_glUniformMatrix3fv));
|
||||
__glObj->defineFunction("uniformMatrix4fv", _SE(JSB_glUniformMatrix4fv));
|
||||
__glObj->defineFunction("_useProgram", _SE(JSB_glUseProgram));
|
||||
__glObj->defineFunction("_validateProgram", _SE(JSB_glValidateProgram));
|
||||
__glObj->defineFunction("vertexAttrib1f", _SE(JSB_glVertexAttrib1f));
|
||||
__glObj->defineFunction("vertexAttrib1fv", _SE(JSB_glVertexAttrib1fv));
|
||||
__glObj->defineFunction("vertexAttrib2f", _SE(JSB_glVertexAttrib2f));
|
||||
__glObj->defineFunction("vertexAttrib2fv", _SE(JSB_glVertexAttrib2fv));
|
||||
__glObj->defineFunction("vertexAttrib3f", _SE(JSB_glVertexAttrib3f));
|
||||
__glObj->defineFunction("vertexAttrib3fv", _SE(JSB_glVertexAttrib3fv));
|
||||
__glObj->defineFunction("vertexAttrib4f", _SE(JSB_glVertexAttrib4f));
|
||||
__glObj->defineFunction("vertexAttrib4fv", _SE(JSB_glVertexAttrib4fv));
|
||||
__glObj->defineFunction("vertexAttribPointer", _SE(JSB_glVertexAttribPointer));
|
||||
__glObj->defineFunction("viewport", _SE(JSB_glViewport));
|
||||
__glObj->defineFunction("getParameter", _SE(JSB_glGetParameter));
|
||||
__glObj->defineFunction("getShaderPrecisionFormat", _SE(JSB_glGetShaderPrecisionFormat));
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
+4
-1
@@ -25,8 +25,11 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
namespace se {
|
||||
class Object;
|
||||
}
|
||||
|
||||
bool JSB_register_opengl(se::Object* obj);
|
||||
bool register_platform_bindings(se::Object* obj);
|
||||
const std::unordered_map<std::string, std::string>& getFontFamilyNameMap();
|
||||
@@ -0,0 +1,66 @@
|
||||
#include "jsb_platform.h"
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_global.h"
|
||||
#include "cocos/platform/CCFileUtils.h"
|
||||
|
||||
#include <regex>
|
||||
|
||||
using namespace cocos2d;
|
||||
|
||||
static std::unordered_map<std::string, std::string> _fontFamilyNameMap;
|
||||
|
||||
const std::unordered_map<std::string, std::string>& getFontFamilyNameMap()
|
||||
{
|
||||
return _fontFamilyNameMap;
|
||||
}
|
||||
|
||||
static bool JSB_loadFont(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc >= 1) {
|
||||
s.rval().setNull();
|
||||
|
||||
std::string originalFamilyName;
|
||||
ok &= seval_to_std_string(args[0], &originalFamilyName);
|
||||
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: originalFamilyName");
|
||||
|
||||
std::string source;
|
||||
ok &= seval_to_std_string(args[1], &source);
|
||||
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source");
|
||||
|
||||
std::string fontFilePath;
|
||||
std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(source.cbegin(), source.cend(), results, re))
|
||||
{
|
||||
fontFilePath = results[1].str();
|
||||
}
|
||||
|
||||
fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath);
|
||||
if (fontFilePath.empty())
|
||||
{
|
||||
SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
JniHelper::callStaticVoidMethod("org/cocos2dx/lib/CanvasRenderingContext2DImpl", "loadTypeface", originalFamilyName, fontFilePath);
|
||||
|
||||
s.rval().setString(originalFamilyName);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_loadFont)
|
||||
|
||||
bool register_platform_bindings(se::Object* obj)
|
||||
{
|
||||
__jsbObj->defineFunction("loadFont", _SE(JSB_loadFont));
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
#import "jsb_platform.h"
|
||||
|
||||
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp"
|
||||
#include "cocos/scripting/js-bindings/manual/jsb_global.h"
|
||||
#include "cocos/platform/CCFileUtils.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreText/CoreText.h>
|
||||
#include <regex>
|
||||
|
||||
using namespace cocos2d;
|
||||
|
||||
static std::unordered_map<std::string, std::string> _fontFamilyNameMap;
|
||||
|
||||
const std::unordered_map<std::string, std::string>& getFontFamilyNameMap()
|
||||
{
|
||||
return _fontFamilyNameMap;
|
||||
}
|
||||
|
||||
static std::vector<std::string> getAvailableFontFamilyNames()
|
||||
{
|
||||
std::vector<std::string> ret;
|
||||
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC
|
||||
CFArrayRef allFamilyNames = CTFontManagerCopyAvailableFontFamilyNames();
|
||||
#else
|
||||
CFArrayRef allFamilyNames = (CFArrayRef) [[UIFont familyNames] retain];
|
||||
#endif
|
||||
|
||||
char buf[256] = {0};
|
||||
for(CFIndex i = 0; i < CFArrayGetCount(allFamilyNames); i++)
|
||||
{
|
||||
CFStringRef fontName = (CFStringRef)CFArrayGetValueAtIndex(allFamilyNames, i);
|
||||
if (CFStringGetCString(fontName, buf, sizeof(buf), kCFStringEncodingUTF8) != 0)
|
||||
{
|
||||
ret.push_back(buf);
|
||||
}
|
||||
}
|
||||
|
||||
CFRelease(allFamilyNames);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static std::string getFontFamilyByCompareAvailableFontFamilyNames(const std::vector<std::string>& before, const std::vector<std::string>& after)
|
||||
{
|
||||
std::string ret;
|
||||
size_t beforeLen = before.size();
|
||||
size_t afterLen = after.size();
|
||||
if (afterLen > beforeLen)
|
||||
{
|
||||
for (size_t i = 0; i < beforeLen; ++i)
|
||||
{
|
||||
if (before[i] != after[i])
|
||||
{
|
||||
ret = after[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ret.empty())
|
||||
ret = after.back();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static bool JSB_loadFont(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc >= 1) {
|
||||
s.rval().setNull();
|
||||
|
||||
std::string originalFamilyName;
|
||||
ok &= seval_to_std_string(args[0], &originalFamilyName);
|
||||
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: originalFamilyName");
|
||||
|
||||
std::string source;
|
||||
ok &= seval_to_std_string(args[1], &source);
|
||||
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source");
|
||||
|
||||
std::string fontFilePath;
|
||||
std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(source.cbegin(), source.cend(), results, re))
|
||||
{
|
||||
fontFilePath = results[1].str();
|
||||
}
|
||||
|
||||
fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath);
|
||||
if (fontFilePath.empty())
|
||||
{
|
||||
SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
NSURL* url = [NSURL fileURLWithPath: [NSString stringWithUTF8String:fontFilePath.c_str()]];
|
||||
NSData* dynamicFontData = [NSData dataWithContentsOfURL:url];
|
||||
if (!dynamicFontData)
|
||||
{
|
||||
SE_LOGE("load font (%s) failed!", source.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
const auto& familyNamesBeforeRegister = getAvailableFontFamilyNames();
|
||||
|
||||
bool succeed = true;
|
||||
CFErrorRef error;
|
||||
CGDataProviderRef providerRef = CGDataProviderCreateWithCFData((CFDataRef)dynamicFontData);
|
||||
CGFontRef font = CGFontCreateWithDataProvider(providerRef);
|
||||
if (!CTFontManagerRegisterGraphicsFont(font, &error))
|
||||
{
|
||||
CFStringRef errorDescription = CFErrorCopyDescription(error);
|
||||
const char* cErrorStr = CFStringGetCStringPtr(errorDescription, kCFStringEncodingUTF8);
|
||||
SE_LOGE("Failed to load font: %s", cErrorStr);
|
||||
CFRelease(errorDescription);
|
||||
succeed = false;
|
||||
}
|
||||
|
||||
if (succeed)
|
||||
{
|
||||
const auto& familyNamesAfterRegister = getAvailableFontFamilyNames();
|
||||
std::string familyName = getFontFamilyByCompareAvailableFontFamilyNames(familyNamesBeforeRegister, familyNamesAfterRegister);
|
||||
if (!familyName.empty())
|
||||
{
|
||||
_fontFamilyNameMap.emplace(originalFamilyName, familyName);
|
||||
s.rval().setString(familyName);
|
||||
}
|
||||
}
|
||||
|
||||
CFRelease(font);
|
||||
CFRelease(providerRef);
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_loadFont)
|
||||
|
||||
bool register_platform_bindings(se::Object* obj)
|
||||
{
|
||||
__jsbObj->defineFunction("loadFont", _SE(JSB_loadFont));
|
||||
return true;
|
||||
}
|
||||
@@ -1,834 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
/* General utilities used throughout devtools. */
|
||||
|
||||
// var { Ci, Cu, Cc, components } = require("chrome");
|
||||
// var Services = require("Services");
|
||||
// var promise = require("promise");
|
||||
|
||||
// loader.lazyRequireGetter(this, "FileUtils",
|
||||
// "resource://gre/modules/FileUtils.jsm", true);
|
||||
|
||||
function DevToolsUtils() {
|
||||
|
||||
}
|
||||
|
||||
DevToolsUtils.utf16to8 = function utf16to8(str) {
|
||||
var out, i, len, c;
|
||||
|
||||
out = "";
|
||||
len = str.length;
|
||||
for(i = 0; i < len; i++)
|
||||
{
|
||||
c = str.charCodeAt(i);
|
||||
if ((c >= 0x0001) && (c <= 0x007F))
|
||||
{
|
||||
out += str.charAt(i);
|
||||
}
|
||||
else if (c > 0x07FF)
|
||||
{
|
||||
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
|
||||
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
|
||||
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
|
||||
}
|
||||
else
|
||||
{
|
||||
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
|
||||
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
DevToolsUtils.utf8to16 = function utf8to16(str) {
|
||||
var out, i, len, c;
|
||||
var char2, char3;
|
||||
|
||||
out = "";
|
||||
len = str.length;
|
||||
i = 0;
|
||||
while(i < len) { c = str.charCodeAt(i++); switch(c >> 4)
|
||||
{
|
||||
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
|
||||
// 0xxxxxxx
|
||||
out += str.charAt(i-1);
|
||||
break;
|
||||
case 12: case 13:
|
||||
// 110x xxxx 10xx xxxx
|
||||
char2 = str.charCodeAt(i++);
|
||||
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
|
||||
break;
|
||||
case 14:
|
||||
// 1110 xxxx 10xx xxxx 10xx xxxx
|
||||
char2 = str.charCodeAt(i++);
|
||||
char3 = str.charCodeAt(i++);
|
||||
out += String.fromCharCode(((c & 0x0F) << 12) |
|
||||
((char2 & 0x3F) << 6) |
|
||||
((char3 & 0x3F) << 0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the error |aError| into a string, without fail.
|
||||
*/
|
||||
DevToolsUtils.safeErrorString = function safeErrorString(aError) {
|
||||
try {
|
||||
let errorString = aError.toString();
|
||||
if (typeof errorString == "string") {
|
||||
// Attempt to attach a stack to |errorString|. If it throws an error, or
|
||||
// isn't a string, don't use it.
|
||||
try {
|
||||
if (aError.stack) {
|
||||
let stack = aError.stack.toString();
|
||||
if (typeof stack == "string") {
|
||||
errorString += "\nStack: " + stack;
|
||||
}
|
||||
}
|
||||
} catch (ee) { }
|
||||
|
||||
// Append additional line and column number information to the output,
|
||||
// since it might not be part of the stringified error.
|
||||
if (typeof aError.lineNumber == "number" && typeof aError.columnNumber == "number") {
|
||||
errorString += "Line: " + aError.lineNumber + ", column: " + aError.columnNumber;
|
||||
}
|
||||
|
||||
return errorString;
|
||||
}
|
||||
} catch (ee) { }
|
||||
|
||||
// We failed to find a good error description, so do the next best thing.
|
||||
return Object.prototype.toString.call(aError);
|
||||
}
|
||||
|
||||
/**
|
||||
* Report that |aWho| threw an exception, |aException|.
|
||||
*/
|
||||
DevToolsUtils.reportException = function reportException(aWho, aException) {
|
||||
let msg = "" + aWho + " threw an exception: " + DevToolsUtils.safeErrorString(aException);
|
||||
|
||||
log(msg + "\n");
|
||||
|
||||
// if (Cu && Cu.reportError) {
|
||||
|
||||
// * Note that the xpcshell test harness registers an observer for
|
||||
// * console messages, so when we're running tests, this will cause
|
||||
// * the test to quit.
|
||||
|
||||
// Cu.reportError(msg);
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a handler function that may throw, return an infallible handler
|
||||
* function that calls the fallible handler, and logs any exceptions it
|
||||
* throws.
|
||||
*
|
||||
* @param aHandler function
|
||||
* A handler function, which may throw.
|
||||
* @param aName string
|
||||
* A name for aHandler, for use in error messages. If omitted, we use
|
||||
* aHandler.name.
|
||||
*
|
||||
* (SpiderMonkey does generate good names for anonymous functions, but we
|
||||
* don't have a way to get at them from JavaScript at the moment.)
|
||||
*/
|
||||
DevToolsUtils.makeInfallible = function makeInfallible(aHandler, aName) {
|
||||
if (!aName)
|
||||
aName = aHandler.name;
|
||||
|
||||
return function (/* arguments */) {
|
||||
try {
|
||||
return aHandler.apply(this, arguments);
|
||||
} catch (ex) {
|
||||
let who = "Handler function";
|
||||
if (aName) {
|
||||
who += " " + aName;
|
||||
}
|
||||
return DevToolsUtils.reportException(who, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Interleaves two arrays element by element, returning the combined array, like
|
||||
* a zip. In the case of arrays with different sizes, undefined values will be
|
||||
* interleaved at the end along with the extra values of the larger array.
|
||||
*
|
||||
* @param Array a
|
||||
* @param Array b
|
||||
* @returns Array
|
||||
* The combined array, in the form [a1, b1, a2, b2, ...]
|
||||
*/
|
||||
DevToolsUtils.zip = function zip(a, b) {
|
||||
if (!b) {
|
||||
return a;
|
||||
}
|
||||
if (!a) {
|
||||
return b;
|
||||
}
|
||||
const pairs = [];
|
||||
for (let i = 0, aLength = a.length, bLength = b.length;
|
||||
i < aLength || i < bLength;
|
||||
i++) {
|
||||
pairs.push([a[i], b[i]]);
|
||||
}
|
||||
return pairs;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Converts an object into an array with 2-element arrays as key/value
|
||||
* pairs of the object. `{ foo: 1, bar: 2}` would become
|
||||
* `[[foo, 1], [bar 2]]` (order not guaranteed);
|
||||
*
|
||||
* @param object obj
|
||||
* @returns array
|
||||
*/
|
||||
DevToolsUtils.entries = function entries(obj) {
|
||||
return Object.keys(obj).map(k => [k, obj[k]]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes the given functions into a single function, which will
|
||||
* apply the results of each function right-to-left, starting with
|
||||
* applying the given arguments to the right-most function.
|
||||
* `compose(foo, bar, baz)` === `args => foo(bar(baz(args)`
|
||||
*
|
||||
* @param ...function funcs
|
||||
* @returns function
|
||||
*/
|
||||
DevToolsUtils.compose = function compose(...funcs) {
|
||||
return (...args) => {
|
||||
const initialValue = funcs[funcs.length - 1].apply(null, args);
|
||||
const leftFuncs = funcs.slice(0, -1);
|
||||
return leftFuncs.reduceRight((composed, f) => f(composed),
|
||||
initialValue);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Waits for the next tick in the event loop to execute a callback.
|
||||
*/
|
||||
DevToolsUtils.executeSoon = function executeSoon(aFn) {
|
||||
if (isWorker) {
|
||||
setImmediate(aFn);
|
||||
} else {
|
||||
let executor;
|
||||
// Only enable async stack reporting when DEBUG_JS_MODULES is set
|
||||
// (customized local builds) to avoid a performance penalty.
|
||||
if (AppConstants.DEBUG_JS_MODULES || flags.testing) {
|
||||
let stack = getStack();
|
||||
executor = () => {
|
||||
callFunctionWithAsyncStack(aFn, stack, "DevToolsUtils.executeSoon");
|
||||
};
|
||||
} else {
|
||||
executor = aFn;
|
||||
}
|
||||
Services.tm.mainThread.dispatch({
|
||||
run: DevToolsUtils.makeInfallible(executor)
|
||||
}, Ci.nsIThread.DISPATCH_NORMAL);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Waits for the next tick in the event loop.
|
||||
*
|
||||
* @return Promise
|
||||
* A promise that is resolved after the next tick in the event loop.
|
||||
*/
|
||||
DevToolsUtils.waitForTick = function waitForTick() {
|
||||
let deferred = Promise.defer();
|
||||
DevToolsUtils.executeSoon(deferred.resolve);
|
||||
return deferred.promise;
|
||||
};
|
||||
|
||||
/**
|
||||
* Waits for the specified amount of time to pass.
|
||||
*
|
||||
* @param number aDelay
|
||||
* The amount of time to wait, in milliseconds.
|
||||
* @return Promise
|
||||
* A promise that is resolved after the specified amount of time passes.
|
||||
*/
|
||||
DevToolsUtils.waitForTime = function waitForTime(aDelay) {
|
||||
let deferred = Promise.defer();
|
||||
require("Timer").setTimeout(deferred.resolve, aDelay);
|
||||
return deferred.promise;
|
||||
};
|
||||
|
||||
/**
|
||||
* Like Array.prototype.forEach, but doesn't cause jankiness when iterating over
|
||||
* very large arrays by yielding to the browser and continuing execution on the
|
||||
* next tick.
|
||||
*
|
||||
* @param Array aArray
|
||||
* The array being iterated over.
|
||||
* @param Function aFn
|
||||
* The function called on each item in the array. If a promise is
|
||||
* returned by this function, iterating over the array will be paused
|
||||
* until the respective promise is resolved.
|
||||
* @returns Promise
|
||||
* A promise that is resolved once the whole array has been iterated
|
||||
* over, and all promises returned by the aFn callback are resolved.
|
||||
*/
|
||||
DevToolsUtils.yieldingEach = function yieldingEach(aArray, aFn) {
|
||||
const deferred = Promise.defer();
|
||||
|
||||
let i = 0;
|
||||
let len = aArray.length;
|
||||
let outstanding = [deferred.promise];
|
||||
|
||||
(function loop() {
|
||||
const start = Date.now();
|
||||
|
||||
while (i < len) {
|
||||
// Don't block the main thread for longer than 16 ms at a time. To
|
||||
// maintain 60fps, you have to render every frame in at least 16ms; we
|
||||
// aren't including time spent in non-JS here, but this is Good
|
||||
// Enough(tm).
|
||||
if (Date.now() - start > 16) {
|
||||
DevToolsUtils.executeSoon(loop);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
outstanding.push(aFn(aArray[i], i++));
|
||||
} catch (e) {
|
||||
deferred.reject(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
deferred.resolve();
|
||||
}());
|
||||
|
||||
return Promise.all(outstanding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like XPCOMUtils.defineLazyGetter, but with a |this| sensitive getter that
|
||||
* allows the lazy getter to be defined on a prototype and work correctly with
|
||||
* instances.
|
||||
*
|
||||
* @param Object aObject
|
||||
* The prototype object to define the lazy getter on.
|
||||
* @param String aKey
|
||||
* The key to define the lazy getter on.
|
||||
* @param Function aCallback
|
||||
* The callback that will be called to determine the value. Will be
|
||||
* called with the |this| value of the current instance.
|
||||
*/
|
||||
DevToolsUtils.defineLazyPrototypeGetter =
|
||||
function defineLazyPrototypeGetter(aObject, aKey, aCallback) {
|
||||
Object.defineProperty(aObject, aKey, {
|
||||
configurable: true,
|
||||
get: function() {
|
||||
const value = aCallback.call(this);
|
||||
|
||||
Object.defineProperty(this, aKey, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: value
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely get the property value from a Debugger.Object for a given key. Walks
|
||||
* the prototype chain until the property is found.
|
||||
*
|
||||
* @param Debugger.Object aObject
|
||||
* The Debugger.Object to get the value from.
|
||||
* @param String aKey
|
||||
* The key to look for.
|
||||
* @return Any
|
||||
*/
|
||||
DevToolsUtils.getProperty = function getProperty(aObj, aKey) {
|
||||
let root = aObj;
|
||||
try {
|
||||
do {
|
||||
const desc = aObj.getOwnPropertyDescriptor(aKey);
|
||||
if (desc) {
|
||||
if ("value" in desc) {
|
||||
return desc.value;
|
||||
}
|
||||
// Call the getter if it's safe.
|
||||
return DevToolsUtils.hasSafeGetter(desc) ? desc.get.call(root).return : undefined;
|
||||
}
|
||||
aObj = aObj.proto;
|
||||
} while (aObj);
|
||||
} catch (e) {
|
||||
// If anything goes wrong report the error and return undefined.
|
||||
DevToolsUtils.reportException("getProperty", e);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a descriptor has a getter which doesn't call into JavaScript.
|
||||
*
|
||||
* @param Object aDesc
|
||||
* The descriptor to check for a safe getter.
|
||||
* @return Boolean
|
||||
* Whether a safe getter was found.
|
||||
*/
|
||||
DevToolsUtils.hasSafeGetter = function hasSafeGetter(aDesc) {
|
||||
// Scripted functions that are CCWs will not appear scripted until after
|
||||
// unwrapping.
|
||||
try {
|
||||
// let fn = aDesc.get.unwrap();
|
||||
let fn = aDesc.get;
|
||||
return fn && fn.callable && fn.class == "Function" && fn.script === undefined;
|
||||
} catch (e) {
|
||||
// Avoid exception 'Object in compartment marked as invisible to Debugger'
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if it is safe to read properties and execute methods from the given JS
|
||||
* object. Safety is defined as being protected from unintended code execution
|
||||
* from content scripts (or cross-compartment code).
|
||||
*
|
||||
* See bugs 945920 and 946752 for discussion.
|
||||
*
|
||||
* @type Object aObj
|
||||
* The object to check.
|
||||
* @return Boolean
|
||||
* True if it is safe to read properties from aObj, or false otherwise.
|
||||
*/
|
||||
DevToolsUtils.isSafeJSObject = function isSafeJSObject(aObj) {
|
||||
return true;
|
||||
// If we are running on a worker thread, Cu is not available. In this case,
|
||||
// we always return false, just to be on the safe side.
|
||||
// if (isWorker) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (Cu.getGlobalForObject(aObj) ==
|
||||
// Cu.getGlobalForObject(DevToolsUtils.isSafeJSObject)) {
|
||||
// return true; // aObj is not a cross-compartment wrapper.
|
||||
// }
|
||||
|
||||
// let principal = Cu.getObjectPrincipal(aObj);
|
||||
// if (Services.scriptSecurityManager.isSystemPrincipal(principal)) {
|
||||
// return true; // allow chrome objects
|
||||
// }
|
||||
|
||||
// return Cu.isXrayWrapper(aObj);
|
||||
};
|
||||
|
||||
DevToolsUtils.dumpn = function dumpn(str) {
|
||||
if (DevToolsUtils.dumpn.wantLogging) {
|
||||
dump("DBG-SERVER: " + str + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
// We want wantLogging to be writable. The DevToolsUtils object is frozen by the
|
||||
// loader, so define it on dumpn instead.
|
||||
DevToolsUtils.dumpn.wantLogging = false;
|
||||
|
||||
/**
|
||||
* A verbose logger for low-level tracing.
|
||||
*/
|
||||
DevToolsUtils.dumpv = function(msg) {
|
||||
if (DevToolsUtils.dumpv.wantVerbose) {
|
||||
DevToolsUtils.dumpn(msg);
|
||||
}
|
||||
};
|
||||
|
||||
// We want wantLogging to be writable. The DevToolsUtils object is frozen by the
|
||||
// loader, so define it on dumpn instead.
|
||||
DevToolsUtils.dumpv.wantVerbose = false;
|
||||
|
||||
DevToolsUtils.assert = function assert(cond, e) {
|
||||
if (!cond) {
|
||||
return e;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Utility function for updating an object with the properties of
|
||||
* other objects.
|
||||
*
|
||||
* @param aTarget Object
|
||||
* The object being updated.
|
||||
* @param aNewAttrs Object
|
||||
* The rest params are objects to update aTarget with. You
|
||||
* can pass as many as you like.
|
||||
*/
|
||||
DevToolsUtils.update = function update(aTarget, ...aArgs) {
|
||||
for (let attrs of aArgs) {
|
||||
for (let key in attrs) {
|
||||
let desc = Object.getOwnPropertyDescriptor(attrs, key);
|
||||
|
||||
if (desc) {
|
||||
Object.defineProperty(aTarget, key, desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return aTarget;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function for getting the values from an object as an array
|
||||
*
|
||||
* @param aObject Object
|
||||
* The object to iterate over
|
||||
*/
|
||||
DevToolsUtils.values = function values(aObject) {
|
||||
return Object.keys(aObject).map(k => aObject[k]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines a getter on a specified object that will be created upon first use.
|
||||
*
|
||||
* @param aObject
|
||||
* The object to define the lazy getter on.
|
||||
* @param aName
|
||||
* The name of the getter to define on aObject.
|
||||
* @param aLambda
|
||||
* A function that returns what the getter should return. This will
|
||||
* only ever be called once.
|
||||
*/
|
||||
DevToolsUtils.defineLazyGetter = function defineLazyGetter(aObject, aName, aLambda) {
|
||||
Object.defineProperty(aObject, aName, {
|
||||
get: function () {
|
||||
delete aObject[aName];
|
||||
return aObject[aName] = aLambda.apply(aObject);
|
||||
},
|
||||
configurable: true,
|
||||
enumerable: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines a getter on a specified object for a module. The module will not
|
||||
* be imported until first use.
|
||||
*
|
||||
* @param aObject
|
||||
* The object to define the lazy getter on.
|
||||
* @param aName
|
||||
* The name of the getter to define on aObject for the module.
|
||||
* @param aResource
|
||||
* The URL used to obtain the module.
|
||||
* @param aSymbol
|
||||
* The name of the symbol exported by the module.
|
||||
* This parameter is optional and defaults to aName.
|
||||
*/
|
||||
DevToolsUtils.defineLazyModuleGetter = function defineLazyModuleGetter(aObject, aName,
|
||||
aResource,
|
||||
aSymbol)
|
||||
{
|
||||
this.defineLazyGetter(aObject, aName, function XPCU_moduleLambda() {
|
||||
var temp = {};
|
||||
Cu.import(aResource, temp);
|
||||
return temp[aSymbol || aName];
|
||||
});
|
||||
};
|
||||
|
||||
DevToolsUtils.defineLazyGetter(this, "NetUtil", () => {
|
||||
return Cu.import("resource://gre/modules/NetUtil.jsm", {}).NetUtil;
|
||||
});
|
||||
|
||||
DevToolsUtils.defineLazyGetter(this, "OS", () => {
|
||||
return Cu.import("resource://gre/modules/osfile.jsm", {}).OS;
|
||||
});
|
||||
|
||||
DevToolsUtils.defineLazyGetter(this, "TextDecoder", () => {
|
||||
return Cu.import("resource://gre/modules/osfile.jsm", {}).TextDecoder;
|
||||
});
|
||||
|
||||
DevToolsUtils.defineLazyGetter(this, "NetworkHelper", () => {
|
||||
return require("devtools/shared/webconsole/network-helper");
|
||||
});
|
||||
|
||||
/**
|
||||
* Performs a request to load the desired URL and returns a promise.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL we will request.
|
||||
* @param aOptions Object
|
||||
* An object with the following optional properties:
|
||||
* - loadFromCache: if false, will bypass the cache and
|
||||
* always load fresh from the network (default: true)
|
||||
* - policy: the nsIContentPolicy type to apply when fetching the URL
|
||||
* (only works when loading from system principal)
|
||||
* - window: the window to get the loadGroup from
|
||||
* - charset: the charset to use if the channel doesn't provide one
|
||||
* - principal: the principal to use, if omitted, the request is loaded
|
||||
* with a codebase principal corresponding to the url being
|
||||
* loaded, using the origin attributes of the window, if any.
|
||||
* - cacheKey: when loading from cache, use this key to retrieve a cache
|
||||
* specific to a given SHEntry. (Allows loading POST
|
||||
* requests from cache)
|
||||
* @returns Promise that resolves with an object with the following members on
|
||||
* success:
|
||||
* - content: the document at that URL, as a string,
|
||||
* - contentType: the content type of the document
|
||||
*
|
||||
* If an error occurs, the promise is rejected with that error.
|
||||
*
|
||||
* XXX: It may be better to use nsITraceableChannel to get to the sources
|
||||
* without relying on caching when we can (not for eval, etc.):
|
||||
* http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/
|
||||
*/
|
||||
function mainThreadFetch(aURL, aOptions = { loadFromCache: true,
|
||||
policy: Ci.nsIContentPolicy.TYPE_OTHER,
|
||||
window: null,
|
||||
charset: null,
|
||||
principal: null,
|
||||
cacheKey: null }) {
|
||||
// Create a channel.
|
||||
let url = aURL.split(" -> ").pop();
|
||||
let channel;
|
||||
try {
|
||||
channel = newChannelForURL(url, aOptions);
|
||||
} catch (ex) {
|
||||
return Promise.reject(ex);
|
||||
}
|
||||
|
||||
// Set the channel options.
|
||||
channel.loadFlags = aOptions.loadFromCache
|
||||
? channel.LOAD_FROM_CACHE
|
||||
: channel.LOAD_BYPASS_CACHE;
|
||||
|
||||
if (aOptions.window) {
|
||||
// Respect private browsing.
|
||||
channel.loadGroup = aOptions.window.QueryInterface(Ci.nsIInterfaceRequestor)
|
||||
.getInterface(Ci.nsIWebNavigation)
|
||||
.QueryInterface(Ci.nsIDocumentLoader)
|
||||
.loadGroup;
|
||||
}
|
||||
|
||||
let deferred = Promise.defer();
|
||||
let onResponse = (stream, status, request) => {
|
||||
// if (!components.isSuccessCode(status)) {
|
||||
// deferred.reject(new Error('Failed to fetch ${url}. Code ${status}.'));
|
||||
// return;
|
||||
// }
|
||||
|
||||
try {
|
||||
// We cannot use NetUtil to do the charset conversion as if charset
|
||||
// information is not available and our default guess is wrong the method
|
||||
// might fail and we lose the stream data. This means we can't fall back
|
||||
// to using the locale default encoding (bug 1181345).
|
||||
|
||||
// Read and decode the data according to the locale default encoding.
|
||||
let available = stream.available();
|
||||
let source = NetUtil.readInputStreamToString(stream, available);
|
||||
stream.close();
|
||||
|
||||
// If the channel or the caller has correct charset information, the
|
||||
// content will be decoded correctly. If we have to fall back to UTF-8 and
|
||||
// the guess is wrong, the conversion fails and convertToUnicode returns
|
||||
// the input unmodified. Essentially we try to decode the data as UTF-8
|
||||
// and if that fails, we use the locale specific default encoding. This is
|
||||
// the best we can do if the source does not provide charset info.
|
||||
let charset = channel.contentCharset || aOptions.charset || "UTF-8";
|
||||
let unicodeSource = NetworkHelper.convertToUnicode(source, charset);
|
||||
|
||||
deferred.resolve({
|
||||
content: unicodeSource,
|
||||
contentType: request.contentType
|
||||
});
|
||||
} catch (ex) {
|
||||
let uri = request.originalURI;
|
||||
if (ex.name === "NS_BASE_STREAM_CLOSED" && uri instanceof Ci.nsIFileURL) {
|
||||
// Empty files cause NS_BASE_STREAM_CLOSED exception. Use OS.File to
|
||||
// differentiate between empty files and other errors (bug 1170864).
|
||||
// This can be removed when bug 982654 is fixed.
|
||||
|
||||
uri.QueryInterface(Ci.nsIFileURL);
|
||||
let result = OS.File.read(uri.file.path).then(bytes => {
|
||||
// Convert the bytearray to a String.
|
||||
let decoder = new TextDecoder();
|
||||
let content = decoder.decode(bytes);
|
||||
|
||||
// We can't detect the contentType without opening a channel
|
||||
// and that failed already. This is the best we can do here.
|
||||
return {
|
||||
content,
|
||||
contentType: "text/plain"
|
||||
};
|
||||
});
|
||||
|
||||
deferred.resolve(result);
|
||||
} else {
|
||||
deferred.reject(ex);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Open the channel
|
||||
try {
|
||||
NetUtil.asyncFetch(channel, onResponse);
|
||||
} catch (ex) {
|
||||
return Promise.reject(ex);
|
||||
}
|
||||
|
||||
return deferred.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a channel for given URL. Tries a bit harder than NetUtil.newChannel.
|
||||
*
|
||||
* @param {String} url - The URL to open a channel for.
|
||||
* @param {Object} options - The options object passed to @method fetch.
|
||||
* @return {nsIChannel} - The newly created channel. Throws on failure.
|
||||
*/
|
||||
function newChannelForURL(url, { policy }) {
|
||||
let channelOptions = {
|
||||
contentPolicyType: policy,
|
||||
loadUsingSystemPrincipal: true,
|
||||
uri: url
|
||||
};
|
||||
|
||||
try {
|
||||
return NetUtil.newChannel(channelOptions);
|
||||
} catch (e) {
|
||||
// In the xpcshell tests, the script url is the absolute path of the test
|
||||
// file, which will make a malformed URI error be thrown. Add the file
|
||||
// scheme to see if it helps.
|
||||
channelOptions.uri = "file://" + url;
|
||||
|
||||
return NetUtil.newChannel(channelOptions);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch is defined differently depending on whether we are on the main thread
|
||||
// or a worker thread.
|
||||
if (!this.isWorker) {
|
||||
DevToolsUtils.fetch = mainThreadFetch;
|
||||
} else {
|
||||
// Services is not available in worker threads, nor is there any other way
|
||||
// to fetch a URL. We need to enlist the help from the main thread here, by
|
||||
// issuing an rpc request, to fetch the URL on our behalf.
|
||||
DevToolsUtils.fetch = function (url, options) {
|
||||
return rpc("fetch", url, options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise that is resolved or rejected when all promises have settled
|
||||
* (resolved or rejected).
|
||||
*
|
||||
* This differs from Promise.all, which will reject immediately after the first
|
||||
* rejection, instead of waiting for the remaining promises to settle.
|
||||
*
|
||||
* @param values
|
||||
* Iterable of promises that may be pending, resolved, or rejected. When
|
||||
* when all promises have settled (resolved or rejected), the returned
|
||||
* promise will be resolved or rejected as well.
|
||||
*
|
||||
* @return A new promise that is fulfilled when all values have settled
|
||||
* (resolved or rejected). Its resolution value will be an array of all
|
||||
* resolved values in the given order, or undefined if values is an
|
||||
* empty array. The reject reason will be forwarded from the first
|
||||
* promise in the list of given promises to be rejected.
|
||||
*/
|
||||
DevToolsUtils.settleAll = values => {
|
||||
if (values === null || typeof(values[Symbol.iterator]) != "function") {
|
||||
throw new Error("settleAll() expects an iterable.");
|
||||
}
|
||||
|
||||
let deferred = Promise.defer();
|
||||
|
||||
values = Array.isArray(values) ? values : [...values];
|
||||
let countdown = values.length;
|
||||
let resolutionValues = new Array(countdown);
|
||||
let rejectionValue;
|
||||
let rejectionOccurred = false;
|
||||
|
||||
if (!countdown) {
|
||||
deferred.resolve(resolutionValues);
|
||||
return deferred.promise;
|
||||
}
|
||||
|
||||
function checkForCompletion() {
|
||||
if (--countdown > 0) {
|
||||
return;
|
||||
}
|
||||
if (!rejectionOccurred) {
|
||||
deferred.resolve(resolutionValues);
|
||||
} else {
|
||||
deferred.reject(rejectionValue);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
let index = i;
|
||||
let value = values[i];
|
||||
let resolver = result => {
|
||||
resolutionValues[index] = result;
|
||||
checkForCompletion();
|
||||
};
|
||||
let rejecter = error => {
|
||||
if (!rejectionOccurred) {
|
||||
rejectionValue = error;
|
||||
rejectionOccurred = true;
|
||||
}
|
||||
checkForCompletion();
|
||||
};
|
||||
|
||||
if (value && typeof(value.then) == "function") {
|
||||
value.then(resolver, rejecter);
|
||||
} else {
|
||||
// Given value is not a promise, forward it as a resolution value.
|
||||
resolver(value);
|
||||
}
|
||||
}
|
||||
|
||||
return deferred.promise;
|
||||
};
|
||||
|
||||
/**
|
||||
* When the testing flag is set, various behaviors may be altered from
|
||||
* production mode, typically to enable easier testing or enhanced debugging.
|
||||
*/
|
||||
var testing = false;
|
||||
Object.defineProperty(DevToolsUtils, "testing", {
|
||||
get: function() {
|
||||
return testing;
|
||||
},
|
||||
set: function(state) {
|
||||
testing = state;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Open the file at the given path for reading.
|
||||
*
|
||||
* @param {String} filePath
|
||||
*
|
||||
* @returns Promise<nsIInputStream>
|
||||
*/
|
||||
DevToolsUtils.openFileStream = function (filePath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const uri = NetUtil.newURI(new FileUtils.File(filePath));
|
||||
NetUtil.asyncFetch(
|
||||
{ uri, loadUsingSystemPrincipal: true },
|
||||
(stream, result) => {
|
||||
// if (!components.isSuccessCode(result)) {
|
||||
// reject(new Error('Could not open "${filePath}": result = ${result}'));
|
||||
// return;
|
||||
// }
|
||||
|
||||
Promise.resolve(stream);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
Remote Debugging By Using FireFox
|
||||
=================================
|
||||
|
||||
Requirement
|
||||
-----------
|
||||
|
||||
* Firefox: From v24
|
||||
|
||||
How To Use
|
||||
----------
|
||||
|
||||
### Prepare ###
|
||||
|
||||
Please refer to https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging .
|
||||
|
||||
### Enable Debugger Support For Your JSB Project ###
|
||||
|
||||
```
|
||||
bool AppDelegate::applicationDidFinishLaunching()
|
||||
{
|
||||
...
|
||||
|
||||
ScriptingCore* sc = ScriptingCore::getInstance();
|
||||
sc->addRegisterCallback(register_all_cocos2dx);
|
||||
sc->addRegisterCallback(register_all_cocos2dx_extension);
|
||||
sc->addRegisterCallback(register_cocos2dx_js_extensions);
|
||||
sc->addRegisterCallback(jsb_register_chipmunk);
|
||||
sc->addRegisterCallback(register_all_cocos2dx_extension_manual);
|
||||
sc->addRegisterCallback(register_CCBuilderReader);
|
||||
sc->addRegisterCallback(jsb_register_system);
|
||||
sc->addRegisterCallback(JSB_register_opengl);
|
||||
|
||||
sc->start();
|
||||
|
||||
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
|
||||
sc->enableDebugger(); // Enable debugger here
|
||||
#endif
|
||||
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Run your game.
|
||||
|
||||
### Open Firefox And Follow The Step As Follows ###
|
||||
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { ActorClassWithSpec } = require("devtools/shared/protocol");
|
||||
// const { breakpointSpec } = require("devtools/shared/specs/breakpoint");
|
||||
|
||||
// from "devtools/shared/specs/breakpoint"
|
||||
const breakpointSpec = generateActorSpec({
|
||||
typeName: "breakpoint",
|
||||
|
||||
methods: {
|
||||
delete: {}
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------
|
||||
|
||||
/**
|
||||
* Set breakpoints on all the given entry points with the given
|
||||
* BreakpointActor as the handler.
|
||||
*
|
||||
* @param BreakpointActor actor
|
||||
* The actor handling the breakpoint hits.
|
||||
* @param Array entryPoints
|
||||
* An array of objects of the form `{ script, offsets }`.
|
||||
*/
|
||||
function setBreakpointAtEntryPoints(actor, entryPoints) {
|
||||
for (let { script, offsets } of entryPoints) {
|
||||
actor.addScript(script);
|
||||
for (let offset of offsets) {
|
||||
script.setBreakpoint(offset, actor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// exports.setBreakpointAtEntryPoints = setBreakpointAtEntryPoints;
|
||||
|
||||
/**
|
||||
* BreakpointActors exist for the lifetime of their containing thread and are
|
||||
* responsible for deleting breakpoints, handling breakpoint hits and
|
||||
* associating breakpoints with scripts.
|
||||
*/
|
||||
let BreakpointActor = ActorClassWithSpec(breakpointSpec, {
|
||||
/**
|
||||
* Create a Breakpoint actor.
|
||||
*
|
||||
* @param ThreadActor threadActor
|
||||
* The parent thread actor that contains this breakpoint.
|
||||
* @param OriginalLocation originalLocation
|
||||
* The original location of the breakpoint.
|
||||
*/
|
||||
initialize: function (threadActor, originalLocation) {
|
||||
// The set of Debugger.Script instances that this breakpoint has been set
|
||||
// upon.
|
||||
this.scripts = new Set();
|
||||
|
||||
this.threadActor = threadActor;
|
||||
this.originalLocation = originalLocation;
|
||||
this.condition = null;
|
||||
this.isPending = true;
|
||||
},
|
||||
|
||||
disconnect: function () {
|
||||
this.removeScripts();
|
||||
},
|
||||
|
||||
hasScript: function (script) {
|
||||
return this.scripts.has(script);
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when this same breakpoint is added to another Debugger.Script
|
||||
* instance.
|
||||
*
|
||||
* @param script Debugger.Script
|
||||
* The new source script on which the breakpoint has been set.
|
||||
*/
|
||||
addScript: function (script) {
|
||||
this.scripts.add(script);
|
||||
this.isPending = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove the breakpoints from associated scripts and clear the script cache.
|
||||
*/
|
||||
removeScripts: function () {
|
||||
for (let script of this.scripts) {
|
||||
script.clearBreakpoint(this);
|
||||
}
|
||||
this.scripts.clear();
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if this breakpoint has a condition that doesn't error and
|
||||
* evaluates to true in frame.
|
||||
*
|
||||
* @param frame Debugger.Frame
|
||||
* The frame to evaluate the condition in
|
||||
* @returns Object
|
||||
* - result: boolean|undefined
|
||||
* True when the conditional breakpoint should trigger a pause,
|
||||
* false otherwise. If the condition evaluation failed/killed,
|
||||
* `result` will be `undefined`.
|
||||
* - message: string
|
||||
* If the condition throws, this is the thrown message.
|
||||
*/
|
||||
checkCondition: function (frame) {
|
||||
let completion = frame.eval(this.condition);
|
||||
if (completion) {
|
||||
if (completion.throw) {
|
||||
// The evaluation failed and threw
|
||||
let message = "Unknown exception";
|
||||
try {
|
||||
if (completion.throw.getOwnPropertyDescriptor) {
|
||||
message = completion.throw.getOwnPropertyDescriptor("message")
|
||||
.value;
|
||||
} else if (completion.toString) {
|
||||
message = completion.toString();
|
||||
}
|
||||
} catch (ex) {}
|
||||
return {
|
||||
result: true,
|
||||
message: message
|
||||
};
|
||||
} else if (completion.yield) {
|
||||
assert(false, "Shouldn't ever get yield completions from an eval");
|
||||
} else {
|
||||
return { result: completion.return ? true : false };
|
||||
}
|
||||
} else {
|
||||
// The evaluation was killed (possibly by the slow script dialog)
|
||||
return { result: undefined };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* A function that the engine calls when a breakpoint has been hit.
|
||||
*
|
||||
* @param frame Debugger.Frame
|
||||
* The stack frame that contained the breakpoint.
|
||||
*/
|
||||
hit: function (frame) {
|
||||
// Don't pause if we are currently stepping (in or over) or the frame is
|
||||
// black-boxed.
|
||||
let generatedLocation = this.threadActor.sources.getFrameLocation(frame);
|
||||
let { originalSourceActor } = this.threadActor.unsafeSynchronize(
|
||||
this.threadActor.sources.getOriginalLocation(generatedLocation));
|
||||
let url = originalSourceActor.url;
|
||||
|
||||
if (this.threadActor.sources.isBlackBoxed(url)
|
||||
|| frame.onStep) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let reason = {};
|
||||
|
||||
if (this.threadActor._hiddenBreakpoints.has(this.actorID)) {
|
||||
reason.type = "pauseOnDOMEvents";
|
||||
} else if (!this.condition) {
|
||||
reason.type = "breakpoint";
|
||||
// TODO: add the rest of the breakpoints on that line (bug 676602).
|
||||
reason.actors = [ this.actorID ];
|
||||
} else {
|
||||
let { result, message } = this.checkCondition(frame);
|
||||
|
||||
if (result) {
|
||||
if (!message) {
|
||||
reason.type = "breakpoint";
|
||||
} else {
|
||||
reason.type = "breakpointConditionThrown";
|
||||
reason.message = message;
|
||||
}
|
||||
reason.actors = [ this.actorID ];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return this.threadActor._pauseAndRespond(frame, reason);
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a protocol request to remove this breakpoint.
|
||||
*/
|
||||
delete: function () {
|
||||
// Remove from the breakpoint store.
|
||||
if (this.originalLocation) {
|
||||
this.threadActor.breakpointActorMap.deleteActor(this.originalLocation);
|
||||
}
|
||||
this.threadActor.threadLifetimePool.removeActor(this);
|
||||
// Remove the actual breakpoint from the associated scripts.
|
||||
this.removeScripts();
|
||||
}
|
||||
});
|
||||
|
||||
// exports.BreakpointActor = BreakpointActor;
|
||||
@@ -1,512 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* Creates "registered" actors factory meant for creating another kind of
|
||||
* factories, ObservedActorFactory, during the call to listTabs.
|
||||
* These factories live in DebuggerServer.{tab|global}ActorFactories.
|
||||
*
|
||||
* These actors only exposes:
|
||||
* - `name` string attribute used to match actors by constructor name
|
||||
* in DebuggerServer.remove{Global,Tab}Actor.
|
||||
* - `createObservedActorFactory` function to create "observed" actors factory
|
||||
*
|
||||
* @param options object, function
|
||||
* Either an object or a function.
|
||||
* If given an object:
|
||||
*
|
||||
* If given a function (deprecated):
|
||||
* Constructor function of an actor.
|
||||
* The constructor function for this actor type.
|
||||
* This expects to be called as a constructor (i.e. with 'new'),
|
||||
* and passed two arguments: the DebuggerServerConnection, and
|
||||
* the BrowserTabActor with which it will be associated.
|
||||
* Only used for deprecated eagerly loaded actors.
|
||||
*
|
||||
*/
|
||||
function RegisteredActorFactory(options, prefix) {
|
||||
// By default the actor name will also be used for the actorID prefix.
|
||||
this._prefix = prefix;
|
||||
if (typeof (options) != "function") {
|
||||
// actors definition registered by actorRegistryActor
|
||||
if (options.constructorFun) {
|
||||
this._getConstructor = () => options.constructorFun;
|
||||
} else {
|
||||
// Lazy actor definition, where options contains all the information
|
||||
// required to load the actor lazily.
|
||||
this._getConstructor = function () {
|
||||
// Load the module
|
||||
let mod;
|
||||
try {
|
||||
mod = require(options.id);
|
||||
} catch (e) {
|
||||
throw new Error("Unable to load actor module '" + options.id + "'.\n" +
|
||||
e.message + "\n" + e.stack + "\n");
|
||||
}
|
||||
// Fetch the actor constructor
|
||||
let c = mod[options.constructorName];
|
||||
if (!c) {
|
||||
throw new Error("Unable to find actor constructor named '" +
|
||||
options.constructorName + "'. (Is it exported?)");
|
||||
}
|
||||
return c;
|
||||
};
|
||||
}
|
||||
// Exposes `name` attribute in order to allow removeXXXActor to match
|
||||
// the actor by its actor constructor name.
|
||||
this.name = options.constructorName;
|
||||
} else {
|
||||
// Old actor case, where options is a function that is the actor constructor.
|
||||
this._getConstructor = () => options;
|
||||
// Exposes `name` attribute in order to allow removeXXXActor to match
|
||||
// the actor by its actor constructor name.
|
||||
this.name = options.name;
|
||||
|
||||
// For old actors, we allow the use of a different prefix for actorID
|
||||
// than for listTabs actor names, by fetching a prefix on the actor prototype.
|
||||
// (Used by ChromeDebuggerActor)
|
||||
if (options.prototype && options.prototype.actorPrefix) {
|
||||
this._prefix = options.prototype.actorPrefix;
|
||||
}
|
||||
}
|
||||
}
|
||||
RegisteredActorFactory.prototype.createObservedActorFactory = function (conn, parentActor) {
|
||||
return new ObservedActorFactory(this._getConstructor, this._prefix, conn, parentActor);
|
||||
};
|
||||
// exports.RegisteredActorFactory = RegisteredActorFactory;
|
||||
|
||||
/**
|
||||
* Creates "observed" actors factory meant for creating real actor instances.
|
||||
* These factories lives in actor pools and fake various actor attributes.
|
||||
* They will be replaced in actor pools by final actor instances during
|
||||
* the first request for the same actorID from DebuggerServer._getOrCreateActor.
|
||||
*
|
||||
* ObservedActorFactory fakes the following actors attributes:
|
||||
* actorPrefix (string) Used by ActorPool.addActor to compute the actor id
|
||||
* actorID (string) Set by ActorPool.addActor just after being instantiated
|
||||
* registeredPool (object) Set by ActorPool.addActor just after being
|
||||
* instantiated
|
||||
* And exposes the following method:
|
||||
* createActor (function) Instantiate an actor that is going to replace
|
||||
* this factory in the actor pool.
|
||||
*/
|
||||
function ObservedActorFactory(getConstructor, prefix, conn, parentActor) {
|
||||
this._getConstructor = getConstructor;
|
||||
this._conn = conn;
|
||||
this._parentActor = parentActor;
|
||||
|
||||
this.actorPrefix = prefix;
|
||||
|
||||
this.actorID = null;
|
||||
this.registeredPool = null;
|
||||
}
|
||||
ObservedActorFactory.prototype.createActor = function () {
|
||||
// Fetch the actor constructor
|
||||
let c = this._getConstructor();
|
||||
// Instantiate a new actor instance
|
||||
let instance = new c(this._conn, this._parentActor);
|
||||
instance.conn = this._conn;
|
||||
instance.parentID = this._parentActor.actorID;
|
||||
// We want the newly-constructed actor to completely replace the factory
|
||||
// actor. Reusing the existing actor ID will make sure ActorPool.addActor
|
||||
// does the right thing.
|
||||
instance.actorID = this.actorID;
|
||||
this.registeredPool.addActor(instance);
|
||||
return instance;
|
||||
};
|
||||
// exports.ObservedActorFactory = ObservedActorFactory;
|
||||
|
||||
|
||||
/**
|
||||
* Methods shared between RootActor and BrowserTabActor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Populate |this._extraActors| as specified by |aFactories|, reusing whatever
|
||||
* actors are already there. Add all actors in the final extra actors table to
|
||||
* |aPool|.
|
||||
*
|
||||
* The root actor and the tab actor use this to instantiate actors that other
|
||||
* parts of the browser have specified with DebuggerServer.addTabActor and
|
||||
* DebuggerServer.addGlobalActor.
|
||||
*
|
||||
* @param aFactories
|
||||
* An object whose own property names are the names of properties to add to
|
||||
* some reply packet (say, a tab actor grip or the "listTabs" response
|
||||
* form), and whose own property values are actor constructor functions, as
|
||||
* documented for addTabActor and addGlobalActor.
|
||||
*
|
||||
* @param this
|
||||
* The BrowserRootActor or BrowserTabActor with which the new actors will
|
||||
* be associated. It should support whatever API the |aFactories|
|
||||
* constructor functions might be interested in, as it is passed to them.
|
||||
* For the sake of CommonCreateExtraActors itself, it should have at least
|
||||
* the following properties:
|
||||
*
|
||||
* - _extraActors
|
||||
* An object whose own property names are factory table (and packet)
|
||||
* property names, and whose values are no-argument actor constructors,
|
||||
* of the sort that one can add to an ActorPool.
|
||||
*
|
||||
* - conn
|
||||
* The DebuggerServerConnection in which the new actors will participate.
|
||||
*
|
||||
* - actorID
|
||||
* The actor's name, for use as the new actors' parentID.
|
||||
*/
|
||||
function createExtraActors(aFactories, aPool) {
|
||||
// Walk over global actors added by extensions.
|
||||
for (let name in aFactories) {
|
||||
let actor = this._extraActors[name];
|
||||
if (!actor) {
|
||||
// Register another factory, but this time specific to this connection.
|
||||
// It creates a fake actor that looks like an regular actor in the pool,
|
||||
// but without actually instantiating the actor.
|
||||
// It will only be instantiated on the first request made to the actor.
|
||||
actor = aFactories[name].createObservedActorFactory(this.conn, this);
|
||||
this._extraActors[name] = actor;
|
||||
}
|
||||
|
||||
// If the actor already exists in the pool, it may have been instantiated,
|
||||
// so make sure not to overwrite it by a non-instantiated version.
|
||||
if (!aPool.has(actor.actorID)) {
|
||||
aPool.addActor(actor);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Append the extra actors in |this._extraActors|, constructed by a prior call
|
||||
* to CommonCreateExtraActors, to |aObject|.
|
||||
*
|
||||
* @param aObject
|
||||
* The object to which the extra actors should be added, under the
|
||||
* property names given in the |aFactories| table passed to
|
||||
* CommonCreateExtraActors.
|
||||
*
|
||||
* @param this
|
||||
* The BrowserRootActor or BrowserTabActor whose |_extraActors| table we
|
||||
* should use; see above.
|
||||
*/
|
||||
function appendExtraActors(aObject) {
|
||||
for (let name in this._extraActors) {
|
||||
let actor = this._extraActors[name];
|
||||
aObject[name] = actor.actorID;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Construct an ActorPool.
|
||||
*
|
||||
* ActorPools are actorID -> actor mapping and storage. These are
|
||||
* used to accumulate and quickly dispose of groups of actors that
|
||||
* share a lifetime.
|
||||
*/
|
||||
function ActorPool(aConnection)
|
||||
{
|
||||
this.conn = aConnection;
|
||||
this._actors = {};
|
||||
}
|
||||
|
||||
ActorPool.prototype = {
|
||||
/**
|
||||
* Destroy the pool. This will remove all actors from the pool.
|
||||
*/
|
||||
destroy: function AP_destroy() {
|
||||
for (let id in this._actors) {
|
||||
this.removeActor(this._actors[id]);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an actor to the pool. If the actor doesn't have an ID, allocate one
|
||||
* from the connection.
|
||||
*
|
||||
* @param Object aActor
|
||||
* The actor to be added to the pool.
|
||||
*/
|
||||
addActor: function AP_addActor(aActor) {
|
||||
aActor.conn = this.conn;
|
||||
if (!aActor.actorID) {
|
||||
let prefix = aActor.actorPrefix;
|
||||
if (!prefix && typeof aActor == "function") {
|
||||
// typeName is a convention used with protocol.js-based actors
|
||||
prefix = aActor.prototype.actorPrefix || aActor.prototype.typeName;
|
||||
}
|
||||
aActor.actorID = this.conn.allocID(prefix || undefined);
|
||||
}
|
||||
|
||||
// If the actor is already in a pool, remove it without destroying it.
|
||||
if (aActor.registeredPool) {
|
||||
delete aActor.registeredPool._actors[aActor.actorID];
|
||||
}
|
||||
aActor.registeredPool = this;
|
||||
|
||||
this._actors[aActor.actorID] = aActor;
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an actor from the pool. If the actor has a disconnect method, call
|
||||
* it.
|
||||
*/
|
||||
removeActor: function AP_remove(aActor) {
|
||||
delete this._actors[aActor.actorID];
|
||||
if (aActor.disconnect) {
|
||||
aActor.disconnect();
|
||||
}
|
||||
},
|
||||
|
||||
get: function AP_get(aActorID) {
|
||||
return this._actors[aActorID] || undefined;
|
||||
},
|
||||
|
||||
has: function AP_has(aActorID) {
|
||||
return aActorID in this._actors;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the pool is empty.
|
||||
*/
|
||||
isEmpty: function AP_isEmpty() {
|
||||
return Object.keys(this._actors).length == 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Match the api expected by the protocol library.
|
||||
*/
|
||||
unmanage: function (aActor) {
|
||||
return this.removeActor(aActor);
|
||||
},
|
||||
|
||||
forEach: function (callback) {
|
||||
for (let name in this._actors) {
|
||||
callback(this._actors[name]);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// exports.ActorPool = ActorPool;
|
||||
|
||||
/**
|
||||
* An OriginalLocation represents a location in an original source.
|
||||
*
|
||||
* @param SourceActor actor
|
||||
* A SourceActor representing an original source.
|
||||
* @param Number line
|
||||
* A line within the given source.
|
||||
* @param Number column
|
||||
* A column within the given line.
|
||||
* @param String name
|
||||
* The name of the symbol corresponding to this OriginalLocation.
|
||||
*/
|
||||
|
||||
function OriginalLocation(actor, line, column, name) {
|
||||
this._connection = actor ? actor.conn : null;
|
||||
this._actorID = actor ? actor.actorID : undefined;
|
||||
this._line = line;
|
||||
this._column = column;
|
||||
this._name = name;
|
||||
}
|
||||
|
||||
OriginalLocation.fromGeneratedLocation = function (generatedLocation) {
|
||||
return new OriginalLocation(
|
||||
generatedLocation.generatedSourceActor,
|
||||
generatedLocation.generatedLine,
|
||||
generatedLocation.generatedColumn
|
||||
);
|
||||
};
|
||||
|
||||
OriginalLocation.prototype = {
|
||||
get originalSourceActor() {
|
||||
return this._connection ? this._connection.getActor(this._actorID) : null;
|
||||
},
|
||||
|
||||
get originalUrl() {
|
||||
let actor = this.originalSourceActor;
|
||||
let source = actor.source;
|
||||
return source ? source.url : actor._originalUrl;
|
||||
},
|
||||
|
||||
get originalLine() {
|
||||
return this._line;
|
||||
},
|
||||
|
||||
get originalColumn() {
|
||||
return this._column;
|
||||
},
|
||||
|
||||
get originalName() {
|
||||
return this._name;
|
||||
},
|
||||
|
||||
get generatedSourceActor() {
|
||||
throw new Error("Shouldn't access generatedSourceActor from an OriginalLocation");
|
||||
},
|
||||
|
||||
get generatedLine() {
|
||||
throw new Error("Shouldn't access generatedLine from an OriginalLocation");
|
||||
},
|
||||
|
||||
get generatedColumn() {
|
||||
throw new Error("Shouldn't access generatedColumn from an Originallocation");
|
||||
},
|
||||
|
||||
equals: function (other) {
|
||||
return this.originalSourceActor.url == other.originalSourceActor.url &&
|
||||
this.originalLine === other.originalLine &&
|
||||
(this.originalColumn === undefined ||
|
||||
other.originalColumn === undefined ||
|
||||
this.originalColumn === other.originalColumn);
|
||||
},
|
||||
|
||||
toJSON: function () {
|
||||
return {
|
||||
source: this.originalSourceActor.form(),
|
||||
line: this.originalLine,
|
||||
column: this.originalColumn
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A GeneratedLocation represents a location in a generated source.
|
||||
*
|
||||
* @param SourceActor actor
|
||||
* A SourceActor representing a generated source.
|
||||
* @param Number line
|
||||
* A line within the given source.
|
||||
* @param Number column
|
||||
* A column within the given line.
|
||||
*/
|
||||
function GeneratedLocation(actor, line, column, lastColumn) {
|
||||
this._connection = actor ? actor.conn : null;
|
||||
this._actorID = actor ? actor.actorID : undefined;
|
||||
this._line = line;
|
||||
this._column = column;
|
||||
this._lastColumn = (lastColumn !== undefined) ? lastColumn : column + 1;
|
||||
}
|
||||
|
||||
GeneratedLocation.fromOriginalLocation = function (originalLocation) {
|
||||
return new GeneratedLocation(
|
||||
originalLocation.originalSourceActor,
|
||||
originalLocation.originalLine,
|
||||
originalLocation.originalColumn
|
||||
);
|
||||
};
|
||||
|
||||
GeneratedLocation.prototype = {
|
||||
get originalSourceActor() {
|
||||
throw new Error();
|
||||
},
|
||||
|
||||
get originalUrl() {
|
||||
throw new Error("Shouldn't access originalUrl from a GeneratedLocation");
|
||||
},
|
||||
|
||||
get originalLine() {
|
||||
throw new Error("Shouldn't access originalLine from a GeneratedLocation");
|
||||
},
|
||||
|
||||
get originalColumn() {
|
||||
throw new Error("Shouldn't access originalColumn from a GeneratedLocation");
|
||||
},
|
||||
|
||||
get originalName() {
|
||||
throw new Error("Shouldn't access originalName from a GeneratedLocation");
|
||||
},
|
||||
|
||||
get generatedSourceActor() {
|
||||
return this._connection ? this._connection.getActor(this._actorID) : null;
|
||||
},
|
||||
|
||||
get generatedLine() {
|
||||
return this._line;
|
||||
},
|
||||
|
||||
get generatedColumn() {
|
||||
return this._column;
|
||||
},
|
||||
|
||||
get generatedLastColumn() {
|
||||
return this._lastColumn;
|
||||
},
|
||||
|
||||
equals: function (other) {
|
||||
return this.generatedSourceActor.url == other.generatedSourceActor.url &&
|
||||
this.generatedLine === other.generatedLine &&
|
||||
(this.generatedColumn === undefined ||
|
||||
other.generatedColumn === undefined ||
|
||||
this.generatedColumn === other.generatedColumn);
|
||||
},
|
||||
|
||||
toJSON: function () {
|
||||
return {
|
||||
source: this.generatedSourceActor.form(),
|
||||
line: this.generatedLine,
|
||||
column: this.generatedColumn,
|
||||
lastColumn: this.generatedLastColumn
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A method decorator that ensures the actor is in the expected state before
|
||||
* proceeding. If the actor is not in the expected state, the decorated method
|
||||
* returns a rejected promise.
|
||||
*
|
||||
* The actor's state must be at this.state property.
|
||||
*
|
||||
* @param String expectedState
|
||||
* The expected state.
|
||||
* @param String activity
|
||||
* Additional info about what's going on.
|
||||
* @param Function method
|
||||
* The actor method to proceed with when the actor is in the expected
|
||||
* state.
|
||||
*
|
||||
* @returns Function
|
||||
* The decorated method.
|
||||
*/
|
||||
function expectState(expectedState, method, activity) {
|
||||
return function (...args) {
|
||||
if (this.state !== expectedState) {
|
||||
const msg = `Wrong state while ${activity}:` +
|
||||
`Expected '${expectedState}', ` +
|
||||
`but current state is '${this.state}'.`;
|
||||
return Promise.reject(new Error(msg));
|
||||
}
|
||||
|
||||
return method.apply(this, args);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxies a call from an actor to an underlying module, stored
|
||||
* as `bridge` on the actor. This allows a module to be defined in one
|
||||
* place, usable by other modules/actors on the server, but a separate
|
||||
* module defining the actor/RDP definition.
|
||||
*
|
||||
* @see Framerate implementation: devtools/server/performance/framerate.js
|
||||
* @see Framerate actor definition: devtools/server/actors/framerate.js
|
||||
*/
|
||||
function actorBridge(methodName, definition = {}) {
|
||||
return method(function () {
|
||||
return this.bridge[methodName].apply(this.bridge, arguments);
|
||||
}, definition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `actorBridge`, but without a spec definition, for when the actor is
|
||||
* created with `ActorClassWithSpec` rather than vanilla `ActorClass`.
|
||||
*/
|
||||
function actorBridgeWithSpec (methodName) {
|
||||
return method(function () {
|
||||
return this.bridge[methodName].apply(this.bridge, arguments);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
"use strict";
|
||||
|
||||
// const { ActorClassWithSpec } = require("devtools/shared/protocol");
|
||||
// const { createValueGrip } = require("devtools/server/actors/object");
|
||||
// const { environmentSpec } = require("devtools/shared/specs/environment");
|
||||
|
||||
// from "devtools/shared/specs/environment"
|
||||
const environmentSpec = generateActorSpec({
|
||||
typeName: "environment",
|
||||
|
||||
methods: {
|
||||
assign: {
|
||||
request: {
|
||||
name: Arg(1),
|
||||
value: Arg(2)
|
||||
}
|
||||
},
|
||||
bindings: {
|
||||
request: {},
|
||||
response: {
|
||||
bindings: RetVal("json")
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// ------------
|
||||
|
||||
/**
|
||||
* Creates an EnvironmentActor. EnvironmentActors are responsible for listing
|
||||
* the bindings introduced by a lexical environment and assigning new values to
|
||||
* those identifier bindings.
|
||||
*
|
||||
* @param Debugger.Environment aEnvironment
|
||||
* The lexical environment that will be used to create the actor.
|
||||
* @param ThreadActor aThreadActor
|
||||
* The parent thread actor that contains this environment.
|
||||
*/
|
||||
let EnvironmentActor = ActorClassWithSpec(environmentSpec, {
|
||||
initialize: function (environment, threadActor) {
|
||||
this.obj = environment;
|
||||
this.threadActor = threadActor;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return an environment form for use in a protocol message.
|
||||
*/
|
||||
form: function () {
|
||||
let form = { actor: this.actorID };
|
||||
|
||||
// What is this environment's type?
|
||||
if (this.obj.type == "declarative") {
|
||||
form.type = this.obj.callee ? "function" : "block";
|
||||
} else {
|
||||
form.type = this.obj.type;
|
||||
}
|
||||
|
||||
// Does this environment have a parent?
|
||||
if (this.obj.parent) {
|
||||
form.parent = (this.threadActor
|
||||
.createEnvironmentActor(this.obj.parent,
|
||||
this.registeredPool)
|
||||
.form());
|
||||
}
|
||||
|
||||
// Does this environment reflect the properties of an object as variables?
|
||||
if (this.obj.type == "object" || this.obj.type == "with") {
|
||||
form.object = createValueGrip(this.obj.object,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
}
|
||||
|
||||
// Is this the environment created for a function call?
|
||||
if (this.obj.callee) {
|
||||
form.function = createValueGrip(this.obj.callee,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
}
|
||||
|
||||
// Shall we list this environment's bindings?
|
||||
if (this.obj.type == "declarative") {
|
||||
form.bindings = this.bindings();
|
||||
}
|
||||
|
||||
return form;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a protocol request to change the value of a variable bound in this
|
||||
* lexical environment.
|
||||
*
|
||||
* @param string name
|
||||
* The name of the variable to be changed.
|
||||
* @param any value
|
||||
* The value to be assigned.
|
||||
*/
|
||||
assign: function (name, value) {
|
||||
// TODO: enable the commented-out part when getVariableDescriptor lands
|
||||
// (bug 725815).
|
||||
/* let desc = this.obj.getVariableDescriptor(name);
|
||||
|
||||
if (!desc.writable) {
|
||||
return { error: "immutableBinding",
|
||||
message: "Changing the value of an immutable binding is not " +
|
||||
"allowed" };
|
||||
}*/
|
||||
|
||||
try {
|
||||
this.obj.setVariable(name, value);
|
||||
} catch (e) {
|
||||
if (e instanceof Debugger.DebuggeeWouldRun) {
|
||||
throw {
|
||||
error: "threadWouldRun",
|
||||
message: "Assigning a value would cause the debuggee to run"
|
||||
};
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return { from: this.actorID };
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a protocol request to fully enumerate the bindings introduced by the
|
||||
* lexical environment.
|
||||
*/
|
||||
bindings: function () {
|
||||
let bindings = { arguments: [], variables: {} };
|
||||
|
||||
// TODO: this part should be removed in favor of the commented-out part
|
||||
// below when getVariableDescriptor lands (bug 725815).
|
||||
if (typeof this.obj.getVariable != "function") {
|
||||
// if (typeof this.obj.getVariableDescriptor != "function") {
|
||||
return bindings;
|
||||
}
|
||||
|
||||
let parameterNames;
|
||||
if (this.obj.callee) {
|
||||
parameterNames = this.obj.callee.parameterNames;
|
||||
} else {
|
||||
parameterNames = [];
|
||||
}
|
||||
for (let name of parameterNames) {
|
||||
let arg = {};
|
||||
let value = this.obj.getVariable(name);
|
||||
|
||||
// TODO: this part should be removed in favor of the commented-out part
|
||||
// below when getVariableDescriptor lands (bug 725815).
|
||||
let desc = {
|
||||
value: value,
|
||||
configurable: false,
|
||||
writable: !(value && value.optimizedOut),
|
||||
enumerable: true
|
||||
};
|
||||
|
||||
// let desc = this.obj.getVariableDescriptor(name);
|
||||
let descForm = {
|
||||
enumerable: true,
|
||||
configurable: desc.configurable
|
||||
};
|
||||
if ("value" in desc) {
|
||||
descForm.value = createValueGrip(desc.value,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
descForm.writable = desc.writable;
|
||||
} else {
|
||||
descForm.get = createValueGrip(desc.get, this.registeredPool,
|
||||
this.threadActor.objectGrip);
|
||||
descForm.set = createValueGrip(desc.set, this.registeredPool,
|
||||
this.threadActor.objectGrip);
|
||||
}
|
||||
arg[name] = descForm;
|
||||
bindings.arguments.push(arg);
|
||||
}
|
||||
|
||||
for (let name of this.obj.names()) {
|
||||
if (bindings.arguments.some(function exists(element) {
|
||||
return !!element[name];
|
||||
})) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let value = this.obj.getVariable(name);
|
||||
|
||||
// TODO: this part should be removed in favor of the commented-out part
|
||||
// below when getVariableDescriptor lands.
|
||||
let desc = {
|
||||
value: value,
|
||||
configurable: false,
|
||||
writable: !(value &&
|
||||
(value.optimizedOut ||
|
||||
value.uninitialized ||
|
||||
value.missingArguments)),
|
||||
enumerable: true
|
||||
};
|
||||
|
||||
// let desc = this.obj.getVariableDescriptor(name);
|
||||
let descForm = {
|
||||
enumerable: true,
|
||||
configurable: desc.configurable
|
||||
};
|
||||
if ("value" in desc) {
|
||||
descForm.value = createValueGrip(desc.value,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
descForm.writable = desc.writable;
|
||||
} else {
|
||||
descForm.get = createValueGrip(desc.get || undefined,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
descForm.set = createValueGrip(desc.set || undefined,
|
||||
this.registeredPool, this.threadActor.objectGrip);
|
||||
}
|
||||
bindings.variables[name] = descForm;
|
||||
}
|
||||
|
||||
return bindings;
|
||||
}
|
||||
});
|
||||
|
||||
// exports.EnvironmentActor = EnvironmentActor;
|
||||
@@ -1,109 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { ActorPool } = require("devtools/server/actors/common");
|
||||
// const { createValueGrip } = require("devtools/server/actors/object");
|
||||
// const { ActorClassWithSpec } = require("devtools/shared/protocol");
|
||||
// const { frameSpec } = require("devtools/shared/specs/frame");
|
||||
|
||||
// from "devtools/shared/specs/frame"
|
||||
const frameSpec = generateActorSpec({
|
||||
typeName: "frame",
|
||||
|
||||
methods: {},
|
||||
});
|
||||
|
||||
// --------------
|
||||
|
||||
/**
|
||||
* An actor for a specified stack frame.
|
||||
*/
|
||||
let FrameActor = ActorClassWithSpec(frameSpec, {
|
||||
/**
|
||||
* Creates the Frame actor.
|
||||
*
|
||||
* @param frame Debugger.Frame
|
||||
* The debuggee frame.
|
||||
* @param threadActor ThreadActor
|
||||
* The parent thread actor for this frame.
|
||||
*/
|
||||
initialize: function (frame, threadActor) {
|
||||
this.frame = frame;
|
||||
this.threadActor = threadActor;
|
||||
},
|
||||
|
||||
/**
|
||||
* A pool that contains frame-lifetime objects, like the environment.
|
||||
*/
|
||||
_frameLifetimePool: null,
|
||||
get frameLifetimePool() {
|
||||
if (!this._frameLifetimePool) {
|
||||
this._frameLifetimePool = new ActorPool(this.conn);
|
||||
this.conn.addActorPool(this._frameLifetimePool);
|
||||
}
|
||||
return this._frameLifetimePool;
|
||||
},
|
||||
|
||||
/**
|
||||
* Finalization handler that is called when the actor is being evicted from
|
||||
* the pool.
|
||||
*/
|
||||
disconnect: function () {
|
||||
this.conn.removeActorPool(this._frameLifetimePool);
|
||||
this._frameLifetimePool = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a frame form for use in a protocol message.
|
||||
*/
|
||||
form: function () {
|
||||
let threadActor = this.threadActor;
|
||||
let form = { actor: this.actorID,
|
||||
type: this.frame.type };
|
||||
if (this.frame.type === "call") {
|
||||
form.callee = createValueGrip(this.frame.callee, threadActor._pausePool,
|
||||
threadActor.objectGrip);
|
||||
}
|
||||
|
||||
if (this.frame.environment) {
|
||||
let envActor = threadActor.createEnvironmentActor(
|
||||
this.frame.environment,
|
||||
this.frameLifetimePool
|
||||
);
|
||||
form.environment = envActor.form();
|
||||
}
|
||||
form.this = createValueGrip(this.frame.this, threadActor._pausePool,
|
||||
threadActor.objectGrip);
|
||||
form.arguments = this._args();
|
||||
if (this.frame.script) {
|
||||
var generatedLocation = this.threadActor.sources.getFrameLocation(this.frame);
|
||||
form.where = {
|
||||
source: generatedLocation.generatedSourceActor.form(),
|
||||
line: generatedLocation.generatedLine,
|
||||
column: generatedLocation.generatedColumn
|
||||
};
|
||||
}
|
||||
|
||||
if (!this.frame.older) {
|
||||
form.oldest = true;
|
||||
}
|
||||
|
||||
return form;
|
||||
},
|
||||
|
||||
_args: function () {
|
||||
if (!this.frame.arguments) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.frame.arguments.map(arg => createValueGrip(arg,
|
||||
this.threadActor._pausePool, this.threadActor.objectGrip));
|
||||
}
|
||||
});
|
||||
|
||||
// exports.FrameActor = FrameActor;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,536 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { Cc, Ci, Cu } = require("chrome");
|
||||
// const Services = require("Services");
|
||||
// const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common");
|
||||
// const { DebuggerServer } = require("devtools/server/main");
|
||||
|
||||
// loader.lazyGetter(this, "ppmm", () => {
|
||||
// return Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster);
|
||||
// });
|
||||
|
||||
/* Root actor for the remote debugging protocol. */
|
||||
|
||||
/**
|
||||
* Create a remote debugging protocol root actor.
|
||||
*
|
||||
* @param aConnection
|
||||
* The DebuggerServerConnection whose root actor we are constructing.
|
||||
*
|
||||
* @param aParameters
|
||||
* The properties of |aParameters| provide backing objects for the root
|
||||
* actor's requests; if a given property is omitted from |aParameters|, the
|
||||
* root actor won't implement the corresponding requests or notifications.
|
||||
* Supported properties:
|
||||
*
|
||||
* - tabList: a live list (see below) of tab actors. If present, the
|
||||
* new root actor supports the 'listTabs' request, providing the live
|
||||
* list's elements as its tab actors, and sending 'tabListChanged'
|
||||
* notifications when the live list's contents change. One actor in
|
||||
* this list must have a true '.selected' property.
|
||||
*
|
||||
* - addonList: a live list (see below) of addon actors. If present, the
|
||||
* new root actor supports the 'listAddons' request, providing the live
|
||||
* list's elements as its addon actors, and sending 'addonListchanged'
|
||||
* notifications when the live list's contents change.
|
||||
*
|
||||
* - globalActorFactories: an object |A| describing further actors to
|
||||
* attach to the 'listTabs' reply. This is the type accumulated by
|
||||
* DebuggerServer.addGlobalActor. For each own property |P| of |A|,
|
||||
* the root actor adds a property named |P| to the 'listTabs'
|
||||
* reply whose value is the name of an actor constructed by
|
||||
* |A[P]|.
|
||||
*
|
||||
* - onShutdown: a function to call when the root actor is disconnected.
|
||||
*
|
||||
* Instance properties:
|
||||
*
|
||||
* - applicationType: the string the root actor will include as the
|
||||
* "applicationType" property in the greeting packet. By default, this
|
||||
* is "browser".
|
||||
*
|
||||
* Live lists:
|
||||
*
|
||||
* A "live list", as used for the |tabList|, is an object that presents a
|
||||
* list of actors, and also notifies its clients of changes to the list. A
|
||||
* live list's interface is two properties:
|
||||
*
|
||||
* - getList: a method that returns a promise to the contents of the list.
|
||||
*
|
||||
* - onListChanged: a handler called, with no arguments, when the set of
|
||||
* values the iterator would produce has changed since the last
|
||||
* time 'iterator' was called. This may only be set to null or a
|
||||
* callable value (one for which the typeof operator returns
|
||||
* 'function'). (Note that the live list will not call the
|
||||
* onListChanged handler until the list has been iterated over
|
||||
* once; if nobody's seen the list in the first place, nobody
|
||||
* should care if its contents have changed!)
|
||||
*
|
||||
* When the list changes, the list implementation should ensure that any
|
||||
* actors yielded in previous iterations whose referents (tabs) still exist
|
||||
* get yielded again in subsequent iterations. If the underlying referent
|
||||
* is the same, the same actor should be presented for it.
|
||||
*
|
||||
* The root actor registers an 'onListChanged' handler on the appropriate
|
||||
* list when it may need to send the client 'tabListChanged' notifications,
|
||||
* and is careful to remove the handler whenever it does not need to send
|
||||
* such notifications (including when it is disconnected). This means that
|
||||
* live list implementations can use the state of the handler property (set
|
||||
* or null) to install and remove observers and event listeners.
|
||||
*
|
||||
* Note that, as the only way for the root actor to see the members of the
|
||||
* live list is to begin an iteration over the list, the live list need not
|
||||
* actually produce any actors until they are reached in the course of
|
||||
* iteration: alliterative lazy live lists.
|
||||
*/
|
||||
|
||||
function RootActor(aConnection, aParameters) {
|
||||
this.conn = aConnection;
|
||||
this._parameters = aParameters;
|
||||
this._onTabListChanged = this.onTabListChanged.bind(this);
|
||||
this._onAddonListChanged = this.onAddonListChanged.bind(this);
|
||||
this._onWorkerListChanged = this.onWorkerListChanged.bind(this);
|
||||
this._onServiceWorkerRegistrationListChanged = this.onServiceWorkerRegistrationListChanged.bind(this);
|
||||
this._onProcessListChanged = this.onProcessListChanged.bind(this);
|
||||
this._extraActors = {};
|
||||
|
||||
this._globalActorPool = new ActorPool(this.conn);
|
||||
this.conn.addActorPool(this._globalActorPool);
|
||||
|
||||
this._chromeActor = null;
|
||||
}
|
||||
|
||||
RootActor.prototype = {
|
||||
constructor: RootActor,
|
||||
applicationType: "browser",
|
||||
|
||||
traits: {
|
||||
sources: true,
|
||||
// Whether the inspector actor allows modifying outer HTML.
|
||||
editOuterHTML: true,
|
||||
// Whether the inspector actor allows modifying innerHTML and inserting
|
||||
// adjacent HTML.
|
||||
pasteHTML: true,
|
||||
// Whether the server-side highlighter actor exists and can be used to
|
||||
// remotely highlight nodes (see server/actors/highlighters.js)
|
||||
highlightable: true,
|
||||
// Which custom highlighter does the server-side highlighter actor supports?
|
||||
// (see server/actors/highlighters.js)
|
||||
customHighlighters: true,
|
||||
// Whether the inspector actor implements the getImageDataFromURL
|
||||
// method that returns data-uris for image URLs. This is used for image
|
||||
// tooltips for instance
|
||||
urlToImageDataResolver: true,
|
||||
networkMonitor: true,
|
||||
// Whether the storage inspector actor to inspect cookies, etc.
|
||||
storageInspector: true,
|
||||
// Whether storage inspector is read only
|
||||
storageInspectorReadOnly: true,
|
||||
// Whether conditional breakpoints are supported
|
||||
conditionalBreakpoints: true,
|
||||
// Whether the server supports full source actors (breakpoints on
|
||||
// eval scripts, etc)
|
||||
debuggerSourceActors: true,
|
||||
bulk: true,
|
||||
// Whether the style rule actor implements the modifySelector method
|
||||
// that modifies the rule's selector
|
||||
selectorEditable: true,
|
||||
// Whether the page style actor implements the addNewRule method that
|
||||
// adds new rules to the page
|
||||
addNewRule: true,
|
||||
// Whether the dom node actor implements the getUniqueSelector method
|
||||
getUniqueSelector: true,
|
||||
// Whether the director scripts are supported
|
||||
directorScripts: true,
|
||||
// Whether the debugger server supports
|
||||
// blackboxing/pretty-printing (not supported in Fever Dream yet)
|
||||
noBlackBoxing: false,
|
||||
noPrettyPrinting: false,
|
||||
// Whether the page style actor implements the getUsedFontFaces method
|
||||
// that returns the font faces used on a node
|
||||
getUsedFontFaces: true,
|
||||
// Trait added in Gecko 38, indicating that all features necessary for
|
||||
// grabbing allocations from the MemoryActor are available for the performance tool
|
||||
memoryActorAllocations: true,
|
||||
// Added in Gecko 40, indicating that the backend isn't stupid about
|
||||
// sending resumption packets on tab navigation.
|
||||
noNeedToFakeResumptionOnNavigation: true,
|
||||
// Added in Firefox 40. Indicates that the backend supports registering custom
|
||||
// commands through the WebConsoleCommands API.
|
||||
webConsoleCommands: true,
|
||||
// Whether root actor exposes tab actors
|
||||
// if allowChromeProcess is true, you can fetch a ChromeActor instance
|
||||
// to debug chrome and any non-content ressource via getProcess request
|
||||
// if allocChromeProcess is defined, but not true, it means that root actor
|
||||
// no longer expose tab actors, but also that getProcess forbids
|
||||
// exposing actors for security reasons
|
||||
get allowChromeProcess() {
|
||||
return DebuggerServer.allowChromeProcess;
|
||||
},
|
||||
// Whether or not `getProfile()` supports specifying a `startTime`
|
||||
// and `endTime` to filter out samples. Fx40+
|
||||
profilerDataFilterable: true,
|
||||
// Whether or not the MemoryActor's heap snapshot abilities are
|
||||
// fully equipped to handle heap snapshots for the memory tool. Fx44+
|
||||
heapSnapshots: true,
|
||||
// Whether or not the timeline actor can emit DOMContentLoaded and Load
|
||||
// markers, currently in use by the network monitor. Fx45+
|
||||
documentLoadingMarkers: true
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a 'hello' packet as specified by the Remote Debugging Protocol.
|
||||
*/
|
||||
sayHello: function () {
|
||||
return {
|
||||
from: this.actorID,
|
||||
applicationType: this.applicationType,
|
||||
/* This is not in the spec, but it's used by tests. */
|
||||
testConnectionPrefix: this.conn.prefix,
|
||||
traits: this.traits
|
||||
};
|
||||
},
|
||||
|
||||
forwardingCancelled: function (prefix) {
|
||||
return {
|
||||
from: this.actorID,
|
||||
type: "forwardingCancelled",
|
||||
prefix,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Disconnects the actor from the browser window.
|
||||
*/
|
||||
disconnect: function () {
|
||||
/* Tell the live lists we aren't watching any more. */
|
||||
if (this._parameters.tabList) {
|
||||
this._parameters.tabList.onListChanged = null;
|
||||
}
|
||||
if (this._parameters.addonList) {
|
||||
this._parameters.addonList.onListChanged = null;
|
||||
}
|
||||
if (this._parameters.workerList) {
|
||||
this._parameters.workerList.onListChanged = null;
|
||||
}
|
||||
if (this._parameters.serviceWorkerRegistrationList) {
|
||||
this._parameters.serviceWorkerRegistrationList.onListChanged = null;
|
||||
}
|
||||
if (typeof this._parameters.onShutdown === "function") {
|
||||
this._parameters.onShutdown();
|
||||
}
|
||||
this._extraActors = null;
|
||||
this.conn = null;
|
||||
this._tabActorPool = null;
|
||||
this._globalActorPool = null;
|
||||
this._parameters = null;
|
||||
this._chromeActor = null;
|
||||
},
|
||||
|
||||
/* The 'listTabs' request and the 'tabListChanged' notification. */
|
||||
|
||||
/**
|
||||
* Handles the listTabs request. The actors will survive until at least
|
||||
* the next listTabs request.
|
||||
*/
|
||||
onListTabs: function () {
|
||||
let tabList = this._parameters.tabList;
|
||||
if (!tabList) {
|
||||
return { from: this.actorID, error: "noTabs",
|
||||
message: "This root actor has no browser tabs." };
|
||||
}
|
||||
|
||||
/*
|
||||
* Walk the tab list, accumulating the array of tab actors for the
|
||||
* reply, and moving all the actors to a new ActorPool. We'll
|
||||
* replace the old tab actor pool with the one we build here, thus
|
||||
* retiring any actors that didn't get listed again, and preparing any
|
||||
* new actors to receive packets.
|
||||
*/
|
||||
let newActorPool = new ActorPool(this.conn);
|
||||
let tabActorList = [];
|
||||
let selected;
|
||||
return tabList.getList().then((tabActors) => {
|
||||
for (let tabActor of tabActors) {
|
||||
if (tabActor.selected) {
|
||||
selected = tabActorList.length;
|
||||
}
|
||||
tabActor.parentID = this.actorID;
|
||||
newActorPool.addActor(tabActor);
|
||||
tabActorList.push(tabActor);
|
||||
}
|
||||
/* DebuggerServer.addGlobalActor support: create actors. */
|
||||
if (!this._globalActorPool) {
|
||||
this._globalActorPool = new ActorPool(this.conn);
|
||||
this.conn.addActorPool(this._globalActorPool);
|
||||
}
|
||||
// this._createExtraActors(this._parameters.globalActorFactories, this._globalActorPool);
|
||||
/*
|
||||
* Drop the old actorID -> actor map. Actors that still mattered were
|
||||
* added to the new map; others will go away.
|
||||
*/
|
||||
if (this._tabActorPool) {
|
||||
this.conn.removeActorPool(this._tabActorPool);
|
||||
}
|
||||
this._tabActorPool = newActorPool;
|
||||
this.conn.addActorPool(this._tabActorPool);
|
||||
|
||||
let reply = {
|
||||
"from": this.actorID,
|
||||
"selected": selected || 0,
|
||||
"tabs": tabActorList.map(actor => actor.form())
|
||||
};
|
||||
|
||||
/* If a root window is accessible, include its URL. */
|
||||
if (this.url) {
|
||||
reply.url = this.url;
|
||||
}
|
||||
|
||||
/* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */
|
||||
// this._appendExtraActors(reply);
|
||||
|
||||
/*
|
||||
* Now that we're actually going to report the contents of tabList to
|
||||
* the client, we're responsible for letting the client know if it
|
||||
* changes.
|
||||
*/
|
||||
tabList.onListChanged = this._onTabListChanged;
|
||||
|
||||
return reply;
|
||||
});
|
||||
},
|
||||
|
||||
onGetTab: function (options) {
|
||||
let tabList = this._parameters.tabList;
|
||||
if (!tabList) {
|
||||
return { error: "noTabs",
|
||||
message: "This root actor has no browser tabs." };
|
||||
}
|
||||
if (!this._tabActorPool) {
|
||||
this._tabActorPool = new ActorPool(this.conn);
|
||||
this.conn.addActorPool(this._tabActorPool);
|
||||
}
|
||||
return tabList.getTab(options)
|
||||
.then(tabActor => {
|
||||
tabActor.parentID = this.actorID;
|
||||
this._tabActorPool.addActor(tabActor);
|
||||
|
||||
return { tab: tabActor.form() };
|
||||
}, error => {
|
||||
if (error.error) {
|
||||
// Pipe expected errors as-is to the client
|
||||
return error;
|
||||
} else {
|
||||
return { error: "noTab",
|
||||
message: "Unexpected error while calling getTab(): " + error };
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
onTabListChanged: function () {
|
||||
this.conn.send({ from: this.actorID, type:"tabListChanged" });
|
||||
/* It's a one-shot notification; no need to watch any more. */
|
||||
this._parameters.tabList.onListChanged = null;
|
||||
},
|
||||
|
||||
onListAddons: function () {
|
||||
let addonList = this._parameters.addonList;
|
||||
if (!addonList) {
|
||||
return { from: this.actorID, error: "noAddons",
|
||||
message: "This root actor has no browser addons." };
|
||||
}
|
||||
|
||||
return addonList.getList().then((addonActors) => {
|
||||
let addonActorPool = new ActorPool(this.conn);
|
||||
for (let addonActor of addonActors) {
|
||||
addonActorPool.addActor(addonActor);
|
||||
}
|
||||
|
||||
if (this._addonActorPool) {
|
||||
this.conn.removeActorPool(this._addonActorPool);
|
||||
}
|
||||
this._addonActorPool = addonActorPool;
|
||||
this.conn.addActorPool(this._addonActorPool);
|
||||
|
||||
addonList.onListChanged = this._onAddonListChanged;
|
||||
|
||||
return {
|
||||
"from": this.actorID,
|
||||
"addons": addonActors.map(addonActor => addonActor.form())
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
onAddonListChanged: function () {
|
||||
this.conn.send({ from: this.actorID, type: "addonListChanged" });
|
||||
this._parameters.addonList.onListChanged = null;
|
||||
},
|
||||
|
||||
onListWorkers: function () {
|
||||
let workerList = this._parameters.workerList;
|
||||
if (!workerList) {
|
||||
return { from: this.actorID, error: "noWorkers",
|
||||
message: "This root actor has no workers." };
|
||||
}
|
||||
|
||||
return workerList.getList().then(actors => {
|
||||
let pool = new ActorPool(this.conn);
|
||||
for (let actor of actors) {
|
||||
pool.addActor(actor);
|
||||
}
|
||||
|
||||
this.conn.removeActorPool(this._workerActorPool);
|
||||
this._workerActorPool = pool;
|
||||
this.conn.addActorPool(this._workerActorPool);
|
||||
|
||||
workerList.onListChanged = this._onWorkerListChanged;
|
||||
|
||||
return {
|
||||
"from": this.actorID,
|
||||
"workers": actors.map(actor => actor.form())
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
onWorkerListChanged: function () {
|
||||
this.conn.send({ from: this.actorID, type: "workerListChanged" });
|
||||
this._parameters.workerList.onListChanged = null;
|
||||
},
|
||||
|
||||
onListServiceWorkerRegistrations: function () {
|
||||
let registrationList = this._parameters.serviceWorkerRegistrationList;
|
||||
if (!registrationList) {
|
||||
return { from: this.actorID, error: "noServiceWorkerRegistrations",
|
||||
message: "This root actor has no service worker registrations." };
|
||||
}
|
||||
|
||||
return registrationList.getList().then(actors => {
|
||||
let pool = new ActorPool(this.conn);
|
||||
for (let actor of actors) {
|
||||
pool.addActor(actor);
|
||||
}
|
||||
|
||||
this.conn.removeActorPool(this._serviceWorkerRegistrationActorPool);
|
||||
this._serviceWorkerRegistrationActorPool = pool;
|
||||
this.conn.addActorPool(this._serviceWorkerRegistrationActorPool);
|
||||
|
||||
registrationList.onListChanged = this._onServiceWorkerRegistrationListChanged;
|
||||
|
||||
return {
|
||||
"from": this.actorID,
|
||||
"registrations": actors.map(actor => actor.form())
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
onServiceWorkerRegistrationListChanged: function () {
|
||||
this.conn.send({ from: this.actorID, type: "serviceWorkerRegistrationListChanged" });
|
||||
this._parameters.serviceWorkerRegistrationList.onListChanged = null;
|
||||
},
|
||||
|
||||
onListProcesses: function () {
|
||||
let { processList } = this._parameters;
|
||||
if (!processList) {
|
||||
return { from: this.actorID, error: "noProcesses",
|
||||
message: "This root actor has no processes." };
|
||||
}
|
||||
processList.onListChanged = this._onProcessListChanged;
|
||||
return {
|
||||
processes: processList.getList()
|
||||
};
|
||||
},
|
||||
|
||||
onProcessListChanged: function () {
|
||||
this.conn.send({ from: this.actorID, type: "processListChanged" });
|
||||
this._parameters.processList.onListChanged = null;
|
||||
},
|
||||
|
||||
onGetProcess: function (aRequest) {
|
||||
if (!DebuggerServer.allowChromeProcess) {
|
||||
return { error: "forbidden",
|
||||
message: "You are not allowed to debug chrome." };
|
||||
}
|
||||
if (("id" in aRequest) && typeof (aRequest.id) != "number") {
|
||||
return { error: "wrongParameter",
|
||||
message: "getProcess requires a valid `id` attribute." };
|
||||
}
|
||||
// If the request doesn't contains id parameter or id is 0
|
||||
// (id == 0, based on onListProcesses implementation)
|
||||
if ((!("id" in aRequest)) || aRequest.id === 0) {
|
||||
if (!this._chromeActor) {
|
||||
// Create a ChromeActor for the parent process
|
||||
let { ChromeActor } = require("devtools/server/actors/chrome");
|
||||
this._chromeActor = new ChromeActor(this.conn);
|
||||
this._globalActorPool.addActor(this._chromeActor);
|
||||
}
|
||||
|
||||
return { form: this._chromeActor.form() };
|
||||
} else {
|
||||
let mm = ppmm.getChildAt(aRequest.id);
|
||||
if (!mm) {
|
||||
return { error: "noProcess",
|
||||
message: "There is no process with id '" + aRequest.id + "'." };
|
||||
}
|
||||
return DebuggerServer.connectToContent(this.conn, mm)
|
||||
.then(form => ({ form }));
|
||||
}
|
||||
},
|
||||
|
||||
/* This is not in the spec, but it's used by tests. */
|
||||
onEcho: function (aRequest) {
|
||||
/*
|
||||
* Request packets are frozen. Copy aRequest, so that
|
||||
* DebuggerServerConnection.onPacket can attach a 'from' property.
|
||||
*/
|
||||
return Cu.cloneInto(aRequest, {});
|
||||
},
|
||||
|
||||
onProtocolDescription: function () {
|
||||
return require("devtools/shared/protocol").dumpProtocolSpec();
|
||||
},
|
||||
|
||||
/* Support for DebuggerServer.addGlobalActor. */
|
||||
// _createExtraActors: createExtraActors,
|
||||
// _appendExtraActors: appendExtraActors,
|
||||
|
||||
/**
|
||||
* Remove the extra actor (added by DebuggerServer.addGlobalActor or
|
||||
* DebuggerServer.addTabActor) name |aName|.
|
||||
*/
|
||||
removeActorByName: function (aName) {
|
||||
if (aName in this._extraActors) {
|
||||
const actor = this._extraActors[aName];
|
||||
if (this._globalActorPool.has(actor)) {
|
||||
this._globalActorPool.removeActor(actor);
|
||||
}
|
||||
if (this._tabActorPool) {
|
||||
// Iterate over TabActor instances to also remove tab actors
|
||||
// created during listTabs for each document.
|
||||
this._tabActorPool.forEach(tab => {
|
||||
tab.removeActorByName(aName);
|
||||
});
|
||||
}
|
||||
delete this._extraActors[aName];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
RootActor.prototype.requestTypes = {
|
||||
"listTabs": RootActor.prototype.onListTabs,
|
||||
"getTab": RootActor.prototype.onGetTab,
|
||||
"listAddons": RootActor.prototype.onListAddons,
|
||||
"listWorkers": RootActor.prototype.onListWorkers,
|
||||
"listServiceWorkerRegistrations": RootActor.prototype.onListServiceWorkerRegistrations,
|
||||
"listProcesses": RootActor.prototype.onListProcesses,
|
||||
"getProcess": RootActor.prototype.onGetProcess,
|
||||
"echo": RootActor.prototype.onEcho,
|
||||
"protocolDescription": RootActor.prototype.onProtocolDescription
|
||||
};
|
||||
|
||||
// exports.RootActor = RootActor;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,937 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { Cc, Ci } = require("chrome");
|
||||
// const Services = require("Services");
|
||||
// const { BreakpointActor, setBreakpointAtEntryPoints } = require("devtools/server/actors/breakpoint");
|
||||
// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common");
|
||||
// const { createValueGrip } = require("devtools/server/actors/object");
|
||||
// const { ActorClassWithSpec, Arg, RetVal, method } = require("devtools/shared/protocol");
|
||||
// const DevToolsUtils = require("devtools/shared/DevToolsUtils");
|
||||
// const { assert, fetch } = DevToolsUtils;
|
||||
// const { joinURI } = require("devtools/shared/path");
|
||||
// const promise = require("promise");
|
||||
// const { defer, resolve, reject, all } = promise;
|
||||
// const { sourceSpec } = require("devtools/shared/specs/source");
|
||||
|
||||
// loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true);
|
||||
// loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true);
|
||||
// loader.lazyRequireGetter(this, "mapURIToAddonID", "devtools/server/actors/utils/map-uri-to-addon-id");
|
||||
|
||||
// from "devtools/shared/specs/source"
|
||||
const sourceSpec = generateActorSpec({
|
||||
typeName: "source",
|
||||
|
||||
methods: {
|
||||
getExecutableLines: { response: { lines: RetVal("json") } },
|
||||
onSource: {
|
||||
request: { type: "source" },
|
||||
response: RetVal("json")
|
||||
},
|
||||
prettyPrint: {
|
||||
request: { indent: Arg(0, "number") },
|
||||
response: RetVal("json")
|
||||
},
|
||||
disablePrettyPrint: {
|
||||
response: RetVal("json")
|
||||
},
|
||||
blackbox: { response: { pausedInSource: RetVal("boolean") } },
|
||||
unblackbox: {},
|
||||
setBreakpoint: {
|
||||
request: {
|
||||
location: {
|
||||
line: Arg(0, "number"),
|
||||
column: Arg(1, "nullable:number")
|
||||
},
|
||||
condition: Arg(2, "nullable:string"),
|
||||
noSliding: Arg(3, "nullable:boolean")
|
||||
},
|
||||
response: RetVal("json")
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------
|
||||
|
||||
function isEvalSource(source) {
|
||||
let introType = source.introductionType;
|
||||
// These are all the sources that are essentially eval-ed (either
|
||||
// by calling eval or passing a string to one of these functions).
|
||||
return (introType === "eval" ||
|
||||
introType === "Function" ||
|
||||
introType === "eventHandler" ||
|
||||
introType === "setTimeout" ||
|
||||
introType === "setInterval");
|
||||
}
|
||||
|
||||
// exports.isEvalSource = isEvalSource;
|
||||
|
||||
function getSourceURL(source, window) {
|
||||
if (isEvalSource(source)) {
|
||||
// Eval sources have no urls, but they might have a `displayURL`
|
||||
// created with the sourceURL pragma. If the introduction script
|
||||
// is a non-eval script, generate an full absolute URL relative to it.
|
||||
|
||||
if (source.displayURL && source.introductionScript &&
|
||||
!isEvalSource(source.introductionScript.source)) {
|
||||
|
||||
if (source.introductionScript.source.url === "debugger eval code") {
|
||||
if (window) {
|
||||
// If this is a named eval script created from the console, make it
|
||||
// relative to the current page. window is only available
|
||||
// when we care about this.
|
||||
return joinURI(window.location.href, source.displayURL);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return joinURI(source.introductionScript.source.url, source.displayURL);
|
||||
}
|
||||
}
|
||||
|
||||
return source.displayURL;
|
||||
}
|
||||
else if (source.url === "debugger eval code") {
|
||||
// Treat code evaluated by the console as unnamed eval scripts
|
||||
return null;
|
||||
}
|
||||
return source.url;
|
||||
}
|
||||
|
||||
// exports.getSourceURL = getSourceURL;
|
||||
|
||||
/**
|
||||
* Resolve a URI back to physical file.
|
||||
*
|
||||
* Of course, this works only for URIs pointing to local resources.
|
||||
*
|
||||
* @param aURI
|
||||
* URI to resolve
|
||||
* @return
|
||||
* resolved nsIURI
|
||||
*/
|
||||
function resolveURIToLocalPath(aURI) {
|
||||
let resolved;
|
||||
switch (aURI.scheme) {
|
||||
case "jar":
|
||||
case "file":
|
||||
return aURI;
|
||||
|
||||
case "chrome":
|
||||
resolved = Cc["@mozilla.org/chrome/chrome-registry;1"].
|
||||
getService(Ci.nsIChromeRegistry).convertChromeURL(aURI);
|
||||
return resolveURIToLocalPath(resolved);
|
||||
|
||||
case "resource":
|
||||
resolved = Cc["@mozilla.org/network/protocol;1?name=resource"].
|
||||
getService(Ci.nsIResProtocolHandler).resolveURI(aURI);
|
||||
aURI = Services.io.newURI(resolved, null, null);
|
||||
return resolveURIToLocalPath(aURI);
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A SourceActor provides information about the source of a script. There
|
||||
* are two kinds of source actors: ones that represent real source objects,
|
||||
* and ones that represent non-existant "original" sources when the real
|
||||
* sources are sourcemapped. When a source is sourcemapped, actors are
|
||||
* created for both the "generated" and "original" sources, and the client will
|
||||
* only see the original sources. We separate these because there isn't
|
||||
* a 1:1 mapping of generated to original sources; one generated source
|
||||
* may represent N original sources, so we need to create N + 1 separate
|
||||
* actors.
|
||||
*
|
||||
* There are 4 different scenarios for sources that you should
|
||||
* understand:
|
||||
*
|
||||
* - A single non-sourcemapped source that is not inlined in HTML
|
||||
* (separate JS file, eval'ed code, etc)
|
||||
* - A single sourcemapped source which creates N original sources
|
||||
* - An HTML page with multiple inline scripts, which are distinct
|
||||
* sources, but should be represented as a single source
|
||||
* - A pretty-printed source (which may or may not be an original
|
||||
* sourcemapped source), which generates a sourcemap for itself
|
||||
*
|
||||
* The complexity of `SourceActor` and `ThreadSources` are to handle
|
||||
* all of thise cases and hopefully internalize the complexities.
|
||||
*
|
||||
* @param Debugger.Source source
|
||||
* The source object we are representing.
|
||||
* @param ThreadActor thread
|
||||
* The current thread actor.
|
||||
* @param String originalUrl
|
||||
* Optional. For sourcemapped urls, the original url this is representing.
|
||||
* @param Debugger.Source generatedSource
|
||||
* Optional, passed in when aSourceMap is also passed in. The generated
|
||||
* source object that introduced this source.
|
||||
* @param Boolean isInlineSource
|
||||
* Optional. True if this is an inline source from a HTML or XUL page.
|
||||
* @param String contentType
|
||||
* Optional. The content type of this source, if immediately available.
|
||||
*/
|
||||
let SourceActor = ActorClassWithSpec(sourceSpec, {
|
||||
typeName: "source",
|
||||
|
||||
initialize: function ({ source, thread, originalUrl, generatedSource,
|
||||
isInlineSource, contentType }) {
|
||||
this._threadActor = thread;
|
||||
this._originalUrl = originalUrl;
|
||||
this._source = source;
|
||||
this._generatedSource = generatedSource;
|
||||
this._contentType = contentType;
|
||||
this._isInlineSource = isInlineSource;
|
||||
|
||||
this.onSource = this.onSource.bind(this);
|
||||
this._invertSourceMap = this._invertSourceMap.bind(this);
|
||||
this._encodeAndSetSourceMapURL = this._encodeAndSetSourceMapURL.bind(this);
|
||||
this._getSourceText = this._getSourceText.bind(this);
|
||||
|
||||
this._mapSourceToAddon();
|
||||
|
||||
if (this.threadActor.sources.isPrettyPrinted(this.url)) {
|
||||
this._init = this.prettyPrint(
|
||||
this.threadActor.sources.prettyPrintIndent(this.url)
|
||||
).then(null, error => {
|
||||
DevToolsUtils.reportException("SourceActor", error);
|
||||
});
|
||||
} else {
|
||||
this._init = null;
|
||||
}
|
||||
},
|
||||
|
||||
get isSourceMapped() {
|
||||
return !!(!this.isInlineSource && (
|
||||
this._originalURL || this._generatedSource ||
|
||||
this.threadActor.sources.isPrettyPrinted(this.url)
|
||||
));
|
||||
},
|
||||
|
||||
get isInlineSource() {
|
||||
return this._isInlineSource;
|
||||
},
|
||||
|
||||
get threadActor() { return this._threadActor; },
|
||||
get sources() { return this._threadActor.sources; },
|
||||
get dbg() { return this.threadActor.dbg; },
|
||||
get source() { return this._source; },
|
||||
get generatedSource() { return this._generatedSource; },
|
||||
get breakpointActorMap() { return this.threadActor.breakpointActorMap; },
|
||||
get url() {
|
||||
if (this.source) {
|
||||
return getSourceURL(this.source, this.threadActor._parent.window);
|
||||
}
|
||||
return this._originalUrl;
|
||||
},
|
||||
get addonID() { return this._addonID; },
|
||||
get addonPath() { return this._addonPath; },
|
||||
|
||||
get prettyPrintWorker() {
|
||||
return this.threadActor.prettyPrintWorker;
|
||||
},
|
||||
|
||||
form: function () {
|
||||
let source = this.source || this.generatedSource;
|
||||
// This might not have a source or a generatedSource because we
|
||||
// treat HTML pages with inline scripts as a special SourceActor
|
||||
// that doesn't have either
|
||||
let introductionUrl = null;
|
||||
if (source && source.introductionScript) {
|
||||
introductionUrl = source.introductionScript.source.url;
|
||||
}
|
||||
|
||||
return {
|
||||
actor: this.actorID,
|
||||
generatedUrl: this.generatedSource ? this.generatedSource.url : null,
|
||||
url: this.url ? this.url.split(" -> ").pop() : null,
|
||||
addonID: this._addonID,
|
||||
addonPath: this._addonPath,
|
||||
isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url),
|
||||
isPrettyPrinted: this.threadActor.sources.isPrettyPrinted(this.url),
|
||||
isSourceMapped: this.isSourceMapped,
|
||||
sourceMapURL: source ? source.sourceMapURL : null,
|
||||
introductionUrl: introductionUrl ? introductionUrl.split(" -> ").pop() : null,
|
||||
introductionType: source ? source.introductionType : null
|
||||
};
|
||||
},
|
||||
|
||||
disconnect: function () {
|
||||
if (this.registeredPool && this.registeredPool.sourceActors) {
|
||||
delete this.registeredPool.sourceActors[this.actorID];
|
||||
}
|
||||
},
|
||||
|
||||
_mapSourceToAddon: function () {
|
||||
try {
|
||||
var nsuri = Services.io.newURI(this.url.split(" -> ").pop(), null, null);
|
||||
}
|
||||
catch (e) {
|
||||
// We can't do anything with an invalid URI
|
||||
return;
|
||||
}
|
||||
|
||||
let localURI = resolveURIToLocalPath(nsuri);
|
||||
if (!localURI) {
|
||||
return;
|
||||
}
|
||||
|
||||
let id = mapURIToAddonID(localURI);
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
this._addonID = id;
|
||||
|
||||
if (localURI instanceof Ci.nsIJARURI) {
|
||||
// The path in the add-on is easy for jar: uris
|
||||
this._addonPath = localURI.JAREntry;
|
||||
}
|
||||
else if (localURI instanceof Ci.nsIFileURL) {
|
||||
// For file: uris walk up to find the last directory that is part of the
|
||||
// add-on
|
||||
let target = localURI.file;
|
||||
let path = target.leafName;
|
||||
|
||||
// We can assume that the directory containing the source file is part
|
||||
// of the add-on
|
||||
let root = target.parent;
|
||||
let file = root.parent;
|
||||
while (file && mapURIToAddonID(Services.io.newFileURI(file))) {
|
||||
path = root.leafName + "/" + path;
|
||||
root = file;
|
||||
file = file.parent;
|
||||
}
|
||||
|
||||
if (!file) {
|
||||
const error = new Error("Could not find the root of the add-on for " + this.url);
|
||||
DevToolsUtils.reportException("SourceActor.prototype._mapSourceToAddon", error);
|
||||
return;
|
||||
}
|
||||
|
||||
this._addonPath = path;
|
||||
}
|
||||
},
|
||||
|
||||
_reportLoadSourceError: function (error, map = null) {
|
||||
try {
|
||||
DevToolsUtils.reportException("SourceActor", error);
|
||||
|
||||
JSON.stringify(this.form(), null, 4).split(/\n/g)
|
||||
.forEach(line => console.error("\t", line));
|
||||
|
||||
if (!map) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error("\t", "source map's sourceRoot =", map.sourceRoot);
|
||||
|
||||
console.error("\t", "source map's sources =");
|
||||
map.sources.forEach(s => {
|
||||
let hasSourceContent = map.sourceContentFor(s, true);
|
||||
console.error("\t\t", s, "\t",
|
||||
hasSourceContent ? "has source content" : "no source content");
|
||||
});
|
||||
|
||||
console.error("\t", "source map's sourcesContent =");
|
||||
map.sourcesContent.forEach(c => {
|
||||
if (c.length > 80) {
|
||||
c = c.slice(0, 77) + "...";
|
||||
}
|
||||
c = c.replace(/\n/g, "\\n");
|
||||
console.error("\t\t", c);
|
||||
});
|
||||
} catch (e) { }
|
||||
},
|
||||
|
||||
_getSourceText: function () {
|
||||
let toResolvedContent = t => ({
|
||||
content: t,
|
||||
contentType: this._contentType
|
||||
});
|
||||
|
||||
let genSource = this.generatedSource || this.source;
|
||||
return this.threadActor.sources.fetchSourceMap(genSource).then(map => {
|
||||
if (map) {
|
||||
try {
|
||||
let sourceContent = map.sourceContentFor(this.url);
|
||||
if (sourceContent) {
|
||||
return toResolvedContent(sourceContent);
|
||||
}
|
||||
} catch (error) {
|
||||
this._reportLoadSourceError(error, map);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Use `source.text` if it exists, is not the "no source" string, and
|
||||
// the content type of the source is JavaScript or it is synthesized
|
||||
// wasm. It will be "no source" if the Debugger API wasn't able to load
|
||||
// the source because sources were discarded
|
||||
// (javascript.options.discardSystemSource == true). Re-fetch non-JS
|
||||
// sources to get the contentType from the headers.
|
||||
if (this.source &&
|
||||
this.source.text !== "[no source]" &&
|
||||
this._contentType &&
|
||||
(this._contentType.indexOf("javascript") !== -1 ||
|
||||
this._contentType === "text/wasm")) {
|
||||
return toResolvedContent(this.source.text);
|
||||
}
|
||||
else {
|
||||
// Only load the HTML page source from cache (which exists when
|
||||
// there are inline sources). Otherwise, we can't trust the
|
||||
// cache because we are most likely here because we are
|
||||
// fetching the original text for sourcemapped code, and the
|
||||
// page hasn't requested it before (if it has, it was a
|
||||
// previous debugging session).
|
||||
let loadFromCache = this.isInlineSource;
|
||||
|
||||
// Fetch the sources with the same principal as the original document
|
||||
let win = this.threadActor._parent.window;
|
||||
let principal, cacheKey;
|
||||
// On xpcshell, we don't have a window but a Sandbox
|
||||
if (!isWorker && win instanceof Ci.nsIDOMWindow) {
|
||||
let webNav = win.QueryInterface(Ci.nsIInterfaceRequestor)
|
||||
.getInterface(Ci.nsIWebNavigation);
|
||||
let channel = webNav.currentDocumentChannel;
|
||||
principal = channel.loadInfo.loadingPrincipal;
|
||||
|
||||
// Retrieve the cacheKey in order to load POST requests from cache
|
||||
// Note that chrome:// URLs don't support this interface.
|
||||
if (loadFromCache &&
|
||||
webNav.currentDocumentChannel instanceof Ci.nsICacheInfoChannel) {
|
||||
cacheKey = webNav.currentDocumentChannel.cacheKey;
|
||||
assert(
|
||||
cacheKey,
|
||||
"Could not fetch the cacheKey from the related document."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let sourceFetched = fetch(this.url, {
|
||||
principal,
|
||||
cacheKey,
|
||||
loadFromCache
|
||||
});
|
||||
|
||||
// Record the contentType we just learned during fetching
|
||||
return sourceFetched
|
||||
.then(result => {
|
||||
this._contentType = result.contentType;
|
||||
return result;
|
||||
}, error => {
|
||||
this._reportLoadSourceError(error, map);
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all executable lines from the current source
|
||||
* @return Array - Executable lines of the current script
|
||||
**/
|
||||
getExecutableLines: function () {
|
||||
function sortLines(lines) {
|
||||
// Converting the Set into an array
|
||||
lines = [...lines];
|
||||
lines.sort((a, b) => {
|
||||
return a - b;
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
|
||||
if (this.generatedSource) {
|
||||
return this.threadActor.sources.getSourceMap(this.generatedSource).then(sm => {
|
||||
let lines = new Set();
|
||||
|
||||
// Position of executable lines in the generated source
|
||||
let offsets = this.getExecutableOffsets(this.generatedSource, false);
|
||||
for (let offset of offsets) {
|
||||
let {line, source: sourceUrl} = sm.originalPositionFor({
|
||||
line: offset.lineNumber,
|
||||
column: offset.columnNumber
|
||||
});
|
||||
|
||||
if (sourceUrl === this.url) {
|
||||
lines.add(line);
|
||||
}
|
||||
}
|
||||
|
||||
return sortLines(lines);
|
||||
});
|
||||
}
|
||||
|
||||
let lines = this.getExecutableOffsets(this.source, true);
|
||||
return sortLines(lines);
|
||||
},
|
||||
|
||||
/**
|
||||
* Extract all executable offsets from the given script
|
||||
* @param String url - extract offsets of the script with this url
|
||||
* @param Boolean onlyLine - will return only the line number
|
||||
* @return Set - Executable offsets/lines of the script
|
||||
**/
|
||||
getExecutableOffsets: function (source, onlyLine) {
|
||||
let offsets = new Set();
|
||||
for (let s of this.dbg.findScripts({ source })) {
|
||||
for (let offset of s.getAllColumnOffsets()) {
|
||||
offsets.add(onlyLine ? offset.lineNumber : offset);
|
||||
}
|
||||
}
|
||||
|
||||
return offsets;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the "source" packet.
|
||||
*/
|
||||
onSource: function () {
|
||||
return Promise.resolve(this._init)
|
||||
.then(this._getSourceText)
|
||||
.then(({ content, contentType }) => {
|
||||
return {
|
||||
source: createValueGrip(content, this.threadActor.threadLifetimePool,
|
||||
this.threadActor.objectGrip),
|
||||
contentType: contentType
|
||||
};
|
||||
})
|
||||
.then(null, aError => {
|
||||
reportError(aError, "Got an exception during SA_onSource: ");
|
||||
throw new Error("Could not load the source for " + this.url + ".\n" +
|
||||
DevToolsUtils.safeErrorString(aError));
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the "prettyPrint" packet.
|
||||
*/
|
||||
prettyPrint: function (indent) {
|
||||
this.threadActor.sources.prettyPrint(this.url, indent);
|
||||
return this._getSourceText()
|
||||
.then(this._sendToPrettyPrintWorker(indent))
|
||||
.then(this._invertSourceMap)
|
||||
.then(this._encodeAndSetSourceMapURL)
|
||||
.then(() => {
|
||||
// We need to reset `_init` now because we have already done the work of
|
||||
// pretty printing, and don't want onSource to wait forever for
|
||||
// initialization to complete.
|
||||
this._init = null;
|
||||
})
|
||||
.then(this.onSource)
|
||||
.then(null, error => {
|
||||
this.disablePrettyPrint();
|
||||
throw new Error(DevToolsUtils.safeErrorString(error));
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a function that sends a request to the pretty print worker, waits on
|
||||
* the worker's response, and then returns the pretty printed code.
|
||||
*
|
||||
* @param Number aIndent
|
||||
* The number of spaces to indent by the code by, when we send the
|
||||
* request to the pretty print worker.
|
||||
* @returns Function
|
||||
* Returns a function which takes an AST, and returns a promise that
|
||||
* is resolved with `{ code, mappings }` where `code` is the pretty
|
||||
* printed code, and `mappings` is an array of source mappings.
|
||||
*/
|
||||
_sendToPrettyPrintWorker: function (aIndent) {
|
||||
return ({ content }) => {
|
||||
return this.prettyPrintWorker.performTask("pretty-print", {
|
||||
url: this.url,
|
||||
indent: aIndent,
|
||||
source: content
|
||||
});
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Invert a source map. So if a source map maps from a to b, return a new
|
||||
* source map from b to a. We need to do this because the source map we get
|
||||
* from _generatePrettyCodeAndMap goes the opposite way we want it to for
|
||||
* debugging.
|
||||
*
|
||||
* Note that the source map is modified in place.
|
||||
*/
|
||||
_invertSourceMap: function ({ code, mappings }) {
|
||||
const generator = new SourceMapGenerator({ file: this.url });
|
||||
return DevToolsUtils.yieldingEach(mappings._array, m => {
|
||||
let mapping = {
|
||||
generated: {
|
||||
line: m.originalLine,
|
||||
column: m.originalColumn
|
||||
}
|
||||
};
|
||||
if (m.source) {
|
||||
mapping.source = m.source;
|
||||
mapping.original = {
|
||||
line: m.generatedLine,
|
||||
column: m.generatedColumn
|
||||
};
|
||||
mapping.name = m.name;
|
||||
}
|
||||
generator.addMapping(mapping);
|
||||
}).then(() => {
|
||||
generator.setSourceContent(this.url, code);
|
||||
let consumer = SourceMapConsumer.fromSourceMap(generator);
|
||||
|
||||
return {
|
||||
code: code,
|
||||
map: consumer
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Save the source map back to our thread's ThreadSources object so that
|
||||
* stepping, breakpoints, debugger statements, etc can use it. If we are
|
||||
* pretty printing a source mapped source, we need to compose the existing
|
||||
* source map with our new one.
|
||||
*/
|
||||
_encodeAndSetSourceMapURL: function ({ map: sm }) {
|
||||
let source = this.generatedSource || this.source;
|
||||
let sources = this.threadActor.sources;
|
||||
|
||||
return sources.getSourceMap(source).then(prevMap => {
|
||||
if (prevMap) {
|
||||
// Compose the source maps
|
||||
this._oldSourceMapping = {
|
||||
url: source.sourceMapURL,
|
||||
map: prevMap
|
||||
};
|
||||
|
||||
prevMap = SourceMapGenerator.fromSourceMap(prevMap);
|
||||
prevMap.applySourceMap(sm, this.url);
|
||||
sm = SourceMapConsumer.fromSourceMap(prevMap);
|
||||
}
|
||||
|
||||
let sources = this.threadActor.sources;
|
||||
sources.clearSourceMapCache(source.sourceMapURL);
|
||||
sources.setSourceMapHard(source, null, sm);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the "disablePrettyPrint" packet.
|
||||
*/
|
||||
disablePrettyPrint: function () {
|
||||
let source = this.generatedSource || this.source;
|
||||
let sources = this.threadActor.sources;
|
||||
let sm = sources.getSourceMap(source);
|
||||
|
||||
sources.clearSourceMapCache(source.sourceMapURL, { hard: true });
|
||||
|
||||
if (this._oldSourceMapping) {
|
||||
sources.setSourceMapHard(source,
|
||||
this._oldSourceMapping.url,
|
||||
this._oldSourceMapping.map);
|
||||
this._oldSourceMapping = null;
|
||||
}
|
||||
|
||||
this.threadActor.sources.disablePrettyPrint(this.url);
|
||||
return this.onSource();
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the "blackbox" packet.
|
||||
*/
|
||||
blackbox: function () {
|
||||
this.threadActor.sources.blackBox(this.url);
|
||||
if (this.threadActor.state == "paused"
|
||||
&& this.threadActor.youngestFrame
|
||||
&& this.threadActor.youngestFrame.script.url == this.url) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the "unblackbox" packet.
|
||||
*/
|
||||
unblackbox: function () {
|
||||
this.threadActor.sources.unblackBox(this.url);
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a request to set a breakpoint.
|
||||
*
|
||||
* @param Number line
|
||||
* Line to break on.
|
||||
* @param Number column
|
||||
* Column to break on.
|
||||
* @param String condition
|
||||
* A condition which must be true for breakpoint to be hit.
|
||||
* @param Boolean noSliding
|
||||
* If true, disables breakpoint sliding.
|
||||
*
|
||||
* @returns Promise
|
||||
* A promise that resolves to a JSON object representing the
|
||||
* response.
|
||||
*/
|
||||
setBreakpoint: function (line, column, condition, noSliding) {
|
||||
if (this.threadActor.state !== "paused") {
|
||||
throw {
|
||||
error: "wrongState",
|
||||
message: "Cannot set breakpoint while debuggee is running."
|
||||
};
|
||||
}
|
||||
|
||||
let location = new OriginalLocation(this, line, column);
|
||||
return this._getOrCreateBreakpointActor(
|
||||
location,
|
||||
condition,
|
||||
noSliding
|
||||
).then((actor) => {
|
||||
let response = {
|
||||
actor: actor.actorID,
|
||||
isPending: actor.isPending
|
||||
};
|
||||
|
||||
let actualLocation = actor.originalLocation;
|
||||
if (!actualLocation.equals(location)) {
|
||||
response.actualLocation = actualLocation.toJSON();
|
||||
}
|
||||
|
||||
return response;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Get or create a BreakpointActor for the given location in the original
|
||||
* source, and ensure it is set as a breakpoint handler on all scripts that
|
||||
* match the given location.
|
||||
*
|
||||
* @param OriginalLocation originalLocation
|
||||
* An OriginalLocation representing the location of the breakpoint in
|
||||
* the original source.
|
||||
* @param String condition
|
||||
* A string that is evaluated whenever the breakpoint is hit. If the
|
||||
* string evaluates to false, the breakpoint is ignored.
|
||||
* @param Boolean noSliding
|
||||
* If true, disables breakpoint sliding.
|
||||
*
|
||||
* @returns BreakpointActor
|
||||
* A BreakpointActor representing the breakpoint.
|
||||
*/
|
||||
_getOrCreateBreakpointActor: function (originalLocation, condition, noSliding) {
|
||||
let actor = this.breakpointActorMap.getActor(originalLocation);
|
||||
if (!actor) {
|
||||
actor = new BreakpointActor(this.threadActor, originalLocation);
|
||||
this.threadActor.threadLifetimePool.addActor(actor);
|
||||
this.breakpointActorMap.setActor(originalLocation, actor);
|
||||
}
|
||||
|
||||
actor.condition = condition;
|
||||
|
||||
return this._setBreakpoint(actor, noSliding);
|
||||
},
|
||||
|
||||
/*
|
||||
* Ensure the given BreakpointActor is set as a breakpoint handler on all
|
||||
* scripts that match its location in the original source.
|
||||
*
|
||||
* If there are no scripts that match the location of the BreakpointActor,
|
||||
* we slide its location to the next closest line (for line breakpoints) or
|
||||
* column (for column breakpoint) that does.
|
||||
*
|
||||
* If breakpoint sliding fails, then either there are no scripts that contain
|
||||
* any code for the given location, or they were all garbage collected before
|
||||
* the debugger started running. We cannot distinguish between these two
|
||||
* cases, so we insert the BreakpointActor in the BreakpointActorMap as
|
||||
* a pending breakpoint. Whenever a new script is introduced, this method is
|
||||
* called again for each pending breakpoint.
|
||||
*
|
||||
* @param BreakpointActor actor
|
||||
* The BreakpointActor to be set as a breakpoint handler.
|
||||
* @param Boolean noSliding
|
||||
* If true, disables breakpoint sliding.
|
||||
*
|
||||
* @returns A Promise that resolves to the given BreakpointActor.
|
||||
*/
|
||||
_setBreakpoint: function (actor, noSliding) {
|
||||
const { originalLocation } = actor;
|
||||
const { originalLine, originalSourceActor } = originalLocation;
|
||||
|
||||
if (!this.isSourceMapped) {
|
||||
const generatedLocation = GeneratedLocation.fromOriginalLocation(originalLocation);
|
||||
if (!this._setBreakpointAtGeneratedLocation(actor, generatedLocation) &&
|
||||
!noSliding) {
|
||||
const query = { line: originalLine };
|
||||
// For most cases, we have a real source to query for. The
|
||||
// only time we don't is for HTML pages. In that case we want
|
||||
// to query for scripts in an HTML page based on its URL, as
|
||||
// there could be several sources within an HTML page.
|
||||
if (this.source) {
|
||||
query.source = this.source;
|
||||
} else {
|
||||
query.url = this.url;
|
||||
}
|
||||
const scripts = this.dbg.findScripts(query);
|
||||
|
||||
// Never do breakpoint sliding for column breakpoints.
|
||||
// Additionally, never do breakpoint sliding if no scripts
|
||||
// exist on this line.
|
||||
//
|
||||
// Sliding can go horribly wrong if we always try to find the
|
||||
// next line with valid entry points in the entire file.
|
||||
// Scripts may be completely GCed and we never knew they
|
||||
// existed, so we end up sliding through whole functions to
|
||||
// the user's bewilderment.
|
||||
//
|
||||
// We can slide reliably if any scripts exist, however, due
|
||||
// to how scripts are kept alive. A parent Debugger.Script
|
||||
// keeps all of its children alive, so as long as we have a
|
||||
// valid script, we can slide through it and know we won't
|
||||
// slide through any of its child scripts. Additionally, if a
|
||||
// script gets GCed, that means that all parents scripts are
|
||||
// GCed as well, and no scripts will exist on those lines
|
||||
// anymore. We will never slide through a GCed script.
|
||||
if (originalLocation.originalColumn || scripts.length === 0) {
|
||||
return Promise.resolve(actor);
|
||||
}
|
||||
|
||||
// Find the script that spans the largest amount of code to
|
||||
// determine the bounds for sliding.
|
||||
const largestScript = scripts.reduce((largestScript, script) => {
|
||||
if (script.lineCount > largestScript.lineCount) {
|
||||
return script;
|
||||
}
|
||||
return largestScript;
|
||||
});
|
||||
const maxLine = largestScript.startLine + largestScript.lineCount - 1;
|
||||
|
||||
let actualLine = originalLine;
|
||||
for (; actualLine <= maxLine; actualLine++) {
|
||||
const loc = new GeneratedLocation(this, actualLine);
|
||||
if (this._setBreakpointAtGeneratedLocation(actor, loc)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The above loop should never complete. We only did breakpoint sliding
|
||||
// because we found scripts on the line we started from,
|
||||
// which means there must be valid entry points somewhere
|
||||
// within those scripts.
|
||||
assert(
|
||||
actualLine <= maxLine,
|
||||
"Could not find any entry points to set a breakpoint on, " +
|
||||
"even though I was told a script existed on the line I started " +
|
||||
"the search with."
|
||||
);
|
||||
|
||||
// Update the actor to use the new location (reusing a
|
||||
// previous breakpoint if it already exists on that line).
|
||||
const actualLocation = new OriginalLocation(originalSourceActor, actualLine);
|
||||
const existingActor = this.breakpointActorMap.getActor(actualLocation);
|
||||
this.breakpointActorMap.deleteActor(originalLocation);
|
||||
if (existingActor) {
|
||||
actor.delete();
|
||||
actor = existingActor;
|
||||
} else {
|
||||
actor.originalLocation = actualLocation;
|
||||
this.breakpointActorMap.setActor(actualLocation, actor);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.resolve(actor);
|
||||
} else {
|
||||
return this.sources.getAllGeneratedLocations(originalLocation).then((generatedLocations) => {
|
||||
this._setBreakpointAtAllGeneratedLocations(
|
||||
actor,
|
||||
generatedLocations
|
||||
);
|
||||
|
||||
return actor;
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
_setBreakpointAtAllGeneratedLocations: function (actor, generatedLocations) {
|
||||
let success = false;
|
||||
for (let generatedLocation of generatedLocations) {
|
||||
if (this._setBreakpointAtGeneratedLocation(
|
||||
actor,
|
||||
generatedLocation
|
||||
)) {
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
return success;
|
||||
},
|
||||
|
||||
/*
|
||||
* Ensure the given BreakpointActor is set as breakpoint handler on all
|
||||
* scripts that match the given location in the generated source.
|
||||
*
|
||||
* @param BreakpointActor actor
|
||||
* The BreakpointActor to be set as a breakpoint handler.
|
||||
* @param GeneratedLocation generatedLocation
|
||||
* A GeneratedLocation representing the location in the generated
|
||||
* source for which the given BreakpointActor is to be set as a
|
||||
* breakpoint handler.
|
||||
*
|
||||
* @returns A Boolean that is true if the BreakpointActor was set as a
|
||||
* breakpoint handler on at least one script, and false otherwise.
|
||||
*/
|
||||
_setBreakpointAtGeneratedLocation: function (actor, generatedLocation) {
|
||||
let {
|
||||
generatedSourceActor,
|
||||
generatedLine,
|
||||
generatedColumn,
|
||||
generatedLastColumn
|
||||
} = generatedLocation;
|
||||
|
||||
// Find all scripts that match the given source actor and line
|
||||
// number.
|
||||
const query = { line: generatedLine };
|
||||
if (generatedSourceActor.source) {
|
||||
query.source = generatedSourceActor.source;
|
||||
} else {
|
||||
query.url = generatedSourceActor.url;
|
||||
}
|
||||
let scripts = this.dbg.findScripts(query);
|
||||
|
||||
scripts = scripts.filter((script) => !actor.hasScript(script));
|
||||
|
||||
// Find all entry points that correspond to the given location.
|
||||
let entryPoints = [];
|
||||
if (generatedColumn === undefined) {
|
||||
// This is a line breakpoint, so we are interested in all offsets
|
||||
// that correspond to the given line number.
|
||||
for (let script of scripts) {
|
||||
let offsets = script.getLineOffsets(generatedLine);
|
||||
if (offsets.length > 0) {
|
||||
entryPoints.push({ script, offsets });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is a column breakpoint, so we are interested in all column
|
||||
// offsets that correspond to the given line *and* column number.
|
||||
for (let script of scripts) {
|
||||
let columnToOffsetMap = script.getAllColumnOffsets()
|
||||
.filter(({ lineNumber }) => {
|
||||
return lineNumber === generatedLine;
|
||||
});
|
||||
for (let { columnNumber: column, offset } of columnToOffsetMap) {
|
||||
if (column >= generatedColumn && column <= generatedLastColumn) {
|
||||
entryPoints.push({ script, offsets: [offset] });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (entryPoints.length === 0) {
|
||||
return false;
|
||||
}
|
||||
setBreakpointAtEntryPoints(actor, entryPoints);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// exports.SourceActor = SourceActor;
|
||||
@@ -1,219 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
const { noop } = DevToolsUtils;
|
||||
|
||||
/**
|
||||
* A `ScriptStore` is a cache of `Debugger.Script` instances. It holds strong
|
||||
* references to the cached scripts to alleviate the GC-sensitivity issues that
|
||||
* plague `Debugger.prototype.findScripts`, but this means that its lifetime
|
||||
* must be managed carefully. It is the `ScriptStore` user's responsibility to
|
||||
* ensure that the `ScriptStore` stays up to date.
|
||||
*
|
||||
* Implementation Notes:
|
||||
*
|
||||
* The ScriptStore's prototype methods are very hot, in general. To help the
|
||||
* JIT, they avoid ES6-isms and higher-order iteration functions, for the most
|
||||
* part. You might be wondering why we don't maintain indices on, say,
|
||||
* Debugger.Source for faster querying, if these methods are so hot. First, the
|
||||
* hottest method is actually just getting all scripts; second, populating the
|
||||
* store becomes prohibitively expensive. So we fall back to linear queries
|
||||
* (which isn't so bad, because Debugger.prototype.findScripts is also linear).
|
||||
*/
|
||||
function ScriptStore() {
|
||||
// Set of every Debugger.Script in the cache.
|
||||
this._scripts = new NoDeleteSet;
|
||||
}
|
||||
|
||||
// module.exports = ScriptStore;
|
||||
|
||||
ScriptStore.prototype = {
|
||||
// Populating a ScriptStore.
|
||||
|
||||
/**
|
||||
* Add one script to the cache.
|
||||
*
|
||||
* @param Debugger.Script script
|
||||
*/
|
||||
addScript: function(script) {
|
||||
this._scripts.add(script);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add many scripts to the cache at once.
|
||||
*
|
||||
* @param Array scripts
|
||||
* The set of Debugger.Scripts to add to the cache.
|
||||
*/
|
||||
addScripts: function(scripts) {
|
||||
for (var i = 0, len = scripts.length; i < len; i++) {
|
||||
this.addScript(scripts[i]);
|
||||
}
|
||||
},
|
||||
|
||||
// Querying a ScriptStore.
|
||||
|
||||
/**
|
||||
* Get all the sources for which we have scripts cached.
|
||||
*
|
||||
* @returns Array of Debugger.Source
|
||||
*/
|
||||
getSources: function() {
|
||||
return [...new Set(this._scripts.items.map(s => s.source))];
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all the scripts in the cache.
|
||||
*
|
||||
* @returns read-only Array of Debugger.Script.
|
||||
*
|
||||
* NB: The ScriptStore retains ownership of the returned array, and the
|
||||
* ScriptStore's consumers MUST NOT MODIFY its contents!
|
||||
*/
|
||||
getAllScripts: function() {
|
||||
return this._scripts.items;
|
||||
},
|
||||
|
||||
getScriptsBySourceActor: function(sourceActor) {
|
||||
return sourceActor.source ?
|
||||
this.getScriptsBySource(sourceActor.source) :
|
||||
this.getScriptsByURL(sourceActor._originalUrl);
|
||||
},
|
||||
|
||||
getScriptsBySourceActorAndLine: function(sourceActor, line) {
|
||||
return sourceActor.source ?
|
||||
this.getScriptsBySourceAndLine(sourceActor.source, line) :
|
||||
this.getScriptsByURLAndLine(sourceActor._originalUrl, line);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all scripts produced from the given source.
|
||||
*
|
||||
* @param Debugger.Source source
|
||||
* @returns Array of Debugger.Script
|
||||
*/
|
||||
getScriptsBySource: function(source) {
|
||||
var results = [];
|
||||
var scripts = this._scripts.items;
|
||||
var length = scripts.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (scripts[i].source === source) {
|
||||
results.push(scripts[i]);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all scripts produced from the given source whose source code definition
|
||||
* spans the given line.
|
||||
*
|
||||
* @param Debugger.Source source
|
||||
* @param Number line
|
||||
* @returns Array of Debugger.Script
|
||||
*/
|
||||
getScriptsBySourceAndLine: function(source, line) {
|
||||
var results = [];
|
||||
var scripts = this._scripts.items;
|
||||
var length = scripts.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
var script = scripts[i];
|
||||
if (script.source === source &&
|
||||
script.startLine <= line &&
|
||||
(script.startLine + script.lineCount) > line) {
|
||||
results.push(script);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all scripts defined by a source at the given URL.
|
||||
*
|
||||
* @param String url
|
||||
* @returns Array of Debugger.Script
|
||||
*/
|
||||
getScriptsByURL: function(url) {
|
||||
var results = [];
|
||||
var scripts = this._scripts.items;
|
||||
var length = scripts.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (scripts[i].url === url) {
|
||||
results.push(scripts[i]);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all scripts defined by a source a the given URL and whose source code
|
||||
* definition spans the given line.
|
||||
*
|
||||
* @param String url
|
||||
* @param Number line
|
||||
* @returns Array of Debugger.Script
|
||||
*/
|
||||
getScriptsByURLAndLine: function(url, line) {
|
||||
var results = [];
|
||||
var scripts = this._scripts.items;
|
||||
var length = scripts.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
var script = scripts[i];
|
||||
if (script.url === url &&
|
||||
script.startLine <= line &&
|
||||
(script.startLine + script.lineCount) > line) {
|
||||
results.push(script);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A set which can only grow, and does not support the delete operation.
|
||||
* Provides faster iteration than the native Set by maintaining an array of all
|
||||
* items, in addition to the internal set of all items, which allows direct
|
||||
* iteration (without the iteration protocol and calling into C++, which are
|
||||
* both expensive).
|
||||
*/
|
||||
function NoDeleteSet() {
|
||||
this._set = new Set();
|
||||
this.items = [];
|
||||
}
|
||||
|
||||
NoDeleteSet.prototype = {
|
||||
/**
|
||||
* An array containing every item in the set for convenience and faster
|
||||
* iteration. This is public for reading only, and consumers MUST NOT modify
|
||||
* this array!
|
||||
*/
|
||||
items: null,
|
||||
|
||||
/**
|
||||
* Add an item to the set.
|
||||
*
|
||||
* @param any item
|
||||
*/
|
||||
add: function(item) {
|
||||
if (!this._set.has(item)) {
|
||||
this._set.add(item);
|
||||
this.items.push(item);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Return true if the item is in the set, false otherwise.
|
||||
*
|
||||
* @param any item
|
||||
* @returns Boolean
|
||||
*/
|
||||
has: function(item) {
|
||||
return this._set.has(item);
|
||||
}
|
||||
};
|
||||
@@ -1,847 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { Ci, Cu } = require("chrome");
|
||||
// const DevToolsUtils = require("devtools/shared/DevToolsUtils");
|
||||
// const { assert, fetch } = DevToolsUtils.;
|
||||
// const EventEmitter = require("devtools/shared/event-emitter");
|
||||
// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common");
|
||||
// const { resolve } = require("promise");
|
||||
// const { joinURI } = require("devtools/shared/path");
|
||||
|
||||
// loader.lazyRequireGetter(this, "SourceActor", "devtools/server/actors/source", true);
|
||||
// loader.lazyRequireGetter(this, "isEvalSource", "devtools/server/actors/source", true);
|
||||
// loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true);
|
||||
// loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true);
|
||||
|
||||
/**
|
||||
* Manages the sources for a thread. Handles source maps, locations in the
|
||||
* sources, etc for ThreadActors.
|
||||
*/
|
||||
function TabSources(threadActor, allowSourceFn = () => true) {
|
||||
EventEmitter.decorate(this);
|
||||
|
||||
this._thread = threadActor;
|
||||
this._useSourceMaps = true;
|
||||
this._autoBlackBox = true;
|
||||
this._anonSourceMapId = 1;
|
||||
this.allowSource = source => {
|
||||
return !isHiddenSource(source) && allowSourceFn(source);
|
||||
};
|
||||
|
||||
this.blackBoxedSources = new Set();
|
||||
this.prettyPrintedSources = new Map();
|
||||
this.neverAutoBlackBoxSources = new Set();
|
||||
|
||||
// generated Debugger.Source -> promise of SourceMapConsumer
|
||||
this._sourceMaps = new Map();
|
||||
// sourceMapURL -> promise of SourceMapConsumer
|
||||
this._sourceMapCache = Object.create(null);
|
||||
// Debugger.Source -> SourceActor
|
||||
this._sourceActors = new Map();
|
||||
// url -> SourceActor
|
||||
this._sourceMappedSourceActors = Object.create(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches strings of the form "foo.min.js" or "foo-min.js", etc. If the regular
|
||||
* expression matches, we can be fairly sure that the source is minified, and
|
||||
* treat it as such.
|
||||
*/
|
||||
const MINIFIED_SOURCE_REGEXP = /\bmin\.js$/;
|
||||
|
||||
TabSources.prototype = {
|
||||
/**
|
||||
* Update preferences and clear out existing sources
|
||||
*/
|
||||
reconfigure: function(options) {
|
||||
if ('useSourceMaps' in options) {
|
||||
this._useSourceMaps = options.useSourceMaps;
|
||||
}
|
||||
|
||||
if ('autoBlackBox' in options) {
|
||||
this._autoBlackBox = options.autoBlackBox;
|
||||
}
|
||||
|
||||
this.reset();
|
||||
},
|
||||
|
||||
/**
|
||||
* Update preferences and clear out existing sources
|
||||
*/
|
||||
setOptions: function (options) {
|
||||
let shouldReset = false;
|
||||
|
||||
if ("useSourceMaps" in options) {
|
||||
shouldReset = true;
|
||||
this._useSourceMaps = options.useSourceMaps;
|
||||
}
|
||||
|
||||
if ("autoBlackBox" in options) {
|
||||
shouldReset = true;
|
||||
this._autoBlackBox = options.autoBlackBox;
|
||||
}
|
||||
|
||||
if (shouldReset) {
|
||||
this.reset();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear existing sources so they are recreated on the next access.
|
||||
*
|
||||
* @param Object opts
|
||||
* Specify { sourceMaps: true } if you also want to clear
|
||||
* the source map cache (usually done on reload).
|
||||
*/
|
||||
reset: function (opts = {}) {
|
||||
this._sourceActors = new Map();
|
||||
this._sourceMaps = new Map();
|
||||
this._sourceMappedSourceActors = Object.create(null);
|
||||
|
||||
if (opts.sourceMaps) {
|
||||
this._sourceMapCache = Object.create(null);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the source actor representing the `source` (or
|
||||
* `originalUrl`), creating one if none exists already. May return
|
||||
* null if the source is disallowed.
|
||||
*
|
||||
* @param Debugger.Source source
|
||||
* The source to make an actor for
|
||||
* @param String originalUrl
|
||||
* The original source URL of a sourcemapped source
|
||||
* @param optional Debguger.Source generatedSource
|
||||
* The generated source that introduced this source via source map,
|
||||
* if any.
|
||||
* @param optional String contentType
|
||||
* The content type of the source, if immediately available.
|
||||
* @returns a SourceActor representing the source or null.
|
||||
*/
|
||||
source: function ({ source, originalUrl, generatedSource,
|
||||
isInlineSource, contentType }) {
|
||||
DevToolsUtils.assert(source || (originalUrl && generatedSource),
|
||||
"TabSources.prototype.source needs an originalUrl or a source");
|
||||
|
||||
if (source) {
|
||||
// If a source is passed, we are creating an actor for a real
|
||||
// source, which may or may not be sourcemapped.
|
||||
|
||||
if (!this.allowSource(source)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// It's a hack, but inline HTML scripts each have real sources,
|
||||
// but we want to represent all of them as one source as the
|
||||
// HTML page. The actor representing this fake HTML source is
|
||||
// stored in this array, which always has a URL, so check it
|
||||
// first.
|
||||
if (source.url in this._sourceMappedSourceActors) {
|
||||
return this._sourceMappedSourceActors[source.url];
|
||||
}
|
||||
|
||||
if (isInlineSource) {
|
||||
// If it's an inline source, the fake HTML source hasn't been
|
||||
// created yet (would have returned above), so flip this source
|
||||
// into a sourcemapped state by giving it an `originalUrl` which
|
||||
// is the HTML url.
|
||||
originalUrl = source.url;
|
||||
source = null;
|
||||
}
|
||||
else if (this._sourceActors.has(source)) {
|
||||
return this._sourceActors.get(source);
|
||||
}
|
||||
}
|
||||
else if (originalUrl) {
|
||||
// Not all "original" scripts are distinctly separate from the
|
||||
// generated script. Pretty-printed sources have a sourcemap for
|
||||
// themselves, so we need to make sure there a real source
|
||||
// doesn't already exist with this URL.
|
||||
for (let [source, actor] of this._sourceActors) {
|
||||
if (source.url === originalUrl) {
|
||||
return actor;
|
||||
}
|
||||
}
|
||||
|
||||
if (originalUrl in this._sourceMappedSourceActors) {
|
||||
return this._sourceMappedSourceActors[originalUrl];
|
||||
}
|
||||
}
|
||||
|
||||
let actor = new SourceActor({
|
||||
thread: this._thread,
|
||||
source: source,
|
||||
originalUrl: originalUrl,
|
||||
generatedSource: generatedSource,
|
||||
isInlineSource: isInlineSource,
|
||||
contentType: contentType
|
||||
});
|
||||
|
||||
let sourceActorStore = this._thread.sourceActorStore;
|
||||
var id = sourceActorStore.getReusableActorId(source, originalUrl);
|
||||
if (id) {
|
||||
actor.actorID = id;
|
||||
}
|
||||
|
||||
this._thread.threadLifetimePool.addActor(actor);
|
||||
sourceActorStore.setReusableActorId(source, originalUrl, actor.actorID);
|
||||
|
||||
if (this._autoBlackBox &&
|
||||
!this.neverAutoBlackBoxSources.has(actor.url) &&
|
||||
this._isMinifiedURL(actor.url)) {
|
||||
|
||||
this.blackBox(actor.url);
|
||||
this.neverAutoBlackBoxSources.add(actor.url);
|
||||
}
|
||||
|
||||
if (source) {
|
||||
this._sourceActors.set(source, actor);
|
||||
}
|
||||
else {
|
||||
this._sourceMappedSourceActors[originalUrl] = actor;
|
||||
}
|
||||
|
||||
this._emitNewSource(actor);
|
||||
return actor;
|
||||
},
|
||||
|
||||
_emitNewSource: function (actor) {
|
||||
if (!actor.source) {
|
||||
// Always notify if we don't have a source because that means
|
||||
// it's something that has been sourcemapped, or it represents
|
||||
// the HTML file that contains inline sources.
|
||||
this.emit("newSource", actor);
|
||||
}
|
||||
else {
|
||||
// If sourcemapping is enabled and a source has sourcemaps, we
|
||||
// create `SourceActor` instances for both the original and
|
||||
// generated sources. The source actors for the generated
|
||||
// sources are only for internal use, however; breakpoints are
|
||||
// managed by these internal actors. We only want to notify the
|
||||
// user of the original sources though, so if the actor has a
|
||||
// `Debugger.Source` instance and a valid source map (meaning
|
||||
// it's a generated source), don't send the notification.
|
||||
this.fetchSourceMap(actor.source).then(map => {
|
||||
if (!map) {
|
||||
this.emit("newSource", actor);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
getSourceActor: function (source) {
|
||||
if (source.url in this._sourceMappedSourceActors) {
|
||||
return this._sourceMappedSourceActors[source.url];
|
||||
}
|
||||
|
||||
if (this._sourceActors.has(source)) {
|
||||
return this._sourceActors.get(source);
|
||||
}
|
||||
|
||||
throw new Error("getSource: could not find source actor for " +
|
||||
(source.url || "source"));
|
||||
},
|
||||
|
||||
getSourceActorByURL: function (url) {
|
||||
if (url) {
|
||||
for (let [source, actor] of this._sourceActors) {
|
||||
if (source.url === url) {
|
||||
return actor;
|
||||
}
|
||||
}
|
||||
|
||||
if (url in this._sourceMappedSourceActors) {
|
||||
return this._sourceMappedSourceActors[url];
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("getSourceActorByURL: could not find source for " + url);
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the URL likely points to a minified resource, false
|
||||
* otherwise.
|
||||
*
|
||||
* @param String aURL
|
||||
* The URL to test.
|
||||
* @returns Boolean
|
||||
*/
|
||||
_isMinifiedURL: function (aURL) {
|
||||
if (!aURL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
let url = new URL(aURL);
|
||||
let pathname = url.pathname;
|
||||
return MINIFIED_SOURCE_REGEXP.test(pathname.slice(pathname.lastIndexOf("/") + 1));
|
||||
} catch (e) {
|
||||
// Not a valid URL so don't try to parse out the filename, just test the
|
||||
// whole thing with the minified source regexp.
|
||||
return MINIFIED_SOURCE_REGEXP.test(aURL);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a source actor representing this source. This ignores
|
||||
* source mapping and always returns an actor representing this real
|
||||
* source. Use `createSourceActors` if you want to respect source maps.
|
||||
*
|
||||
* @param Debugger.Source aSource
|
||||
* The source instance to create an actor for.
|
||||
* @returns SourceActor
|
||||
*/
|
||||
createNonSourceMappedActor: function (aSource) {
|
||||
// Don't use getSourceURL because we don't want to consider the
|
||||
// displayURL property if it's an eval source. We only want to
|
||||
// consider real URLs, otherwise if there is a URL but it's
|
||||
// invalid the code below will not set the content type, and we
|
||||
// will later try to fetch the contents of the URL to figure out
|
||||
// the content type, but it's a made up URL for eval sources.
|
||||
let url = isEvalSource(aSource) ? null : aSource.url;
|
||||
let spec = { source: aSource };
|
||||
|
||||
// XXX bug 915433: We can't rely on Debugger.Source.prototype.text
|
||||
// if the source is an HTML-embedded <script> tag. Since we don't
|
||||
// have an API implemented to detect whether this is the case, we
|
||||
// need to be conservative and only treat valid js files as real
|
||||
// sources. Otherwise, use the `originalUrl` property to treat it
|
||||
// as an HTML source that manages multiple inline sources.
|
||||
|
||||
// Assume the source is inline if the element that introduced it is not a
|
||||
// script element, or does not have a src attribute.
|
||||
let element = aSource.element ? aSource.element.unsafeDereference() : null;
|
||||
if (element && (element.tagName !== "SCRIPT" || !element.hasAttribute("src"))) {
|
||||
spec.isInlineSource = true;
|
||||
} else if (aSource.introductionType === "wasm") {
|
||||
// Wasm sources are not JavaScript. Give them their own content-type.
|
||||
spec.contentType = "text/wasm";
|
||||
} else {
|
||||
if (url) {
|
||||
// There are a few special URLs that we know are JavaScript:
|
||||
// inline `javascript:` and code coming from the console
|
||||
if (url.indexOf("Scratchpad/") === 0 ||
|
||||
url.indexOf("javascript:") === 0 ||
|
||||
url === "debugger eval code") {
|
||||
spec.contentType = "text/javascript";
|
||||
} else {
|
||||
try {
|
||||
let pathname = new URL(url).pathname;
|
||||
let filename = pathname.slice(pathname.lastIndexOf("/") + 1);
|
||||
let index = filename.lastIndexOf(".");
|
||||
let extension = index >= 0 ? filename.slice(index + 1) : "";
|
||||
if (extension === "xml") {
|
||||
// XUL inline scripts may not correctly have the
|
||||
// `source.element` property, so do a blunt check here if
|
||||
// it's an xml page.
|
||||
spec.isInlineSource = true;
|
||||
}
|
||||
else if (extension === "js") {
|
||||
spec.contentType = "text/javascript";
|
||||
}
|
||||
} catch (e) {
|
||||
// This only needs to be here because URL is not yet exposed to
|
||||
// workers. (BUG 1258892)
|
||||
const filename = url;
|
||||
const index = filename.lastIndexOf(".");
|
||||
const extension = index >= 0 ? filename.slice(index + 1) : "";
|
||||
if (extension === "js") {
|
||||
spec.contentType = "text/javascript";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Assume the content is javascript if there's no URL
|
||||
spec.contentType = "text/javascript";
|
||||
}
|
||||
}
|
||||
return this.source(spec);
|
||||
},
|
||||
|
||||
/**
|
||||
* This is an internal function that returns a promise of an array
|
||||
* of source actors representing all the source mapped sources of
|
||||
* `aSource`, or `null` if the source is not sourcemapped or
|
||||
* sourcemapping is disabled. Users should call `createSourceActors`
|
||||
* instead of this.
|
||||
*
|
||||
* @param Debugger.Source aSource
|
||||
* The source instance to create actors for.
|
||||
* @return Promise of an array of source actors
|
||||
*/
|
||||
_createSourceMappedActors: function (aSource) {
|
||||
if (!this._useSourceMaps || !aSource.sourceMapURL) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
return this.fetchSourceMap(aSource)
|
||||
.then(map => {
|
||||
if (map) {
|
||||
return map.sources.map(s => {
|
||||
return this.source({ originalUrl: s, generatedSource: aSource });
|
||||
}).filter(isNotNull);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates the source actors representing the appropriate sources
|
||||
* of `aSource`. If sourcemapped, returns actors for all of the original
|
||||
* sources, otherwise returns a 1-element array with the actor for
|
||||
* `aSource`.
|
||||
*
|
||||
* @param Debugger.Source aSource
|
||||
* The source instance to create actors for.
|
||||
* @param Promise of an array of source actors
|
||||
*/
|
||||
createSourceActors: function (aSource) {
|
||||
return this._createSourceMappedActors(aSource).then(actors => {
|
||||
let actor = this.createNonSourceMappedActor(aSource);
|
||||
return (actors || [actor]).filter(isNotNull);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a promise of a SourceMapConsumer for the source map for
|
||||
* `aSource`; if we already have such a promise extant, return that.
|
||||
* This will fetch the source map if we don't have a cached object
|
||||
* and source maps are enabled (see `_fetchSourceMap`).
|
||||
*
|
||||
* @param Debugger.Source aSource
|
||||
* The source instance to get sourcemaps for.
|
||||
* @return Promise of a SourceMapConsumer
|
||||
*/
|
||||
fetchSourceMap: function (aSource) {
|
||||
if (!this._useSourceMaps) {
|
||||
return resolve(null);
|
||||
}
|
||||
else if (this._sourceMaps.has(aSource)) {
|
||||
return this._sourceMaps.get(aSource);
|
||||
}
|
||||
else if (!aSource || !aSource.sourceMapURL) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
let sourceMapURL = aSource.sourceMapURL;
|
||||
if (aSource.url) {
|
||||
sourceMapURL = joinURI(aSource.url, sourceMapURL);
|
||||
}
|
||||
let result = this._fetchSourceMap(sourceMapURL, aSource.url);
|
||||
|
||||
// The promises in `_sourceMaps` must be the exact same instances
|
||||
// as returned by `_fetchSourceMap` for `clearSourceMapCache` to
|
||||
// work.
|
||||
this._sourceMaps.set(aSource, result);
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a promise of a SourceMapConsumer for the source map for
|
||||
* `aSource`. The resolved result may be null if the source does not
|
||||
* have a source map or source maps are disabled.
|
||||
*/
|
||||
getSourceMap: function (aSource) {
|
||||
return Promise.resolve(this._sourceMaps.get(aSource));
|
||||
},
|
||||
|
||||
/**
|
||||
* Set a SourceMapConsumer for the source map for
|
||||
* |aSource|.
|
||||
*/
|
||||
setSourceMap: function (aSource, aMap) {
|
||||
this._sourceMaps.set(aSource, Promise.resolve(aMap));
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a promise of a SourceMapConsumer for the source map located at
|
||||
* |aAbsSourceMapURL|, which must be absolute. If there is already such a
|
||||
* promise extant, return it. This will not fetch if source maps are
|
||||
* disabled.
|
||||
*
|
||||
* @param string aAbsSourceMapURL
|
||||
* The source map URL, in absolute form, not relative.
|
||||
* @param string aScriptURL
|
||||
* When the source map URL is a data URI, there is no sourceRoot on the
|
||||
* source map, and the source map's sources are relative, we resolve
|
||||
* them from aScriptURL.
|
||||
*/
|
||||
_fetchSourceMap: function (aAbsSourceMapURL, aSourceURL) {
|
||||
DevToolsUtils.assert(this._useSourceMaps,
|
||||
"Cannot fetch sourcemaps if they are disabled");
|
||||
|
||||
if (this._sourceMapCache[aAbsSourceMapURL]) {
|
||||
return this._sourceMapCache[aAbsSourceMapURL];
|
||||
}
|
||||
|
||||
let fetching = DevToolsUtils.fetch(aAbsSourceMapURL, { loadFromCache: false })
|
||||
.then(({ content }) => {
|
||||
let map = new SourceMapConsumer(content);
|
||||
this._setSourceMapRoot(map, aAbsSourceMapURL, aSourceURL);
|
||||
return map;
|
||||
})
|
||||
.then(null, error => {
|
||||
if (!DevToolsUtils.reportingDisabled) {
|
||||
DevToolsUtils.reportException("TabSources.prototype._fetchSourceMap", error);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
this._sourceMapCache[aAbsSourceMapURL] = fetching;
|
||||
return fetching;
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the source map's sourceRoot to be relative to the source map url.
|
||||
*/
|
||||
_setSourceMapRoot: function (aSourceMap, aAbsSourceMapURL, aScriptURL) {
|
||||
// No need to do this fiddling if we won't be fetching any sources over the
|
||||
// wire.
|
||||
if (aSourceMap.hasContentsOfAllSources()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const base = this._dirname(
|
||||
aAbsSourceMapURL.indexOf("data:") === 0
|
||||
? aScriptURL
|
||||
: aAbsSourceMapURL);
|
||||
aSourceMap.sourceRoot = aSourceMap.sourceRoot
|
||||
? joinURI(base, aSourceMap.sourceRoot)
|
||||
: base;
|
||||
},
|
||||
|
||||
_dirname: function (aPath) {
|
||||
let url = new URL(aPath);
|
||||
let href = url.href;
|
||||
return href.slice(0, href.lastIndexOf("/"));
|
||||
},
|
||||
|
||||
/**
|
||||
* Clears the source map cache. Source maps are cached by URL so
|
||||
* they can be reused across separate Debugger instances (once in
|
||||
* this cache, they will never be reparsed again). They are
|
||||
* also cached by Debugger.Source objects for usefulness. By default
|
||||
* this just removes the Debugger.Source cache, but you can remove
|
||||
* the lower-level URL cache with the `hard` option.
|
||||
*
|
||||
* @param aSourceMapURL string
|
||||
* The source map URL to uncache
|
||||
* @param opts object
|
||||
* An object with the following properties:
|
||||
* - hard: Also remove the lower-level URL cache, which will
|
||||
* make us completely forget about the source map.
|
||||
*/
|
||||
clearSourceMapCache: function (aSourceMapURL, opts = { hard: false }) {
|
||||
let oldSm = this._sourceMapCache[aSourceMapURL];
|
||||
|
||||
if (opts.hard) {
|
||||
delete this._sourceMapCache[aSourceMapURL];
|
||||
}
|
||||
|
||||
if (oldSm) {
|
||||
// Clear out the current cache so all sources will get the new one
|
||||
for (let [source, sm] of this._sourceMaps.entries()) {
|
||||
if (sm === oldSm) {
|
||||
this._sourceMaps.delete(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
* Forcefully change the source map of a source, changing the
|
||||
* sourceMapURL and installing the source map in the cache. This is
|
||||
* necessary to expose changes across Debugger instances
|
||||
* (pretty-printing is the use case). Generate a random url if one
|
||||
* isn't specified, allowing you to set "anonymous" source maps.
|
||||
*
|
||||
* @param aSource Debugger.Source
|
||||
* The source to change the sourceMapURL property
|
||||
* @param aUrl string
|
||||
* The source map URL (optional)
|
||||
* @param aMap SourceMapConsumer
|
||||
* The source map instance
|
||||
*/
|
||||
setSourceMapHard: function (aSource, aUrl, aMap) {
|
||||
let url = aUrl;
|
||||
if (!url) {
|
||||
// This is a littly hacky, but we want to forcefully set a
|
||||
// sourcemap regardless of sourcemap settings. We want to
|
||||
// literally change the sourceMapURL so that all debuggers will
|
||||
// get this and pretty-printing will Just Work (Debugger.Source
|
||||
// instances are per-debugger, so we can't key off that). To
|
||||
// avoid tons of work serializing the sourcemap into a data url,
|
||||
// just make a fake URL and stick the sourcemap there.
|
||||
url = "internal://sourcemap" + (this._anonSourceMapId++) + "/";
|
||||
}
|
||||
aSource.sourceMapURL = url;
|
||||
|
||||
// Forcefully set the sourcemap cache. This will be used even if
|
||||
// sourcemaps are disabled.
|
||||
this._sourceMapCache[url] = Promise.resolve(aMap);
|
||||
this.emit("updatedSource", this.getSourceActor(aSource));
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the non-source-mapped location of the given Debugger.Frame. If the
|
||||
* frame does not have a script, the location's properties are all null.
|
||||
*
|
||||
* @param Debugger.Frame aFrame
|
||||
* The frame whose location we are getting.
|
||||
* @returns Object
|
||||
* Returns an object of the form { source, line, column }
|
||||
*/
|
||||
getFrameLocation: function (aFrame) {
|
||||
if (!aFrame || !aFrame.script) {
|
||||
return new GeneratedLocation();
|
||||
}
|
||||
let {lineNumber, columnNumber} =
|
||||
aFrame.script.getOffsetLocation(aFrame.offset);
|
||||
return new GeneratedLocation(
|
||||
this.createNonSourceMappedActor(aFrame.script.source),
|
||||
lineNumber,
|
||||
columnNumber
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a promise of the location in the original source if the source is
|
||||
* source mapped, otherwise a promise of the same location. This can
|
||||
* be called with a source from *any* Debugger instance and we make
|
||||
* sure to that it works properly, reusing source maps if already
|
||||
* fetched. Use this from any actor that needs sourcemapping.
|
||||
*/
|
||||
getOriginalLocation: function (generatedLocation) {
|
||||
let {
|
||||
generatedSourceActor,
|
||||
generatedLine,
|
||||
generatedColumn
|
||||
} = generatedLocation;
|
||||
let source = generatedSourceActor.source;
|
||||
let url = source ? source.url : generatedSourceActor._originalUrl;
|
||||
|
||||
// In certain scenarios the source map may have not been fetched
|
||||
// yet (or at least tied to this Debugger.Source instance), so use
|
||||
// `fetchSourceMap` instead of `getSourceMap`. This allows this
|
||||
// function to be called from anywere (across debuggers) and it
|
||||
// should just automatically work.
|
||||
return this.fetchSourceMap(source).then(map => {
|
||||
if (map) {
|
||||
let {
|
||||
source: originalUrl,
|
||||
line: originalLine,
|
||||
column: originalColumn,
|
||||
name: originalName
|
||||
} = map.originalPositionFor({
|
||||
line: generatedLine,
|
||||
column: generatedColumn == null ? Infinity : generatedColumn
|
||||
});
|
||||
|
||||
// Since the `Debugger.Source` instance may come from a
|
||||
// different `Debugger` instance (any actor can call this
|
||||
// method), we can't rely on any of the source discovery
|
||||
// setup (`_discoverSources`, etc) to have been run yet. So
|
||||
// we have to assume that the actor may not already exist,
|
||||
// and we might need to create it, so use `source` and give
|
||||
// it the required parameters for a sourcemapped source.
|
||||
return new OriginalLocation(
|
||||
originalUrl ? this.source({
|
||||
originalUrl: originalUrl,
|
||||
generatedSource: source
|
||||
}) : null,
|
||||
originalLine,
|
||||
originalColumn,
|
||||
originalName
|
||||
);
|
||||
}
|
||||
|
||||
// No source map
|
||||
return OriginalLocation.fromGeneratedLocation(generatedLocation);
|
||||
});
|
||||
},
|
||||
|
||||
getAllGeneratedLocations: function (originalLocation) {
|
||||
let {
|
||||
originalSourceActor,
|
||||
originalLine,
|
||||
originalColumn
|
||||
} = originalLocation;
|
||||
|
||||
let source = (originalSourceActor.source ||
|
||||
originalSourceActor.generatedSource);
|
||||
|
||||
return this.fetchSourceMap(source).then((map) => {
|
||||
if (map) {
|
||||
map.computeColumnSpans();
|
||||
|
||||
return map.allGeneratedPositionsFor({
|
||||
source: originalSourceActor.url,
|
||||
line: originalLine,
|
||||
column: originalColumn
|
||||
}).map(({ line, column, lastColumn }) => {
|
||||
return new GeneratedLocation(
|
||||
this.createNonSourceMappedActor(source),
|
||||
line,
|
||||
column,
|
||||
lastColumn
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return [GeneratedLocation.fromOriginalLocation(originalLocation)];
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Returns a promise of the location in the generated source corresponding to
|
||||
* the original source and line given.
|
||||
*
|
||||
* When we pass a script S representing generated code to `sourceMap`,
|
||||
* above, that returns a promise P. The process of resolving P populates
|
||||
* the tables this function uses; thus, it won't know that S's original
|
||||
* source URLs map to S until P is resolved.
|
||||
*/
|
||||
getGeneratedLocation: function (originalLocation) {
|
||||
let { originalSourceActor } = originalLocation;
|
||||
|
||||
// Both original sources and normal sources could have sourcemaps,
|
||||
// because normal sources can be pretty-printed which generates a
|
||||
// sourcemap for itself. Check both of the source properties to make it work
|
||||
// for both kinds of sources.
|
||||
let source = originalSourceActor.source || originalSourceActor.generatedSource;
|
||||
|
||||
// See comment about `fetchSourceMap` in `getOriginalLocation`.
|
||||
return this.fetchSourceMap(source).then((map) => {
|
||||
if (map) {
|
||||
let {
|
||||
originalLine,
|
||||
originalColumn
|
||||
} = originalLocation;
|
||||
|
||||
let {
|
||||
line: generatedLine,
|
||||
column: generatedColumn
|
||||
} = map.generatedPositionFor({
|
||||
source: originalSourceActor.url,
|
||||
line: originalLine,
|
||||
column: originalColumn == null ? 0 : originalColumn,
|
||||
bias: SourceMapConsumer.LEAST_UPPER_BOUND
|
||||
});
|
||||
|
||||
return new GeneratedLocation(
|
||||
this.createNonSourceMappedActor(source),
|
||||
generatedLine,
|
||||
generatedColumn
|
||||
);
|
||||
}
|
||||
|
||||
return GeneratedLocation.fromOriginalLocation(originalLocation);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if URL for the given source is black boxed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source which we are checking whether it is black
|
||||
* boxed or not.
|
||||
*/
|
||||
isBlackBoxed: function (aURL) {
|
||||
return this.blackBoxedSources.has(aURL);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add the given source URL to the set of sources that are black boxed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source which we are black boxing.
|
||||
*/
|
||||
blackBox: function (aURL) {
|
||||
this.blackBoxedSources.add(aURL);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove the given source URL to the set of sources that are black boxed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source which we are no longer black boxing.
|
||||
*/
|
||||
unblackBox: function (aURL) {
|
||||
this.blackBoxedSources.delete(aURL);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the given URL is pretty printed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source that might be pretty printed.
|
||||
*/
|
||||
isPrettyPrinted: function (aURL) {
|
||||
return this.prettyPrintedSources.has(aURL);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add the given URL to the set of sources that are pretty printed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source to be pretty printed.
|
||||
*/
|
||||
prettyPrint: function (aURL, aIndent) {
|
||||
this.prettyPrintedSources.set(aURL, aIndent);
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the indent the given URL was pretty printed by.
|
||||
*/
|
||||
prettyPrintIndent: function (aURL) {
|
||||
return this.prettyPrintedSources.get(aURL);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove the given URL from the set of sources that are pretty printed.
|
||||
*
|
||||
* @param aURL String
|
||||
* The URL of the source that is no longer pretty printed.
|
||||
*/
|
||||
disablePrettyPrint: function (aURL) {
|
||||
this.prettyPrintedSources.delete(aURL);
|
||||
},
|
||||
|
||||
iter: function () {
|
||||
let actors = Object.keys(this._sourceMappedSourceActors).map(k => {
|
||||
return this._sourceMappedSourceActors[k];
|
||||
});
|
||||
for (let actor of this._sourceActors.values()) {
|
||||
if (!this._sourceMaps.has(actor.source)) {
|
||||
actors.push(actor);
|
||||
}
|
||||
}
|
||||
return actors;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Checks if a source should never be displayed to the user because
|
||||
* it's either internal or we don't support in the UI yet.
|
||||
*/
|
||||
function isHiddenSource(aSource) {
|
||||
// Ignore the internal Function.prototype script
|
||||
return aSource.text === "() {\n}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if its argument is not null.
|
||||
*/
|
||||
function isNotNull(aThing) {
|
||||
return aThing !== null;
|
||||
}
|
||||
|
||||
//exports.TabSources = TabSources;
|
||||
//exports.isHiddenSource = isHiddenSource;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,218 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/**
|
||||
* EventEmitter.
|
||||
*/
|
||||
|
||||
// (function (factory) { // Module boilerplate
|
||||
// if (this.module && module.id.indexOf("event-emitter") >= 0) { // require
|
||||
// factory.call(this, require, exports, module);
|
||||
// } else { // Cu.import
|
||||
// const Cu = Components.utils;
|
||||
// const { require } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
|
||||
// this.isWorker = false;
|
||||
// this.promise = Cu.import("resource://gre/modules/Promise.jsm", {}).Promise;
|
||||
// factory.call(this, require, this, { exports: this });
|
||||
// this.EXPORTED_SYMBOLS = ["EventEmitter"];
|
||||
// }
|
||||
// }).call(this, function (require, exports, module) {
|
||||
|
||||
this.EventEmitter = function EventEmitter() {};
|
||||
// module.exports = EventEmitter;
|
||||
|
||||
// const { Cu, components } = require("chrome");
|
||||
// const Services = require("Services");
|
||||
// const promise = require("promise");
|
||||
var loggingEnabled = true;
|
||||
|
||||
// if (!isWorker) {
|
||||
// loggingEnabled = Services.prefs.getBoolPref("devtools.dump.emit");
|
||||
// Services.prefs.addObserver("devtools.dump.emit", {
|
||||
// observe: () => {
|
||||
// loggingEnabled = Services.prefs.getBoolPref("devtools.dump.emit");
|
||||
// }
|
||||
// }, false);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Decorate an object with event emitter functionality.
|
||||
*
|
||||
* @param Object objectToDecorate
|
||||
* Bind all public methods of EventEmitter to
|
||||
* the objectToDecorate object.
|
||||
*/
|
||||
EventEmitter.decorate = function (objectToDecorate) {
|
||||
let emitter = new EventEmitter();
|
||||
objectToDecorate.on = emitter.on.bind(emitter);
|
||||
objectToDecorate.off = emitter.off.bind(emitter);
|
||||
objectToDecorate.once = emitter.once.bind(emitter);
|
||||
objectToDecorate.emit = emitter.emit.bind(emitter);
|
||||
};
|
||||
|
||||
EventEmitter.prototype = {
|
||||
/**
|
||||
* Connect a listener.
|
||||
*
|
||||
* @param string event
|
||||
* The event name to which we're connecting.
|
||||
* @param function listener
|
||||
* Called when the event is fired.
|
||||
*/
|
||||
on(event, listener) {
|
||||
if (!this._eventEmitterListeners) {
|
||||
this._eventEmitterListeners = new Map();
|
||||
}
|
||||
if (!this._eventEmitterListeners.has(event)) {
|
||||
this._eventEmitterListeners.set(event, []);
|
||||
}
|
||||
this._eventEmitterListeners.get(event).push(listener);
|
||||
},
|
||||
|
||||
/**
|
||||
* Listen for the next time an event is fired.
|
||||
*
|
||||
* @param string event
|
||||
* The event name to which we're connecting.
|
||||
* @param function listener
|
||||
* (Optional) Called when the event is fired. Will be called at most
|
||||
* one time.
|
||||
* @return promise
|
||||
* A promise which is resolved when the event next happens. The
|
||||
* resolution value of the promise is the first event argument. If
|
||||
* you need access to second or subsequent event arguments (it's rare
|
||||
* that this is needed) then use listener
|
||||
*/
|
||||
once(event, listener) {
|
||||
let deferred = Promise.defer();
|
||||
|
||||
let handler = (_, first, ...rest) => {
|
||||
this.off(event, handler);
|
||||
if (listener) {
|
||||
listener.apply(null, [event, first, ...rest]);
|
||||
}
|
||||
deferred.resolve(first);
|
||||
};
|
||||
|
||||
handler._originalListener = listener;
|
||||
this.on(event, handler);
|
||||
|
||||
return deferred.promise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove a previously-registered event listener. Works for events
|
||||
* registered with either on or once.
|
||||
*
|
||||
* @param string event
|
||||
* The event name whose listener we're disconnecting.
|
||||
* @param function listener
|
||||
* The listener to remove.
|
||||
*/
|
||||
off(event, listener) {
|
||||
if (!this._eventEmitterListeners) {
|
||||
return;
|
||||
}
|
||||
let listeners = this._eventEmitterListeners.get(event);
|
||||
if (listeners) {
|
||||
this._eventEmitterListeners.set(event, listeners.filter(l => {
|
||||
return l !== listener && l._originalListener !== listener;
|
||||
}));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Emit an event. All arguments to this method will
|
||||
* be sent to listener functions.
|
||||
*/
|
||||
emit(event) {
|
||||
this.logEvent(event, arguments);
|
||||
|
||||
if (!this._eventEmitterListeners || !this._eventEmitterListeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let originalListeners = this._eventEmitterListeners.get(event);
|
||||
for (let listener of this._eventEmitterListeners.get(event)) {
|
||||
// If the object was destroyed during event emission, stop
|
||||
// emitting.
|
||||
if (!this._eventEmitterListeners) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If listeners were removed during emission, make sure the
|
||||
// event handler we're going to fire wasn't removed.
|
||||
if (originalListeners === this._eventEmitterListeners.get(event) ||
|
||||
this._eventEmitterListeners.get(event).some(l => l === listener)) {
|
||||
try {
|
||||
listener.apply(null, arguments);
|
||||
} catch (ex) {
|
||||
// Prevent a bad listener from interfering with the others.
|
||||
let msg = ex + ": " + ex.stack;
|
||||
log(msg);
|
||||
DevToolsUtils.dumpn(msg + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
logEvent(event, args) {
|
||||
if (!loggingEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
let caller, func, path;
|
||||
// if (!isWorker) {
|
||||
// caller = components.stack.caller.caller;
|
||||
// func = caller.name;
|
||||
// let file = caller.filename;
|
||||
// if (file.includes(" -> ")) {
|
||||
// file = caller.filename.split(/ -> /)[1];
|
||||
// }
|
||||
// path = file + ":" + caller.lineNumber;
|
||||
// }
|
||||
|
||||
let argOut = "(";
|
||||
if (args.length === 1) {
|
||||
argOut += event;
|
||||
}
|
||||
|
||||
let out = "EMITTING: ";
|
||||
|
||||
// We need this try / catch to prevent any dead object errors.
|
||||
try {
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
if (i === 1) {
|
||||
argOut = "(" + event + ", ";
|
||||
} else {
|
||||
argOut += ", ";
|
||||
}
|
||||
|
||||
let arg = args[i];
|
||||
argOut += arg;
|
||||
|
||||
if (arg && arg.nodeName) {
|
||||
argOut += " (" + arg.nodeName;
|
||||
if (arg.id) {
|
||||
argOut += "#" + arg.id;
|
||||
}
|
||||
if (arg.className) {
|
||||
argOut += "." + arg.className;
|
||||
}
|
||||
argOut += ")";
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Object is dead so the toolbox is most likely shutting down,
|
||||
// do nothing.
|
||||
}
|
||||
|
||||
argOut += ")";
|
||||
out += "emit" + argOut + " from " + func + "() -> " + path + "\n";
|
||||
|
||||
DevToolsUtils.dumpn(out);
|
||||
},
|
||||
};
|
||||
|
||||
// });
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,187 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
"use strict";
|
||||
|
||||
const UNCAUGHT_ERROR = 'An error event was emitted for which there was no listener.';
|
||||
const BAD_LISTENER = 'The event listener must be a function.';
|
||||
|
||||
const EVENT_TYPE_PATTERN = /^on([A-Z]\w+$)/;
|
||||
|
||||
// Count of total listeners ever added.
|
||||
// This is used to keep track of when a listener was added, which can
|
||||
// have an effect on when it is and isn't dispatched. See comments in
|
||||
// emitOnObject for more details.
|
||||
let listenerCount = 0;
|
||||
|
||||
const observers = new DefaultWeakMap(() => {
|
||||
return new DefaultMap(() => new Map());
|
||||
});
|
||||
|
||||
/**
|
||||
* Registers an event `listener` that is called every time events of
|
||||
* specified `type` is emitted on the given event `target`.
|
||||
* @param {Object} target
|
||||
* Event target object.
|
||||
* @param {String} type
|
||||
* The type of event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
*/
|
||||
function on(target, type, listener) {
|
||||
if (typeof(listener) !== 'function')
|
||||
throw new Error(BAD_LISTENER);
|
||||
|
||||
observers.get(target).get(type).set(listener, listenerCount++);
|
||||
}
|
||||
// exports.on = on;
|
||||
|
||||
|
||||
// Map of wrapper functions for listeners added using `once`.
|
||||
var onceWeakMap = new WeakMap();
|
||||
|
||||
/**
|
||||
* Registers an event `listener` that is called only the next time an event
|
||||
* of the specified `type` is emitted on the given event `target`.
|
||||
* @param {Object} target
|
||||
* Event target object.
|
||||
* @param {String} type
|
||||
* The type of the event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
*/
|
||||
function once(target, type, listener) {
|
||||
function replacement(...args) {
|
||||
off(target, type, replacement);
|
||||
onceWeakMap.delete(listener);
|
||||
listener.apply(target, args);
|
||||
};
|
||||
onceWeakMap.set(listener, replacement);
|
||||
on(target, type, replacement);
|
||||
}
|
||||
// exports.once = once;
|
||||
|
||||
/**
|
||||
* Execute each of the listeners in order with the supplied arguments.
|
||||
* All the exceptions that are thrown by listeners during the emit
|
||||
* are caught and can be handled by listeners of 'error' event. Thrown
|
||||
* exceptions are passed as an argument to an 'error' event listener.
|
||||
* If no 'error' listener is registered exception will be logged into an
|
||||
* error console.
|
||||
* @param {Object} target
|
||||
* Event target object.
|
||||
* @param {String} type
|
||||
* The type of event.
|
||||
* @params {Object|Number|String|Boolean} args
|
||||
* Arguments that will be passed to listeners.
|
||||
*/
|
||||
function emit (target, type, ...args) {
|
||||
emitOnObject(target, type, target, ...args);
|
||||
}
|
||||
// exports.emit = emit;
|
||||
|
||||
/**
|
||||
* A variant of emit that allows setting the this property for event listeners
|
||||
*/
|
||||
function emitOnObject(target, type, thisArg, ...args) {
|
||||
let allListeners = observers.get(target);
|
||||
let listeners = allListeners.get(type);
|
||||
|
||||
// If error event and there are no handlers (explicit or catch-all)
|
||||
// then print error message to the console.
|
||||
if (type === 'error' && !listeners.size && !allListeners.get('*').size)
|
||||
console.exception(args[0]);
|
||||
|
||||
let count = listenerCount;
|
||||
for (let [listener, added] of listeners)
|
||||
try {
|
||||
// Since our contract unfortunately requires that we not dispatch to
|
||||
// this event to listeners that were either added or removed during this
|
||||
// dispatch, we need to check when each listener was added.
|
||||
if (added >= count)
|
||||
break;
|
||||
listener.apply(thisArg, args);
|
||||
}
|
||||
catch (error) {
|
||||
// If exception is not thrown by a error listener and error listener is
|
||||
// registered emit `error` event. Otherwise dump exception to the console.
|
||||
if (type !== 'error')
|
||||
emitOnObject(target, 'error', target, error);
|
||||
else
|
||||
console.exception(error);
|
||||
}
|
||||
|
||||
// Also emit on `"*"` so that one could listen for all events.
|
||||
if (type !== '*' && allListeners.get('*').size)
|
||||
emitOnObject(target, '*', target, type, ...args);
|
||||
}
|
||||
// exports.emitOnObject = emitOnObject;
|
||||
|
||||
/**
|
||||
* Removes an event `listener` for the given event `type` on the given event
|
||||
* `target`. If no `listener` is passed removes all listeners of the given
|
||||
* `type`. If `type` is not passed removes all the listeners of the given
|
||||
* event `target`.
|
||||
* @param {Object} target
|
||||
* The event target object.
|
||||
* @param {String} type
|
||||
* The type of event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
*/
|
||||
function off(target, type, listener) {
|
||||
let length = arguments.length;
|
||||
if (length === 3) {
|
||||
if (onceWeakMap.has(listener)) {
|
||||
observers.get(target).get(type)
|
||||
.delete(onceWeakMap.get(listener));
|
||||
onceWeakMap.delete(listener);
|
||||
}
|
||||
|
||||
observers.get(target).get(type).delete(listener);
|
||||
}
|
||||
else if (length === 2) {
|
||||
observers.get(target).get(type).clear();
|
||||
observers.get(target).delete(type);
|
||||
}
|
||||
else if (length === 1) {
|
||||
for (let listeners of observers.get(target).values())
|
||||
listeners.clear();
|
||||
observers.delete(target);
|
||||
}
|
||||
}
|
||||
// exports.off = off;
|
||||
|
||||
/**
|
||||
* Returns a number of event listeners registered for the given event `type`
|
||||
* on the given event `target`.
|
||||
*/
|
||||
function count(target, type) {
|
||||
return observers.get(target).get(type).size;
|
||||
}
|
||||
// exports.count = count;
|
||||
|
||||
/**
|
||||
* Registers listeners on the given event `target` from the given `listeners`
|
||||
* dictionary. Iterates over the listeners and if property name matches name
|
||||
* pattern `onEventType` and property is a function, then registers it as
|
||||
* an `eventType` listener on `target`.
|
||||
*
|
||||
* @param {Object} target
|
||||
* The type of event.
|
||||
* @param {Object} listeners
|
||||
* Dictionary of listeners.
|
||||
*/
|
||||
function setListeners(target, listeners) {
|
||||
Object.keys(listeners || {}).forEach(key => {
|
||||
let match = EVENT_TYPE_PATTERN.exec(key);
|
||||
let type = match && match[1].toLowerCase();
|
||||
if (!type)
|
||||
return;
|
||||
|
||||
let listener = listeners[key];
|
||||
if (typeof(listener) === 'function')
|
||||
on(target, type, listener);
|
||||
});
|
||||
}
|
||||
// exports.setListeners = setListeners;
|
||||
@@ -1,204 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
'use strict';
|
||||
|
||||
var getPrototypeOf = Object.getPrototypeOf;
|
||||
function* getNames(x) {
|
||||
yield* Object.getOwnPropertyNames(x);
|
||||
yield* Object.getOwnPropertySymbols(x);
|
||||
}
|
||||
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
|
||||
var freeze = Object.freeze;
|
||||
|
||||
// This shortcut makes sure that we do perform desired operations, even if
|
||||
// associated methods have being overridden on the used object.
|
||||
var hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
|
||||
|
||||
// Utility function to get own properties descriptor map.
|
||||
function getOwnPropertyDescriptors(...objects) {
|
||||
let descriptors = {};
|
||||
for (let object of objects)
|
||||
for (let name of getNames(object))
|
||||
descriptors[name] = getOwnPropertyDescriptor(object, name);
|
||||
return descriptors;
|
||||
}
|
||||
|
||||
function isDataProperty(property) {
|
||||
var type = typeof(property.value);
|
||||
return "value" in property &&
|
||||
type !== "function" &&
|
||||
(type !== "object" || property.value === null);
|
||||
}
|
||||
|
||||
function getDataProperties(object) {
|
||||
var properties = getOwnPropertyDescriptors(object);
|
||||
let result = {};
|
||||
for (let name of getNames(properties)) {
|
||||
var property = properties[name];
|
||||
if (isDataProperty(property)) {
|
||||
result[name] = {
|
||||
value: property.value,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
enumerable: false
|
||||
};
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes `source` object as an argument and returns identical object
|
||||
* with the difference that all own properties will be non-enumerable
|
||||
*/
|
||||
function obscure(source, prototype = getPrototypeOf(source)) {
|
||||
let descriptors = {};
|
||||
for (let name of getNames(source)) {
|
||||
let property = getOwnPropertyDescriptor(source, name);
|
||||
property.enumerable = false;
|
||||
descriptors[name] = property;
|
||||
}
|
||||
return Object.create(prototype, descriptors);
|
||||
}
|
||||
// exports.obscure = obscure;
|
||||
|
||||
/**
|
||||
* Takes arbitrary number of source objects and returns fresh one, that
|
||||
* inherits from the same prototype as a first argument and implements all
|
||||
* own properties of all argument objects. If two or more argument objects
|
||||
* have own properties with the same name, the property is overridden, with
|
||||
* precedence from right to left, implying, that properties of the object on
|
||||
* the left are overridden by a same named property of the object on the right.
|
||||
*/
|
||||
var mix = function(...sources) {
|
||||
return Object.create(getPrototypeOf(sources[0]),
|
||||
getOwnPropertyDescriptors(...sources));
|
||||
};
|
||||
// exports.mix = mix;
|
||||
|
||||
/**
|
||||
* Returns a frozen object with that inherits from the given `prototype` and
|
||||
* implements all own properties of the given `properties` object.
|
||||
*/
|
||||
function extend(prototype, properties) {
|
||||
return Object.create(prototype,
|
||||
getOwnPropertyDescriptors(properties));
|
||||
}
|
||||
// exports.extend = extend;
|
||||
|
||||
function prototypeOf(input) {
|
||||
return typeof(input) === 'function' ? input.prototype : input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a constructor function with a proper `prototype` setup. Returned
|
||||
* constructor's `prototype` inherits from a given `options.extends` or
|
||||
* `Class.prototype` if omitted and implements all the properties of the
|
||||
* given `option`. If `options.implemens` array is passed, it's elements
|
||||
* will be mixed into prototype as well. Also, `options.extends` can be
|
||||
* a function or a prototype. If function than it's prototype is used as
|
||||
* an ancestor of the prototype, if it's an object that it's used directly.
|
||||
* Also `options.implements` may contain functions or objects, in case of
|
||||
* functions their prototypes are used for mixing.
|
||||
*/
|
||||
function Class(options) {
|
||||
// Create descriptor with normalized `options.extends` and
|
||||
// `options.implements`.
|
||||
var descriptor = {
|
||||
// Normalize extends property of `options.extends` to a prototype object
|
||||
// in case it's constructor. If property is missing that fallback to
|
||||
// `Type.prototype`.
|
||||
extends: hasOwnProperty(options, 'extends') ?
|
||||
prototypeOf(options.extends) : Class.prototype,
|
||||
|
||||
// Normalize `options.implements` to make sure that it's array of
|
||||
// prototype objects instead of constructor functions.
|
||||
implements: freeze(hasOwnProperty(options, 'implements') ?
|
||||
options.implements.map(prototypeOf) : []),
|
||||
};
|
||||
|
||||
// Create array of property descriptors who's properties will be defined
|
||||
// on the resulting prototype.
|
||||
var descriptors = [].concat(descriptor.implements, options, descriptor,
|
||||
{ constructor });
|
||||
|
||||
// Note: we use reflection `apply` in the constructor instead of method
|
||||
// call since later may be overridden.
|
||||
function constructor() {
|
||||
var instance = Object.create(prototype, attributes);
|
||||
if (initialize)
|
||||
Reflect.apply(initialize, instance, arguments);
|
||||
return instance;
|
||||
}
|
||||
// Create `prototype` that inherits from given ancestor passed as
|
||||
// `options.extends`, falling back to `Type.prototype`, implementing all
|
||||
// properties of given `options.implements` and `options` itself.
|
||||
var prototype = Object.create(descriptor.extends,
|
||||
getOwnPropertyDescriptors(...descriptors));
|
||||
var initialize = prototype.initialize;
|
||||
|
||||
// Combine ancestor attributes with prototype's attributes so that
|
||||
// ancestors attributes also become initializeable.
|
||||
var attributes = mix(descriptor.extends.constructor.attributes || {},
|
||||
getDataProperties(prototype));
|
||||
|
||||
constructor.attributes = attributes;
|
||||
Object.defineProperty(constructor, 'prototype', {
|
||||
configurable: false,
|
||||
writable: false,
|
||||
value: prototype
|
||||
});
|
||||
return constructor;
|
||||
}
|
||||
Class.prototype = obscure({
|
||||
constructor: function constructor() {
|
||||
this.initialize.apply(this, arguments);
|
||||
return this;
|
||||
},
|
||||
initialize: function initialize() {
|
||||
// Do your initialization logic here
|
||||
},
|
||||
// Copy useful properties from `Object.prototype`.
|
||||
toString: Object.prototype.toString,
|
||||
toLocaleString: Object.prototype.toLocaleString,
|
||||
toSource: Object.prototype.toSource,
|
||||
valueOf: Object.prototype.valueOf,
|
||||
isPrototypeOf: Object.prototype.isPrototypeOf
|
||||
}, null);
|
||||
|
||||
// From sdk/land/functional/helpers.js
|
||||
|
||||
const arity = f => f.arity || f.length;
|
||||
const name = f => f.displayName || f.name;
|
||||
const derive = (f, source) => {
|
||||
f.displayName = name(source);
|
||||
f.arity = arity(source);
|
||||
return f;
|
||||
};
|
||||
|
||||
// From sdk/land/functional/core.js
|
||||
|
||||
/**
|
||||
* Takes variadic numeber of functions and returns composed one.
|
||||
* Returned function pushes `this` pseudo-variable to the head
|
||||
* of the passed arguments and invokes all the functions from
|
||||
* left to right passing same arguments to them. Composite function
|
||||
* returns return value of the right most funciton.
|
||||
*/
|
||||
const _method = (...lambdas) => {
|
||||
return function method(...args) {
|
||||
args.unshift(this);
|
||||
return lambdas.reduce((_, lambda) => lambda.apply(this, args),
|
||||
void(0));
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* Takes a funtion and returns a wrapped function that returns `this`
|
||||
*/
|
||||
const chainable = f => derive(function(...args) {
|
||||
f.apply(this, args);
|
||||
return this;
|
||||
}, f);
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
"use strict";
|
||||
|
||||
// Create a shortcut for Array.prototype.slice.call().
|
||||
const unbind = Function.call.bind(Function.bind, Function.call);
|
||||
const slice = unbind(Array.prototype.slice);
|
||||
|
||||
class DefaultWeakMap extends WeakMap {
|
||||
constructor(createItem, items = undefined) {
|
||||
super(items);
|
||||
|
||||
this.createItem = createItem;
|
||||
}
|
||||
|
||||
get(key) {
|
||||
if (!this.has(key)) {
|
||||
this.set(key, this.createItem(key));
|
||||
}
|
||||
|
||||
return super.get(key);
|
||||
}
|
||||
}
|
||||
|
||||
class DefaultMap extends Map {
|
||||
constructor(createItem, items = undefined) {
|
||||
super(items);
|
||||
|
||||
this.createItem = createItem;
|
||||
}
|
||||
|
||||
get(key) {
|
||||
if (!this.has(key)) {
|
||||
this.set(key, this.createItem(key));
|
||||
}
|
||||
|
||||
return super.get(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Object.assign(exports, {DefaultMap, DefaultWeakMap});
|
||||
|
||||
/**
|
||||
* Merges all the properties of all arguments into first argument. If two or
|
||||
* more argument objects have own properties with the same name, the property
|
||||
* is overridden, with precedence from right to left, implying, that properties
|
||||
* of the object on the left are overridden by a same named property of the
|
||||
* object on the right.
|
||||
*
|
||||
* Any argument given with "falsy" value - commonly `null` and `undefined` in
|
||||
* case of objects - are skipped.
|
||||
*
|
||||
* @examples
|
||||
* var a = { bar: 0, a: 'a' }
|
||||
* var b = merge(a, { foo: 'foo', bar: 1 }, { foo: 'bar', name: 'b' });
|
||||
* b === a // true
|
||||
* b.a // 'a'
|
||||
* b.foo // 'bar'
|
||||
* b.bar // 1
|
||||
* b.name // 'b'
|
||||
*/
|
||||
function merge(source) {
|
||||
let descriptor = {};
|
||||
|
||||
// `Boolean` converts the first parameter to a boolean value. Any object is
|
||||
// converted to `true` where `null` and `undefined` becames `false`. Therefore
|
||||
// the `filter` method will keep only objects that are defined and not null.
|
||||
slice(arguments, 1).filter(Boolean).forEach(function onEach(properties) {
|
||||
getOwnPropertyIdentifiers(properties).forEach(function(name) {
|
||||
descriptor[name] = Object.getOwnPropertyDescriptor(properties, name);
|
||||
});
|
||||
});
|
||||
return Object.defineProperties(source, descriptor);
|
||||
}
|
||||
// exports.merge = merge;
|
||||
|
||||
/**
|
||||
* Returns an object that inherits from the first argument and contains all the
|
||||
* properties from all following arguments.
|
||||
* `extend(source1, source2, source3)` is equivalent of
|
||||
* `merge(Object.create(source1), source2, source3)`.
|
||||
*/
|
||||
function extend(source) {
|
||||
let rest = slice(arguments, 1);
|
||||
rest.unshift(Object.create(source));
|
||||
return merge.apply(null, rest);
|
||||
}
|
||||
// exports.extend = extend;
|
||||
|
||||
function has(obj, key) {
|
||||
return obj.hasOwnProperty(key);
|
||||
}
|
||||
// exports.has = has;
|
||||
|
||||
function each(obj, fn) {
|
||||
for (let key in obj) has(obj, key) && fn(obj[key], key, obj);
|
||||
}
|
||||
// exports.each = each;
|
||||
|
||||
/**
|
||||
* Like `merge`, except no property descriptors are manipulated, for use
|
||||
* with platform objects. Identical to underscore's `extend`. Useful for
|
||||
* merging XPCOM objects
|
||||
*/
|
||||
function safeMerge(source) {
|
||||
slice(arguments, 1).forEach(function onEach (obj) {
|
||||
for (let prop in obj) source[prop] = obj[prop];
|
||||
});
|
||||
return source;
|
||||
}
|
||||
// exports.safeMerge = safeMerge;
|
||||
|
||||
/*
|
||||
* Returns a copy of the object without omitted properties
|
||||
*/
|
||||
function omit(source, ...values) {
|
||||
let copy = {};
|
||||
let keys = flatten(values);
|
||||
for (let prop in source)
|
||||
if (!~keys.indexOf(prop))
|
||||
copy[prop] = source[prop];
|
||||
return copy;
|
||||
}
|
||||
// exports.omit = omit;
|
||||
|
||||
// get object's own property Symbols and/or Names, including nonEnumerables by default
|
||||
function getOwnPropertyIdentifiers(object, options = { names: true, symbols: true, nonEnumerables: true }) {
|
||||
const symbols = !options.symbols ? [] :
|
||||
Object.getOwnPropertySymbols(object);
|
||||
const names = !options.names ? [] :
|
||||
options.nonEnumerables ? Object.getOwnPropertyNames(object) :
|
||||
Object.keys(object);
|
||||
return [...names, ...symbols];
|
||||
}
|
||||
// exports.getOwnPropertyIdentifiers = getOwnPropertyIdentifiers;
|
||||
@@ -1,60 +0,0 @@
|
||||
/**
|
||||
* `EventTarget` is an exemplar for creating an objects that can be used to
|
||||
* add / remove event listeners on them. Events on these objects may be emitted
|
||||
* via `emit` function exported by 'event/core' module.
|
||||
*/
|
||||
const EventTarget = Class({
|
||||
/**
|
||||
* Method initializes `this` event source. It goes through properties of a
|
||||
* given `options` and registers listeners for the ones that look like an
|
||||
* event listeners.
|
||||
*/
|
||||
/**
|
||||
* Method initializes `this` event source. It goes through properties of a
|
||||
* given `options` and registers listeners for the ones that look like an
|
||||
* event listeners.
|
||||
*/
|
||||
initialize: function initialize(options) {
|
||||
setListeners(this, options);
|
||||
},
|
||||
/**
|
||||
* Registers an event `listener` that is called every time events of
|
||||
* specified `type` are emitted.
|
||||
* @param {String} type
|
||||
* The type of event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
* @example
|
||||
* worker.on('message', function (data) {
|
||||
* console.log('data received: ' + data)
|
||||
* })
|
||||
*/
|
||||
on: chainable(_method(on)),
|
||||
/**
|
||||
* Registers an event `listener` that is called once the next time an event
|
||||
* of the specified `type` is emitted.
|
||||
* @param {String} type
|
||||
* The type of the event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
*/
|
||||
once: chainable(_method(once)),
|
||||
/**
|
||||
* Removes an event `listener` for the given event `type`.
|
||||
* @param {String} type
|
||||
* The type of event.
|
||||
* @param {Function} listener
|
||||
* The listener function that processes the event.
|
||||
*/
|
||||
removeListener: function removeListener(type, listener) {
|
||||
// Note: We can't just wrap `off` in `method` as we do it for other methods
|
||||
// cause skipping a second or third argument will behave very differently
|
||||
// than intended. This way we make sure all arguments are passed and only
|
||||
// one listener is removed at most.
|
||||
off(this, type, listener);
|
||||
return this;
|
||||
},
|
||||
// but we can wrap `off` here, as the semantics are the same
|
||||
off: chainable(_method(off))
|
||||
|
||||
});
|
||||
@@ -1,921 +0,0 @@
|
||||
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
|
||||
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// TODO: Get rid of this code once the marionette server loads transport.js as
|
||||
// an SDK module (see bug 1000814)
|
||||
// (function (factory) { // Module boilerplate
|
||||
// if (this.module && module.id.indexOf("transport") >= 0) { // require
|
||||
// factory.call(this, require, exports);
|
||||
// } else {// loadSubScript
|
||||
// if (this.require) {
|
||||
// factory.call(this, require, this);
|
||||
// } else {
|
||||
// const Cu = Components.utils;
|
||||
// const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
|
||||
// factory.call(this, require, this);
|
||||
// }
|
||||
// }
|
||||
// }).call(this, function (require, exports) {
|
||||
|
||||
"use strict";
|
||||
|
||||
// const { Cc, Cr, CC } = require("chrome");
|
||||
// const DevToolsUtils = require("devtools/shared/DevToolsUtils");
|
||||
// const { dumpn, dumpv } = DevToolsUtils;
|
||||
// const flags = require("devtools/shared/flags");
|
||||
// const StreamUtils = require("devtools/shared/transport/stream-utils");
|
||||
// const { Packet, JSONPacket, BulkPacket } =
|
||||
// require("devtools/shared/transport/packets");
|
||||
// const promise = require("promise");
|
||||
// const defer = require("devtools/shared/defer");
|
||||
// const EventEmitter = require("devtools/shared/event-emitter");
|
||||
|
||||
// DevToolsUtils.defineLazyGetter(this, "Pipe", () => {
|
||||
// return CC("@mozilla.org/pipe;1", "nsIPipe", "init");
|
||||
// });
|
||||
|
||||
// DevToolsUtils.defineLazyGetter(this, "ScriptableInputStream", () => {
|
||||
// return CC("@mozilla.org/scriptableinputstream;1",
|
||||
// "nsIScriptableInputStream", "init");
|
||||
// });
|
||||
|
||||
const PACKET_HEADER_MAX = 200;
|
||||
|
||||
/**
|
||||
* An adapter that handles data transfers between the debugger client and
|
||||
* server. It can work with both nsIPipe and nsIServerSocket transports so
|
||||
* long as the properly created input and output streams are specified.
|
||||
* (However, for intra-process connections, LocalDebuggerTransport, below,
|
||||
* is more efficient than using an nsIPipe pair with DebuggerTransport.)
|
||||
*
|
||||
* @param input nsIAsyncInputStream
|
||||
* The input stream.
|
||||
* @param output nsIAsyncOutputStream
|
||||
* The output stream.
|
||||
*
|
||||
* Given a DebuggerTransport instance dt:
|
||||
* 1) Set dt.hooks to a packet handler object (described below).
|
||||
* 2) Call dt.ready() to begin watching for input packets.
|
||||
* 3) Call dt.send() / dt.startBulkSend() to send packets.
|
||||
* 4) Call dt.close() to close the connection, and disengage from the event
|
||||
* loop.
|
||||
*
|
||||
* A packet handler is an object with the following methods:
|
||||
*
|
||||
* - onPacket(packet) - called when we have received a complete packet.
|
||||
* |packet| is the parsed form of the packet --- a JavaScript value, not
|
||||
* a JSON-syntax string.
|
||||
*
|
||||
* - onBulkPacket(packet) - called when we have switched to bulk packet
|
||||
* receiving mode. |packet| is an object containing:
|
||||
* * actor: Name of actor that will receive the packet
|
||||
* * type: Name of actor's method that should be called on receipt
|
||||
* * length: Size of the data to be read
|
||||
* * stream: This input stream should only be used directly if you can ensure
|
||||
* that you will read exactly |length| bytes and will not close the
|
||||
* stream when reading is complete
|
||||
* * done: If you use the stream directly (instead of |copyTo| below), you
|
||||
* must signal completion by resolving / rejecting this deferred.
|
||||
* If it's rejected, the transport will be closed. If an Error is
|
||||
* supplied as a rejection value, it will be logged via |dumpn|.
|
||||
* If you do use |copyTo|, resolving is taken care of for you when
|
||||
* copying completes.
|
||||
* * copyTo: A helper function for getting your data out of the stream that
|
||||
* meets the stream handling requirements above, and has the
|
||||
* following signature:
|
||||
* @param output nsIAsyncOutputStream
|
||||
* The stream to copy to.
|
||||
* @return Promise
|
||||
* The promise is resolved when copying completes or rejected if any
|
||||
* (unexpected) errors occur.
|
||||
* This object also emits "progress" events for each chunk that is
|
||||
* copied. See stream-utils.js.
|
||||
*
|
||||
* - onClosed(reason) - called when the connection is closed. |reason| is
|
||||
* an optional nsresult or object, typically passed when the transport is
|
||||
* closed due to some error in a underlying stream.
|
||||
*
|
||||
* See ./packets.js and the Remote Debugging Protocol specification for more
|
||||
* details on the format of these packets.
|
||||
*/
|
||||
function DebuggerTransport(input, output) {
|
||||
// EventEmitter.decorate(this);
|
||||
|
||||
this._input = input;
|
||||
// this._scriptableInput = new ScriptableInputStream(input);
|
||||
this._output = output;
|
||||
|
||||
// The current incoming (possibly partial) header, which will determine which
|
||||
// type of Packet |_incoming| below will become.
|
||||
this._incomingHeader = "";
|
||||
// The current incoming Packet object
|
||||
// this._incoming = null;
|
||||
this._incoming = "";
|
||||
// A queue of outgoing Packet objects
|
||||
// this._outgoing = [];
|
||||
this._outgoing = "";
|
||||
|
||||
this.hooks = null;
|
||||
this.active = false;
|
||||
|
||||
this._incomingEnabled = true;
|
||||
this._outgoingEnabled = true;
|
||||
|
||||
this.close = this.close.bind(this);
|
||||
}
|
||||
|
||||
DebuggerTransport.prototype = {
|
||||
/**
|
||||
* Transmit an object as a JSON packet.
|
||||
*
|
||||
* This method returns immediately, without waiting for the entire
|
||||
* packet to be transmitted, registering event handlers as needed to
|
||||
* transmit the entire packet. Packets are transmitted in the order
|
||||
* they are passed to this method.
|
||||
*/
|
||||
send: function (object) {
|
||||
// this.emit("send", object);
|
||||
|
||||
// let packet = new JSONPacket(this);
|
||||
// packet.object = object;
|
||||
// this._outgoing.push(packet);
|
||||
|
||||
let data = JSON.stringify(object);
|
||||
let data_for_len = DevToolsUtils.utf16to8(data);
|
||||
this._outgoing = data_for_len.length + ':' + data;
|
||||
// log("<<<<<<<<<< " + this._outgoing);
|
||||
this._flushOutgoing();
|
||||
},
|
||||
|
||||
/**
|
||||
* Transmit streaming data via a bulk packet.
|
||||
*
|
||||
* This method initiates the bulk send process by queuing up the header data.
|
||||
* The caller receives eventual access to a stream for writing.
|
||||
*
|
||||
* N.B.: Do *not* attempt to close the stream handed to you, as it will
|
||||
* continue to be used by this transport afterwards. Most users should
|
||||
* instead use the provided |copyFrom| function instead.
|
||||
*
|
||||
* @param header Object
|
||||
* This is modeled after the format of JSON packets above, but does not
|
||||
* actually contain the data, but is instead just a routing header:
|
||||
* * actor: Name of actor that will receive the packet
|
||||
* * type: Name of actor's method that should be called on receipt
|
||||
* * length: Size of the data to be sent
|
||||
* @return Promise
|
||||
* The promise will be resolved when you are allowed to write to the
|
||||
* stream with an object containing:
|
||||
* * stream: This output stream should only be used directly if
|
||||
* you can ensure that you will write exactly |length|
|
||||
* bytes and will not close the stream when writing is
|
||||
* complete
|
||||
* * done: If you use the stream directly (instead of |copyFrom|
|
||||
* below), you must signal completion by resolving /
|
||||
* rejecting this deferred. If it's rejected, the
|
||||
* transport will be closed. If an Error is supplied as
|
||||
* a rejection value, it will be logged via |dumpn|. If
|
||||
* you do use |copyFrom|, resolving is taken care of for
|
||||
* you when copying completes.
|
||||
* * copyFrom: A helper function for getting your data onto the
|
||||
* stream that meets the stream handling requirements
|
||||
* above, and has the following signature:
|
||||
* @param input nsIAsyncInputStream
|
||||
* The stream to copy from.
|
||||
* @return Promise
|
||||
* The promise is resolved when copying completes or
|
||||
* rejected if any (unexpected) errors occur.
|
||||
* This object also emits "progress" events for each chunk
|
||||
* that is copied. See stream-utils.js.
|
||||
*/
|
||||
startBulkSend: function (header) {
|
||||
this.emit("startbulksend", header);
|
||||
|
||||
let packet = new BulkPacket(this);
|
||||
packet.header = header;
|
||||
this._outgoing.push(packet);
|
||||
this._flushOutgoing();
|
||||
return packet.streamReadyForWriting;
|
||||
},
|
||||
|
||||
/**
|
||||
* Close the transport.
|
||||
* @param reason nsresult / object (optional)
|
||||
* The status code or error message that corresponds to the reason for
|
||||
* closing the transport (likely because a stream closed or failed).
|
||||
*/
|
||||
close: function (reason) {
|
||||
this.emit("close", reason);
|
||||
|
||||
this.active = false;
|
||||
this._input.close();
|
||||
this._scriptableInput.close();
|
||||
this._output.close();
|
||||
this._destroyIncoming();
|
||||
this._destroyAllOutgoing();
|
||||
if (this.hooks) {
|
||||
this.hooks.onClosed(reason);
|
||||
this.hooks = null;
|
||||
}
|
||||
if (reason) {
|
||||
dumpn("Transport closed: " + DevToolsUtils.safeErrorString(reason));
|
||||
} else {
|
||||
dumpn("Transport closed.");
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* The currently outgoing packet (at the top of the queue).
|
||||
*/
|
||||
get _currentOutgoing() {
|
||||
return this._outgoing[0];
|
||||
},
|
||||
|
||||
/**
|
||||
* Flush data to the outgoing stream. Waits until the output stream notifies
|
||||
* us that it is ready to be written to (via onOutputStreamReady).
|
||||
*/
|
||||
_flushOutgoing: function () {
|
||||
if (!this._outgoingEnabled || this._outgoing.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the top of the packet queue has nothing more to send, remove it.
|
||||
if (this._currentOutgoing.done) {
|
||||
this._finishCurrentOutgoing();
|
||||
}
|
||||
|
||||
if (this._outgoing.length > 0) {
|
||||
// var threadManager = Cc["@mozilla.org/thread-manager;1"].getService();
|
||||
// this._output.asyncWait(this, 0, 0, threadManager.currentThread);
|
||||
// log('send: ' + this._outgoing);
|
||||
_bufferWrite(this._outgoing);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pause this transport's attempts to write to the output stream. This is
|
||||
* used when we've temporarily handed off our output stream for writing bulk
|
||||
* data.
|
||||
*/
|
||||
pauseOutgoing: function () {
|
||||
this._outgoingEnabled = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Resume this transport's attempts to write to the output stream.
|
||||
*/
|
||||
resumeOutgoing: function () {
|
||||
this._outgoingEnabled = true;
|
||||
this._flushOutgoing();
|
||||
},
|
||||
|
||||
// nsIOutputStreamCallback
|
||||
/**
|
||||
* This is called when the output stream is ready for more data to be written.
|
||||
* The current outgoing packet will attempt to write some amount of data, but
|
||||
* may not complete.
|
||||
*/
|
||||
onOutputStreamReady: DevToolsUtils.makeInfallible(function (stream) {
|
||||
if (!this._outgoingEnabled || this._outgoing.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this._currentOutgoing.write(stream);
|
||||
} catch (e) {
|
||||
if (e.result != Cr.NS_BASE_STREAM_WOULD_BLOCK) {
|
||||
this.close(e.result);
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
this._flushOutgoing();
|
||||
}, "DebuggerTransport.prototype.onOutputStreamReady"),
|
||||
|
||||
/**
|
||||
* Remove the current outgoing packet from the queue upon completion.
|
||||
*/
|
||||
_finishCurrentOutgoing: function () {
|
||||
if (this._currentOutgoing) {
|
||||
this._currentOutgoing.destroy();
|
||||
this._outgoing.shift();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear the entire outgoing queue.
|
||||
*/
|
||||
_destroyAllOutgoing: function () {
|
||||
for (let packet of this._outgoing) {
|
||||
packet.destroy();
|
||||
}
|
||||
this._outgoing = [];
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize the input stream for reading. Once this method has been called,
|
||||
* we watch for packets on the input stream, and pass them to the appropriate
|
||||
* handlers via this.hooks.
|
||||
*/
|
||||
ready: function () {
|
||||
this.active = true;
|
||||
this._waitForIncoming();
|
||||
},
|
||||
|
||||
/**
|
||||
* Asks the input stream to notify us (via onInputStreamReady) when it is
|
||||
* ready for reading.
|
||||
*/
|
||||
_waitForIncoming: function () {
|
||||
// if (this._incomingEnabled) {
|
||||
// let threadManager = Cc["@mozilla.org/thread-manager;1"].getService();
|
||||
// this._input.asyncWait(this, 0, 0, threadManager.currentThread);
|
||||
// }
|
||||
},
|
||||
|
||||
/**
|
||||
* Pause this transport's attempts to read from the input stream. This is
|
||||
* used when we've temporarily handed off our input stream for reading bulk
|
||||
* data.
|
||||
*/
|
||||
pauseIncoming: function () {
|
||||
this._incomingEnabled = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Resume this transport's attempts to read from the input stream.
|
||||
*/
|
||||
resumeIncoming: function () {
|
||||
this._incomingEnabled = true;
|
||||
this._flushIncoming();
|
||||
this._waitForIncoming();
|
||||
},
|
||||
|
||||
// nsIInputStreamCallback
|
||||
/**
|
||||
* Called when the stream is either readable or closed.
|
||||
*/
|
||||
onInputStreamReady: DevToolsUtils.makeInfallible(function (stream) {
|
||||
try {
|
||||
while (stream.available() && this._incomingEnabled &&
|
||||
this._processIncoming(stream, stream.available())) {
|
||||
// Loop until there is nothing more to process
|
||||
}
|
||||
this._waitForIncoming();
|
||||
} catch (e) {
|
||||
if (e.result != Cr.NS_BASE_STREAM_WOULD_BLOCK) {
|
||||
this.close(e.result);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}, "DebuggerTransport.prototype.onInputStreamReady"),
|
||||
|
||||
/**
|
||||
* Process the incoming data. Will create a new currently incoming Packet if
|
||||
* needed. Tells the incoming Packet to read as much data as it can, but
|
||||
* reading may not complete. The Packet signals that its data is ready for
|
||||
* delivery by calling one of this transport's _on*Ready methods (see
|
||||
* ./packets.js and the _on*Ready methods below).
|
||||
* @return boolean
|
||||
* Whether incoming stream processing should continue for any
|
||||
* remaining data.
|
||||
*/
|
||||
_processIncoming: function (stream, count) {
|
||||
dumpv("Data available: " + count);
|
||||
|
||||
if (!count) {
|
||||
dumpv("Nothing to read, skipping");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!this._incoming) {
|
||||
dumpv("Creating a new packet from incoming");
|
||||
|
||||
if (!this._readHeader(stream)) {
|
||||
// Not enough data to read packet type
|
||||
return false;
|
||||
}
|
||||
|
||||
// Attempt to create a new Packet by trying to parse each possible
|
||||
// header pattern.
|
||||
this._incoming = Packet.fromHeader(this._incomingHeader, this);
|
||||
if (!this._incoming) {
|
||||
throw new Error("No packet types for header: " +
|
||||
this._incomingHeader);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this._incoming.done) {
|
||||
// We have an incomplete packet, keep reading it.
|
||||
dumpv("Existing packet incomplete, keep reading");
|
||||
this._incoming.read(stream, this._scriptableInput);
|
||||
}
|
||||
} catch (e) {
|
||||
let msg = "Error reading incoming packet: (" + e + " - " + e.stack + ")";
|
||||
dumpn(msg);
|
||||
|
||||
// Now in an invalid state, shut down the transport.
|
||||
this.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this._incoming.done) {
|
||||
// Still not complete, we'll wait for more data.
|
||||
dumpv("Packet not done, wait for more");
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ready for next packet
|
||||
this._flushIncoming();
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Read as far as we can into the incoming data, attempting to build up a
|
||||
* complete packet header (which terminates with ":"). We'll only read up to
|
||||
* PACKET_HEADER_MAX characters.
|
||||
* @return boolean
|
||||
* True if we now have a complete header.
|
||||
*/
|
||||
_readHeader: function () {
|
||||
let amountToRead = PACKET_HEADER_MAX - this._incomingHeader.length;
|
||||
this._incomingHeader +=
|
||||
StreamUtils.delimitedRead(this._scriptableInput, ":", amountToRead);
|
||||
if (dumpv.wantVerbose) {
|
||||
dumpv("Header read: " + this._incomingHeader);
|
||||
}
|
||||
|
||||
if (this._incomingHeader.endsWith(":")) {
|
||||
if (dumpv.wantVerbose) {
|
||||
dumpv("Found packet header successfully: " + this._incomingHeader);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this._incomingHeader.length >= PACKET_HEADER_MAX) {
|
||||
throw new Error("Failed to parse packet header!");
|
||||
}
|
||||
|
||||
// Not enough data yet.
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* If the incoming packet is done, log it as needed and clear the buffer.
|
||||
*/
|
||||
_flushIncoming: function() {
|
||||
if (!this._incoming.done) {
|
||||
return;
|
||||
}
|
||||
if (dumpn.wantLogging) {
|
||||
dumpn("Got: " + this._incoming);
|
||||
}
|
||||
this._destroyIncoming();
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler triggered by an incoming JSONPacket completing it's |read| method.
|
||||
* Delivers the packet to this.hooks.onPacket.
|
||||
*/
|
||||
_onJSONObjectReady: function (object) {
|
||||
DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => {
|
||||
// Ensure the transport is still alive by the time this runs.
|
||||
if (this.active) {
|
||||
this.emit("packet", object);
|
||||
this.hooks.onPacket(object);
|
||||
}
|
||||
}, "DebuggerTransport instance's this.hooks.onPacket"));
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler triggered by an incoming BulkPacket entering the |read| phase for
|
||||
* the stream portion of the packet. Delivers info about the incoming
|
||||
* streaming data to this.hooks.onBulkPacket. See the main comment on the
|
||||
* transport at the top of this file for more details.
|
||||
*/
|
||||
_onBulkReadReady: function (...args) {
|
||||
DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => {
|
||||
// Ensure the transport is still alive by the time this runs.
|
||||
if (this.active) {
|
||||
this.emit("bulkpacket", ...args);
|
||||
this.hooks.onBulkPacket(...args);
|
||||
}
|
||||
}, "DebuggerTransport instance's this.hooks.onBulkPacket"));
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all handlers and references related to the current incoming packet,
|
||||
* either because it is now complete or because the transport is closing.
|
||||
*/
|
||||
_destroyIncoming: function () {
|
||||
if (this._incoming) {
|
||||
this._incoming.destroy();
|
||||
}
|
||||
this._incomingHeader = "";
|
||||
this._incoming = null;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// exports.DebuggerTransport = DebuggerTransport;
|
||||
|
||||
/**
|
||||
* An adapter that handles data transfers between the debugger client and
|
||||
* server when they both run in the same process. It presents the same API as
|
||||
* DebuggerTransport, but instead of transmitting serialized messages across a
|
||||
* connection it merely calls the packet dispatcher of the other side.
|
||||
*
|
||||
* @param other LocalDebuggerTransport
|
||||
* The other endpoint for this debugger connection.
|
||||
*
|
||||
* @see DebuggerTransport
|
||||
*/
|
||||
function LocalDebuggerTransport(other) {
|
||||
// EventEmitter.decorate(this);
|
||||
|
||||
this.other = other;
|
||||
this.hooks = null;
|
||||
|
||||
// A packet number, shared between this and this.other. This isn't used by the
|
||||
// protocol at all, but it makes the packet traces a lot easier to follow.
|
||||
this._serial = this.other ? this.other._serial : { count: 0 };
|
||||
this.close = this.close.bind(this);
|
||||
}
|
||||
|
||||
LocalDebuggerTransport.prototype = {
|
||||
/**
|
||||
* Transmit a message by directly calling the onPacket handler of the other
|
||||
* endpoint.
|
||||
*/
|
||||
send: function (packet) {
|
||||
// this.emit("send", packet);
|
||||
|
||||
let serial = this._serial.count++;
|
||||
// if (dumpn.wantLogging) {
|
||||
// /* Check 'from' first, as 'echo' packets have both. */
|
||||
// if (packet.from) {
|
||||
// dumpn("Packet " + serial + " sent from " + uneval(packet.from));
|
||||
// } else if (packet.to) {
|
||||
// dumpn("Packet " + serial + " sent to " + uneval(packet.to));
|
||||
// }
|
||||
// }
|
||||
this._deepFreeze(packet);
|
||||
let other = this.other;
|
||||
if (other && other.hooks) {
|
||||
log("Received packet " + serial + ": " + JSON.stringify(packet, null, 2));
|
||||
other.hooks.onPacket(packet);
|
||||
}
|
||||
// if (other) {
|
||||
// DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => {
|
||||
// // Avoid the cost of JSON.stringify() when logging is disabled.
|
||||
// if (dumpn.wantLogging) {
|
||||
// dumpn("Received packet " + serial + ": " + JSON.stringify(packet, null, 2));
|
||||
// }
|
||||
// if (other.hooks) {
|
||||
// other.emit("onPacket", packet);
|
||||
// other.hooks.onPacket(packet);
|
||||
// }
|
||||
// }, "LocalDebuggerTransport instance's this.other.hooks.onPacket"));
|
||||
// }
|
||||
},
|
||||
|
||||
/**
|
||||
* Send a streaming bulk packet directly to the onBulkPacket handler of the
|
||||
* other endpoint.
|
||||
*
|
||||
* This case is much simpler than the full DebuggerTransport, since there is
|
||||
* no primary stream we have to worry about managing while we hand it off to
|
||||
* others temporarily. Instead, we can just make a single use pipe and be
|
||||
* done with it.
|
||||
*/
|
||||
startBulkSend: function ({actor, type, length}) {
|
||||
this.emit("startbulksend", {actor, type, length});
|
||||
|
||||
let serial = this._serial.count++;
|
||||
|
||||
dumpn("Sent bulk packet " + serial + " for actor " + actor);
|
||||
if (!this.other) {
|
||||
let error = new Error("startBulkSend: other side of transport missing");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
let pipe = new Pipe(true, true, 0, 0, null);
|
||||
|
||||
DevToolsUtils.executeSoon(DevToolsUtils.makeInfallible(() => {
|
||||
dumpn("Received bulk packet " + serial);
|
||||
if (!this.other.hooks) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Receiver
|
||||
let deferred = Promise.defer();
|
||||
let packet = {
|
||||
actor: actor,
|
||||
type: type,
|
||||
length: length,
|
||||
copyTo: (output) => {
|
||||
let copying =
|
||||
StreamUtils.copyStream(pipe.inputStream, output, length);
|
||||
deferred.resolve(copying);
|
||||
return copying;
|
||||
},
|
||||
stream: pipe.inputStream,
|
||||
done: deferred
|
||||
};
|
||||
|
||||
this.other.emit("bulkpacket", packet);
|
||||
this.other.hooks.onBulkPacket(packet);
|
||||
|
||||
// Await the result of reading from the stream
|
||||
deferred.promise.then(() => pipe.inputStream.close(), this.close);
|
||||
}, "LocalDebuggerTransport instance's this.other.hooks.onBulkPacket"));
|
||||
|
||||
// Sender
|
||||
let sendDeferred = Promise.defer();
|
||||
|
||||
// The remote transport is not capable of resolving immediately here, so we
|
||||
// shouldn't be able to either.
|
||||
DevToolsUtils.executeSoon(() => {
|
||||
let copyDeferred = Promise.defer();
|
||||
|
||||
sendDeferred.resolve({
|
||||
copyFrom: (input) => {
|
||||
let copying =
|
||||
StreamUtils.copyStream(input, pipe.outputStream, length);
|
||||
copyDeferred.resolve(copying);
|
||||
return copying;
|
||||
},
|
||||
stream: pipe.outputStream,
|
||||
done: copyDeferred
|
||||
});
|
||||
|
||||
// Await the result of writing to the stream
|
||||
copyDeferred.promise.then(() => pipe.outputStream.close(), this.close);
|
||||
});
|
||||
|
||||
return sendDeferred.promise;
|
||||
},
|
||||
|
||||
/**
|
||||
* Close the transport.
|
||||
*/
|
||||
close: function () {
|
||||
this.emit("close");
|
||||
|
||||
if (this.other) {
|
||||
// Remove the reference to the other endpoint before calling close(), to
|
||||
// avoid infinite recursion.
|
||||
let other = this.other;
|
||||
this.other = null;
|
||||
other.close();
|
||||
}
|
||||
if (this.hooks) {
|
||||
try {
|
||||
this.hooks.onClosed();
|
||||
} catch (ex) {
|
||||
console.error(ex);
|
||||
}
|
||||
this.hooks = null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* An empty method for emulating the DebuggerTransport API.
|
||||
*/
|
||||
ready: function () {},
|
||||
|
||||
/**
|
||||
* Helper function that makes an object fully immutable.
|
||||
*/
|
||||
_deepFreeze: function (object) {
|
||||
Object.freeze(object);
|
||||
for (let prop in object) {
|
||||
// Freeze the properties that are objects, not on the prototype, and not
|
||||
// already frozen. Note that this might leave an unfrozen reference
|
||||
// somewhere in the object if there is an already frozen object containing
|
||||
// an unfrozen object.
|
||||
if (object.hasOwnProperty(prop) && typeof object === "object" &&
|
||||
!Object.isFrozen(object)) {
|
||||
this._deepFreeze(object[prop]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// exports.LocalDebuggerTransport = LocalDebuggerTransport;
|
||||
|
||||
/**
|
||||
* A transport for the debugging protocol that uses nsIMessageManagers to
|
||||
* exchange packets with servers running in child processes.
|
||||
*
|
||||
* In the parent process, |mm| should be the nsIMessageSender for the
|
||||
* child process. In a child process, |mm| should be the child process
|
||||
* message manager, which sends packets to the parent.
|
||||
*
|
||||
* |prefix| is a string included in the message names, to distinguish
|
||||
* multiple servers running in the same child process.
|
||||
*
|
||||
* This transport exchanges messages named 'debug:<prefix>:packet', where
|
||||
* <prefix> is |prefix|, whose data is the protocol packet.
|
||||
*/
|
||||
// function ChildDebuggerTransport(mm, prefix) {
|
||||
// EventEmitter.decorate(this);
|
||||
|
||||
// this._mm = mm;
|
||||
// this._messageName = "debug:" + prefix + ":packet";
|
||||
// }
|
||||
|
||||
// /*
|
||||
// * To avoid confusion, we use 'message' to mean something that
|
||||
// * nsIMessageSender conveys, and 'packet' to mean a remote debugging
|
||||
// * protocol packet.
|
||||
// */
|
||||
// ChildDebuggerTransport.prototype = {
|
||||
// constructor: ChildDebuggerTransport,
|
||||
|
||||
// hooks: null,
|
||||
|
||||
// _addListener() {
|
||||
// this._mm.addMessageListener(this._messageName, this);
|
||||
// },
|
||||
|
||||
// _removeListener() {
|
||||
// try {
|
||||
// this._mm.removeMessageListener(this._messageName, this);
|
||||
// } catch (e) {
|
||||
// if (e.result != Cr.NS_ERROR_NULL_POINTER) {
|
||||
// throw e;
|
||||
// }
|
||||
// // In some cases, especially when using messageManagers in non-e10s mode, we reach
|
||||
// // this point with a dead messageManager which only throws errors but does not
|
||||
// // seem to indicate in any other way that it is dead.
|
||||
// }
|
||||
// },
|
||||
|
||||
// ready: function () {
|
||||
// this._addListener();
|
||||
// },
|
||||
|
||||
// close: function () {
|
||||
// this._removeListener();
|
||||
// this.emit("close");
|
||||
// this.hooks.onClosed();
|
||||
// },
|
||||
|
||||
// receiveMessage: function ({data}) {
|
||||
// this.emit("packet", data);
|
||||
// this.hooks.onPacket(data);
|
||||
// },
|
||||
|
||||
// send: function (packet) {
|
||||
// this.emit("send", packet);
|
||||
// try {
|
||||
// this._mm.sendAsyncMessage(this._messageName, packet);
|
||||
// } catch (e) {
|
||||
// if (e.result != Cr.NS_ERROR_NULL_POINTER) {
|
||||
// throw e;
|
||||
// }
|
||||
// // In some cases, especially when using messageManagers in non-e10s mode, we reach
|
||||
// // this point with a dead messageManager which only throws errors but does not
|
||||
// // seem to indicate in any other way that it is dead.
|
||||
// }
|
||||
// },
|
||||
|
||||
// startBulkSend: function () {
|
||||
// throw new Error("Can't send bulk data to child processes.");
|
||||
// },
|
||||
|
||||
// swapBrowser(mm) {
|
||||
// this._removeListener();
|
||||
// this._mm = mm;
|
||||
// this._addListener();
|
||||
// },
|
||||
// };
|
||||
|
||||
// exports.ChildDebuggerTransport = ChildDebuggerTransport;
|
||||
|
||||
// // WorkerDebuggerTransport is defined differently depending on whether we are
|
||||
// // on the main thread or a worker thread. In the former case, we are required
|
||||
// // by the devtools loader, and isWorker will be false. Otherwise, we are
|
||||
// // required by the worker loader, and isWorker will be true.
|
||||
// //
|
||||
// // Each worker debugger supports only a single connection to the main thread.
|
||||
// // However, its theoretically possible for multiple servers to connect to the
|
||||
// // same worker. Consequently, each transport has a connection id, to allow
|
||||
// // messages from multiple connections to be multiplexed on a single channel.
|
||||
|
||||
// if (!this.isWorker) {
|
||||
// // Main thread
|
||||
// (function () {
|
||||
// /**
|
||||
// * A transport that uses a WorkerDebugger to send packets from the main
|
||||
// * thread to a worker thread.
|
||||
// */
|
||||
// function WorkerDebuggerTransport(dbg, id) {
|
||||
// this._dbg = dbg;
|
||||
// this._id = id;
|
||||
// this.onMessage = this._onMessage.bind(this);
|
||||
// }
|
||||
|
||||
// WorkerDebuggerTransport.prototype = {
|
||||
// constructor: WorkerDebuggerTransport,
|
||||
|
||||
// ready: function () {
|
||||
// this._dbg.addListener(this);
|
||||
// },
|
||||
|
||||
// close: function () {
|
||||
// this._dbg.removeListener(this);
|
||||
// if (this.hooks) {
|
||||
// this.hooks.onClosed();
|
||||
// }
|
||||
// },
|
||||
|
||||
// send: function (packet) {
|
||||
// this._dbg.postMessage(JSON.stringify({
|
||||
// type: "message",
|
||||
// id: this._id,
|
||||
// message: packet
|
||||
// }));
|
||||
// },
|
||||
|
||||
// startBulkSend: function () {
|
||||
// throw new Error("Can't send bulk data from worker threads!");
|
||||
// },
|
||||
|
||||
// _onMessage: function (message) {
|
||||
// let packet = JSON.parse(message);
|
||||
// if (packet.type !== "message" || packet.id !== this._id) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// if (this.hooks) {
|
||||
// this.hooks.onPacket(packet.message);
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
|
||||
// exports.WorkerDebuggerTransport = WorkerDebuggerTransport;
|
||||
// }).call(this);
|
||||
// } else {
|
||||
// // Worker thread
|
||||
// (function () {
|
||||
// /**
|
||||
// * A transport that uses a WorkerDebuggerGlobalScope to send packets from a
|
||||
// * worker thread to the main thread.
|
||||
// */
|
||||
// function WorkerDebuggerTransport(scope, id) {
|
||||
// this._scope = scope;
|
||||
// this._id = id;
|
||||
// this._onMessage = this._onMessage.bind(this);
|
||||
// }
|
||||
|
||||
// WorkerDebuggerTransport.prototype = {
|
||||
// constructor: WorkerDebuggerTransport,
|
||||
|
||||
// ready: function () {
|
||||
// this._scope.addEventListener("message", this._onMessage);
|
||||
// },
|
||||
|
||||
// close: function () {
|
||||
// this._scope.removeEventListener("message", this._onMessage);
|
||||
// if (this.hooks) {
|
||||
// this.hooks.onClosed();
|
||||
// }
|
||||
// },
|
||||
|
||||
// send: function (packet) {
|
||||
// this._scope.postMessage(JSON.stringify({
|
||||
// type: "message",
|
||||
// id: this._id,
|
||||
// message: packet
|
||||
// }));
|
||||
// },
|
||||
|
||||
// startBulkSend: function () {
|
||||
// throw new Error("Can't send bulk data from worker threads!");
|
||||
// },
|
||||
|
||||
// _onMessage: function (event) {
|
||||
// let packet = JSON.parse(event.data);
|
||||
// if (packet.type !== "message" || packet.id !== this._id) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// if (this.hooks) {
|
||||
// this.hooks.onPacket(packet.message);
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
|
||||
// exports.WorkerDebuggerTransport = WorkerDebuggerTransport;
|
||||
// }).call(this);
|
||||
// }
|
||||
// });
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,218 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.AssetsManager
|
||||
* jsb.AssetsManager is the native AssetsManager for your game resources or scripts.
|
||||
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
|
||||
* Only available in JSB
|
||||
*/
|
||||
jsb.AssetsManager = cc.AssetsManager;
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.Manifest
|
||||
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
|
||||
* Only available in JSB
|
||||
*/
|
||||
jsb.Manifest = cc.Manifest;
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.EventListenerAssetsManager
|
||||
* jsb.EventListenerAssetsManager is the native event listener for AssetsManager.
|
||||
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
|
||||
* Only available in JSB
|
||||
*/
|
||||
jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager;
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.EventAssetsManager
|
||||
* jsb.EventAssetsManager is the native event for AssetsManager.
|
||||
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
|
||||
* Only available in JSB
|
||||
*/
|
||||
jsb.EventAssetsManager = cc.EventAssetsManager;
|
||||
|
||||
jsb.AssetsManager.State = {
|
||||
UNINITED : 0,
|
||||
UNCHECKED : 1,
|
||||
PREDOWNLOAD_VERSION : 2,
|
||||
DOWNLOADING_VERSION : 3,
|
||||
VERSION_LOADED : 4,
|
||||
PREDOWNLOAD_MANIFEST : 5,
|
||||
DOWNLOADING_MANIFEST : 6,
|
||||
MANIFEST_LOADED : 7,
|
||||
NEED_UPDATE : 8,
|
||||
READY_TO_UPDATE : 9,
|
||||
UPDATING : 10,
|
||||
UNZIPPING : 11,
|
||||
UP_TO_DATE : 12,
|
||||
FAIL_TO_UPDATE : 13
|
||||
}
|
||||
|
||||
jsb.EventListenerAssetsManager.prototype._ctor = function(assetsManager, callback) {
|
||||
callback !== undefined && this.init(assetsManager, callback);
|
||||
};
|
||||
|
||||
jsb.Manifest.DownloadState = {
|
||||
UNSTARTED: 0,
|
||||
DOWNLOADING: 1,
|
||||
SUCCESSED: 2,
|
||||
UNMARKED: 3
|
||||
};
|
||||
|
||||
jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
|
||||
jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
|
||||
jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
|
||||
jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
|
||||
jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
|
||||
jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
|
||||
jsb.EventAssetsManager.ASSET_UPDATED = 6;
|
||||
jsb.EventAssetsManager.ERROR_UPDATING = 7;
|
||||
jsb.EventAssetsManager.UPDATE_FINISHED = 8;
|
||||
jsb.EventAssetsManager.UPDATE_FAILED = 9;
|
||||
jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.KEYBOARD_RETURNTYPE_DEFAULT = 0;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.KEYBOARD_RETURNTYPE_DONE = 1;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.KEYBOARD_RETURNTYPE_SEND = 2;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.KEYBOARD_RETURNTYPE_SEARCH = 3;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.KEYBOARD_RETURNTYPE_GO = 4;
|
||||
|
||||
/**
|
||||
* The EditBox::InputMode defines the type of text that the user is allowed * to enter.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_ANY = 0;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter an e-mail address.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_EMAILADDR = 1;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter an integer value.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_NUMERIC = 2;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter a phone number.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter a URL.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_URL = 4;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter a real number value.
|
||||
* This extends kEditBoxInputModeNumeric by allowing a decimal point.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_DECIMAL = 5;
|
||||
|
||||
/**
|
||||
* The user is allowed to enter any text, except for line breaks.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_MODE_SINGLELINE = 6;
|
||||
|
||||
/**
|
||||
* Indicates that the text entered is confidential data that should be
|
||||
* obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_FLAG_PASSWORD = 0;
|
||||
|
||||
/**
|
||||
* Indicates that the text entered is sensitive data that the
|
||||
* implementation must never store into a dictionary or table for use
|
||||
* in predictive, auto-completing, or other accelerated input schemes.
|
||||
* A credit card number is an example of sensitive data.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1;
|
||||
|
||||
/**
|
||||
* This flag is a hint to the implementation that during text editing,
|
||||
* the initial letter of each word should be capitalized.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2;
|
||||
|
||||
/**
|
||||
* This flag is a hint to the implementation that during text editing,
|
||||
* the initial letter of each sentence should be capitalized.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3;
|
||||
|
||||
/**
|
||||
* Capitalize all characters automatically.
|
||||
* @constant
|
||||
* @type Number
|
||||
*/
|
||||
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4;
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
//
|
||||
// JavaScript Bindings helper file
|
||||
//
|
||||
|
||||
// DO NOT ALTER THE ORDER
|
||||
require('script/jsb_cocos2d.js');
|
||||
require('script/jsb_common.js');
|
||||
require('script/jsb_property_impls.js');
|
||||
require('script/jsb_property_apis.js');
|
||||
require('script/jsb_create_apis.js');
|
||||
require('script/extension/jsb_cocos2d_extension.js');
|
||||
|
||||
if (window.ccui) {
|
||||
require('script/ccui/jsb_cocos2d_ui.js');
|
||||
require('script/ccui/jsb_ccui_property_impls.js');
|
||||
require('script/ccui/jsb_ccui_property_apis.js');
|
||||
require('script/ccui/jsb_ccui_create_apis.js');
|
||||
}
|
||||
|
||||
require('script/jsb_opengl_constants.js');
|
||||
require('script/jsb_opengl.js');
|
||||
|
||||
if (window.sp) {
|
||||
require('script/jsb_spine.js');
|
||||
}
|
||||
|
||||
if (window.dragonBones) {
|
||||
require('script/jsb_dragonbones.js');
|
||||
}
|
||||
|
||||
require("script/jsb_audioengine.js");
|
||||
require("script/jsb_cocosanalytics.js");
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
(function (jsb) {
|
||||
|
||||
if (!jsb || !jsb.AudioEngine) return;
|
||||
|
||||
jsb.AudioEngine.AudioState = {
|
||||
ERROR: -1,
|
||||
INITIALZING: 0,
|
||||
PLAYING: 1,
|
||||
PAUSED: 2
|
||||
};
|
||||
|
||||
jsb.AudioEngine.INVALID_AUDIO_ID = -1;
|
||||
jsb.AudioEngine.TIME_UNKNOWN = -1;
|
||||
|
||||
})(jsb);
|
||||
@@ -1,793 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
//
|
||||
// cocos2d boot
|
||||
//
|
||||
|
||||
'use strict';
|
||||
|
||||
//+++++++++++++++++++++++++Engine initialization function begin+++++++++++++++++++++++++++
|
||||
|
||||
// Define singleton objects
|
||||
cc.director = cc.Director.getInstance();
|
||||
cc.director._actionManager = cc.director.getActionManager();
|
||||
cc.director._scheduler = cc.director.getScheduler();
|
||||
cc.winSize = cc.director.getWinSize();
|
||||
|
||||
cc.view = cc.director.getOpenGLView();
|
||||
cc.view.getDevicePixelRatio = cc.view.getRetinaFactor;
|
||||
cc.view.convertToLocationInView = function (tx, ty, relatedPos) {
|
||||
var _devicePixelRatio = cc.view.getDevicePixelRatio();
|
||||
return {x: _devicePixelRatio * (tx - relatedPos.left), y: _devicePixelRatio * (relatedPos.top + relatedPos.height - ty)};
|
||||
};
|
||||
cc.view.enableRetina = function(enabled) {};
|
||||
cc.view.isRetinaEnabled = function() {
|
||||
var sys = cc.sys;
|
||||
return (sys.os === sys.OS_IOS || sys.os === sys.OS_OSX) ? true : false;
|
||||
};
|
||||
cc.view.adjustViewPort = function() {};
|
||||
cc.view.resizeWithBrowserSize = function () {return;};
|
||||
cc.view.setResizeCallback = function() {return;};
|
||||
cc.view.enableAutoFullScreen = function () {return;};
|
||||
cc.view.isAutoFullScreenEnabled = function() {return true;};
|
||||
cc.view._setDesignResolutionSize = cc.view.setDesignResolutionSize;
|
||||
cc.view.setDesignResolutionSize = function(width,height,resolutionPolicy){
|
||||
cc.view._setDesignResolutionSize(width,height,resolutionPolicy);
|
||||
cc.winSize = cc.director.getWinSize();
|
||||
cc.visibleRect.init();
|
||||
};
|
||||
cc.view.setRealPixelResolution = cc.view.setDesignResolutionSize;
|
||||
cc.view.setResolutionPolicy = function(resolutionPolicy){
|
||||
var size = cc.view.getDesignResolutionSize();
|
||||
cc.view.setDesignResolutionSize(size.width,size.height,resolutionPolicy);
|
||||
};
|
||||
|
||||
cc.view.getCanvasSize = cc.view.getFrameSize;
|
||||
cc.view.getVisibleSizeInPixel = cc.view.getVisibleSize;
|
||||
cc.view.getVisibleOriginInPixel = cc.view.getVisibleOrigin;
|
||||
cc.view.setContentTranslateLeftTop = function(){return;};
|
||||
cc.view.getContentTranslateLeftTop = function(){return null;};
|
||||
cc.view.setFrameZoomFactor = function(){return;};
|
||||
cc.view.setOrientation = function () {};
|
||||
cc.view.setTargetDensityDPI = function() {};
|
||||
cc.view.getTargetDensityDPI = function() {return cc.macro.DENSITYDPI_DEVICE;};
|
||||
|
||||
cc.eventManager = cc.director.getEventDispatcher();
|
||||
|
||||
cc.eventManager._resizeListener = cc.eventManager.addCustomListener('window-resize', function () {
|
||||
cc.winSize = cc.director.getWinSize();
|
||||
cc.visibleRect.init();
|
||||
});
|
||||
|
||||
cc.configuration = cc.Configuration.getInstance();
|
||||
cc.textureCache = cc.director.getTextureCache();
|
||||
cc.shaderCache = cc.ShaderCache.getInstance();
|
||||
cc.plistParser = cc.PlistParser.getInstance();
|
||||
|
||||
// File utils (Temporary, won't be accessible)
|
||||
cc.fileUtils = cc.FileUtils.getInstance();
|
||||
cc.fileUtils.setPopupNotify(false);
|
||||
|
||||
cc.screen = {
|
||||
init: function() {},
|
||||
fullScreen: function() {
|
||||
return true;
|
||||
},
|
||||
requestFullScreen: function(element, onFullScreenChange) {
|
||||
onFullScreenChange.call();
|
||||
},
|
||||
exitFullScreen: function() {
|
||||
return false;
|
||||
},
|
||||
autoFullScreen: function(element, onFullScreenChange) {
|
||||
onFullScreenChange.call();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.fileUtils
|
||||
* jsb.fileUtils is the native file utils singleton object,
|
||||
* please refer to Cocos2d-x API to know how to use it.
|
||||
* Only available in JSB
|
||||
*/
|
||||
jsb.fileUtils = cc.fileUtils;
|
||||
delete cc.FileUtils;
|
||||
delete cc.fileUtils;
|
||||
|
||||
/**
|
||||
* @type {Object}
|
||||
* @name jsb.reflection
|
||||
* jsb.reflection is a bridge to let you invoke Java static functions.
|
||||
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/reflection/en
|
||||
* Only available on Android platform
|
||||
*/
|
||||
jsb.reflection = {
|
||||
callStaticMethod : function(){
|
||||
cc.log("not supported on current platform");
|
||||
}
|
||||
};
|
||||
|
||||
//+++++++++++++++++++++++++Redefine JSB only APIs+++++++++++++++++++++++++++++
|
||||
|
||||
|
||||
//+++++++++++++++++++++++++something about window events begin+++++++++++++++++++++++++++
|
||||
cc.winEvents = {//TODO register hidden and show callback for window
|
||||
hiddens : [],
|
||||
shows : []
|
||||
};
|
||||
//+++++++++++++++++++++++++something about window events end+++++++++++++++++++++++++++++
|
||||
|
||||
//+++++++++++++++++++++++++something about sys begin+++++++++++++++++++++++++++++
|
||||
var _initSys = function () {
|
||||
|
||||
cc.sys = window.sys || {};
|
||||
var sys = cc.sys;
|
||||
|
||||
/**
|
||||
* English language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_ENGLISH = "en";
|
||||
|
||||
/**
|
||||
* Chinese language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_CHINESE = "zh";
|
||||
|
||||
/**
|
||||
* French language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_FRENCH = "fr";
|
||||
|
||||
/**
|
||||
* Italian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_ITALIAN = "it";
|
||||
|
||||
/**
|
||||
* German language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_GERMAN = "de";
|
||||
|
||||
/**
|
||||
* Spanish language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_SPANISH = "es";
|
||||
|
||||
/**
|
||||
* Netherlands language code
|
||||
* @type {string}
|
||||
*/
|
||||
sys.LANGUAGE_DUTCH = "nl";
|
||||
/**
|
||||
* Dutch language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_DUTCH = "du";
|
||||
|
||||
/**
|
||||
* Russian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_RUSSIAN = "ru";
|
||||
|
||||
/**
|
||||
* Korean language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_KOREAN = "ko";
|
||||
|
||||
/**
|
||||
* Japanese language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_JAPANESE = "ja";
|
||||
|
||||
/**
|
||||
* Hungarian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_HUNGARIAN = "hu";
|
||||
|
||||
/**
|
||||
* Portuguese language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_PORTUGUESE = "pt";
|
||||
|
||||
/**
|
||||
* Arabic language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_ARABIC = "ar";
|
||||
|
||||
/**
|
||||
* Norwegian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_NORWEGIAN = "no";
|
||||
|
||||
/**
|
||||
* Polish language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_POLISH = "pl";
|
||||
|
||||
/**
|
||||
* Turkish language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_TURKISH = "tr";
|
||||
|
||||
/**
|
||||
* Ukrainian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_UKRAINIAN = "uk";
|
||||
|
||||
/**
|
||||
* Romanian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_ROMANIAN = "ro";
|
||||
|
||||
/**
|
||||
* Bulgarian language code
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_BULGARIAN = "bg";
|
||||
|
||||
/**
|
||||
* Unknown language code
|
||||
* @memberof cc.sys
|
||||
* @name LANGUAGE_UNKNOWN
|
||||
* @constant
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LANGUAGE_UNKNOWN = "unknown";
|
||||
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_IOS
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_IOS = "iOS";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_ANDROID
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_ANDROID = "Android";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_WINDOWS
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_WINDOWS = "Windows";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_MARMALADE
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_MARMALADE = "Marmalade";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_LINUX
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_LINUX = "Linux";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_BADA
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_BADA = "Bada";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_BLACKBERRY
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_BLACKBERRY = "Blackberry";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_OSX
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_OSX = "OS X";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_WP8
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_WP8 = "WP8";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_WINRT
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_WINRT = "WINRT";
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name OS_UNKNOWN
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
sys.OS_UNKNOWN = "Unknown";
|
||||
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name UNKNOWN
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.UNKNOWN = -1;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name WIN32
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.WIN32 = 0;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name LINUX
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.LINUX = 1;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name MACOS
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.MACOS = 2;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name ANDROID
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.ANDROID = 3;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name IOS
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.IPHONE = 4;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name IOS
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.IPAD = 5;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name BLACKBERRY
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.BLACKBERRY = 6;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name NACL
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.NACL = 7;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name EMSCRIPTEN
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.EMSCRIPTEN = 8;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name TIZEN
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.TIZEN = 9;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name WINRT
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.WINRT = 10;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name WP8
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.WP8 = 11;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name MOBILE_BROWSER
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.MOBILE_BROWSER = 100;
|
||||
/**
|
||||
* @memberof cc.sys
|
||||
* @name DESKTOP_BROWSER
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Number}
|
||||
*/
|
||||
sys.DESKTOP_BROWSER = 101;
|
||||
|
||||
sys.BROWSER_TYPE_WECHAT = "wechat";
|
||||
sys.BROWSER_TYPE_ANDROID = "androidbrowser";
|
||||
sys.BROWSER_TYPE_IE = "ie";
|
||||
sys.BROWSER_TYPE_QQ = "qqbrowser";
|
||||
sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser";
|
||||
sys.BROWSER_TYPE_UC = "ucbrowser";
|
||||
sys.BROWSER_TYPE_360 = "360browser";
|
||||
sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp";
|
||||
sys.BROWSER_TYPE_BAIDU = "baidubrowser";
|
||||
sys.BROWSER_TYPE_MAXTHON = "maxthon";
|
||||
sys.BROWSER_TYPE_OPERA = "opera";
|
||||
sys.BROWSER_TYPE_OUPENG = "oupeng";
|
||||
sys.BROWSER_TYPE_MIUI = "miuibrowser";
|
||||
sys.BROWSER_TYPE_FIREFOX = "firefox";
|
||||
sys.BROWSER_TYPE_SAFARI = "safari";
|
||||
sys.BROWSER_TYPE_CHROME = "chrome";
|
||||
sys.BROWSER_TYPE_LIEBAO = "liebao";
|
||||
sys.BROWSER_TYPE_QZONE = "qzone";
|
||||
sys.BROWSER_TYPE_SOUGOU = "sogou";
|
||||
sys.BROWSER_TYPE_UNKNOWN = "unknown";
|
||||
|
||||
/**
|
||||
* Is native ? This is set to be true in jsb auto.
|
||||
* @constant
|
||||
* @default
|
||||
* @type {Boolean}
|
||||
*/
|
||||
sys.isNative = true;
|
||||
|
||||
var platform = sys.platform = __getPlatform();
|
||||
|
||||
/**
|
||||
* Indicate whether system is mobile system
|
||||
* @memberof cc.sys
|
||||
* @name isMobile
|
||||
* @type {Boolean}
|
||||
*/
|
||||
sys.isMobile = (platform === sys.ANDROID ||
|
||||
platform === sys.IPAD ||
|
||||
platform === sys.IPHONE ||
|
||||
platform === sys.WP8 ||
|
||||
platform === sys.TIZEN ||
|
||||
platform === sys.BLACKBERRY) ? true : false;
|
||||
|
||||
sys._application = cc.Application.getInstance();
|
||||
|
||||
/**
|
||||
* Indicate the current language of the running system
|
||||
* @memberof cc.sys
|
||||
* @name language
|
||||
* @type {String}
|
||||
*/
|
||||
sys.language = (function(){
|
||||
var language = sys._application.getCurrentLanguage();
|
||||
switch(language){
|
||||
case 0: return sys.LANGUAGE_ENGLISH;
|
||||
case 1: return sys.LANGUAGE_CHINESE;
|
||||
case 2: return sys.LANGUAGE_FRENCH;
|
||||
case 3: return sys.LANGUAGE_ITALIAN;
|
||||
case 4: return sys.LANGUAGE_GERMAN;
|
||||
case 5: return sys.LANGUAGE_SPANISH;
|
||||
case 6: return sys.LANGUAGE_DUTCH;
|
||||
case 7: return sys.LANGUAGE_RUSSIAN;
|
||||
case 8: return sys.LANGUAGE_KOREAN;
|
||||
case 9: return sys.LANGUAGE_JAPANESE;
|
||||
case 10: return sys.LANGUAGE_HUNGARIAN;
|
||||
case 11: return sys.LANGUAGE_PORTUGUESE;
|
||||
case 12: return sys.LANGUAGE_ARABIC;
|
||||
case 13: return sys.LANGUAGE_NORWEGIAN;
|
||||
case 14: return sys.LANGUAGE_POLISH;
|
||||
case 15: return sys.LANGUAGE_TURKISH;
|
||||
case 16: return sys.LANGUAGE_UKRAINIAN;
|
||||
case 17: return sys.LANGUAGE_ROMANIAN;
|
||||
case 18: return sys.LANGUAGE_BULGARIAN;
|
||||
default: return sys.LANGUAGE_ENGLISH;
|
||||
}
|
||||
})();
|
||||
|
||||
sys.os = __getOS();
|
||||
|
||||
sys.browserType = null; //null in jsb
|
||||
|
||||
sys.browserVersion = null; //null in jsb
|
||||
|
||||
sys.windowPixelResolution = cc.view.getFrameSize();
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Network type enumeration
|
||||
* !#zh
|
||||
* 网络类型枚举
|
||||
*
|
||||
* @enum NetworkType
|
||||
*/
|
||||
sys.NetworkType = {
|
||||
/**
|
||||
* !#en
|
||||
* Network is unreachable.
|
||||
* !#zh
|
||||
* 网络不通
|
||||
*
|
||||
* @property {Number} NONE
|
||||
*/
|
||||
NONE: 0,
|
||||
/**
|
||||
* !#en
|
||||
* Network is reachable via WiFi or cable.
|
||||
* !#zh
|
||||
* 通过无线或者有线本地网络连接因特网
|
||||
*
|
||||
* @property {Number} LAN
|
||||
*/
|
||||
LAN: 1,
|
||||
/**
|
||||
* !#en
|
||||
* Network is reachable via Wireless Wide Area Network
|
||||
* !#zh
|
||||
* 通过蜂窝移动网络连接因特网
|
||||
*
|
||||
* @property {Number} WWAN
|
||||
*/
|
||||
WWAN: 2
|
||||
};
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Get the battery level of current device, return 1.0 if failure.
|
||||
* !#zh
|
||||
* 获取当前设备的电池电量,如果电量无法获取,默认将返回 1
|
||||
*
|
||||
* @method getBatteryLevel
|
||||
* @return {Number} - 0.0 ~ 1.0
|
||||
*/
|
||||
sys.getBatteryLevel = function() {
|
||||
return cc.Device.getBatteryLevel();
|
||||
};
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Get the network type of current device, return cc.sys.NetworkType.LAN if failure.
|
||||
* !#zh
|
||||
* 获取当前设备的网络类型, 如果网络类型无法获取,默认将返回 cc.sys.NetworkType.LAN
|
||||
*
|
||||
* @method getNetworkType
|
||||
* @return {NetworkType}
|
||||
*/
|
||||
sys.getNetworkType = function() {
|
||||
return cc.Device.getNetworkType();
|
||||
};
|
||||
|
||||
var capabilities = sys.capabilities = {
|
||||
"canvas": false,
|
||||
"opengl": true
|
||||
};
|
||||
if( sys.isMobile ) {
|
||||
capabilities["accelerometer"] = true;
|
||||
capabilities["touches"] = true;
|
||||
if (platform === sys.WINRT || platform === sys.WP8) {
|
||||
capabilities["keyboard"] = true;
|
||||
}
|
||||
} else {
|
||||
// desktop
|
||||
capabilities["keyboard"] = true;
|
||||
capabilities["mouse"] = true;
|
||||
// winrt can't suppot mouse in current version
|
||||
if (platform === sys.WINRT || platform === sys.WP8)
|
||||
{
|
||||
capabilities["touches"] = true;
|
||||
capabilities["mouse"] = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces the garbage collection, only available in JSB
|
||||
* @memberof cc.sys
|
||||
* @name garbageCollect
|
||||
* @function
|
||||
*/
|
||||
sys.garbageCollect = function() {
|
||||
__jsc__.garbageCollect();
|
||||
};
|
||||
|
||||
/**
|
||||
* Dumps rooted objects, only available in JSB
|
||||
* @memberof cc.sys
|
||||
* @name dumpRoot
|
||||
* @function
|
||||
*/
|
||||
sys.dumpRoot = function() {
|
||||
__jsc__.dumpRoot();
|
||||
};
|
||||
|
||||
/**
|
||||
* Restart the JS VM, only available in JSB
|
||||
* @memberof cc.sys
|
||||
* @name restartVM
|
||||
* @function
|
||||
*/
|
||||
sys.restartVM = function() {
|
||||
__restartVM();
|
||||
};
|
||||
|
||||
/**
|
||||
* Clean a script in the JS VM, only available in JSB
|
||||
* @memberof cc.sys
|
||||
* @name cleanScript
|
||||
* @param {String} jsfile
|
||||
* @function
|
||||
*/
|
||||
sys.cleanScript = function(jsFile) {
|
||||
__cleanScript(jsFile);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check whether an object is valid,
|
||||
* In web engine, it will return true if the object exist
|
||||
* In native engine, it will return true if the JS object and the correspond native object are both valid
|
||||
* @memberof cc.sys
|
||||
* @name isObjectValid
|
||||
* @param {Object} obj
|
||||
* @return {boolean} Validity of the object
|
||||
* @function
|
||||
*/
|
||||
sys.isObjectValid = function(obj) {
|
||||
return __isObjectValid(obj);
|
||||
};
|
||||
|
||||
/**
|
||||
* Dump system informations
|
||||
* @memberof cc.sys
|
||||
* @name dump
|
||||
* @function
|
||||
*/
|
||||
sys.dump = function () {
|
||||
var self = this;
|
||||
var str = "";
|
||||
str += "isMobile : " + self.isMobile + "\r\n";
|
||||
str += "language : " + self.language + "\r\n";
|
||||
str += "browserType : " + self.browserType + "\r\n";
|
||||
str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n";
|
||||
str += "os : " + self.os + "\r\n";
|
||||
str += "platform : " + self.platform + "\r\n";
|
||||
cc.log(str);
|
||||
};
|
||||
|
||||
/**
|
||||
* Open a url in browser
|
||||
* @memberof cc.sys
|
||||
* @name openURL
|
||||
* @param {String} url
|
||||
*/
|
||||
sys.openURL = function(url){
|
||||
sys._application.openURL(url);
|
||||
};
|
||||
|
||||
sys.now = function () {
|
||||
return Date.now();
|
||||
};
|
||||
|
||||
// JS to Native bridges
|
||||
if(window.JavascriptJavaBridge && cc.sys.os == cc.sys.OS_ANDROID){
|
||||
jsb.reflection = new JavascriptJavaBridge();
|
||||
cc.sys.capabilities["keyboard"] = true;
|
||||
}
|
||||
else if(window.JavaScriptObjCBridge && (cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_OSX)){
|
||||
jsb.reflection = new JavaScriptObjCBridge();
|
||||
}
|
||||
};
|
||||
_initSys();
|
||||
|
||||
//+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++
|
||||
|
||||
jsb.urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i");
|
||||
|
||||
cc._engineLoaded = false;
|
||||
|
||||
(function (config) {
|
||||
require("script/jsb.js");
|
||||
cc._engineLoaded = true;
|
||||
console.log(cc.ENGINE_VERSION);
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,734 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
(function(){
|
||||
|
||||
var sys = cc.sys;
|
||||
var platform = sys.platform;
|
||||
|
||||
// Only android and iOS support cocos analytics
|
||||
if (platform === sys.ANDROID) {
|
||||
|
||||
cocosAnalytics = {};
|
||||
|
||||
var cls_CAAccount = "com/cocos/analytics/CAAccount";
|
||||
var cls_CAAgent = "com/cocos/analytics/CAAgent";
|
||||
var cls_CAEvent = "com/cocos/analytics/CAEvent";
|
||||
var cls_CAItem = "com/cocos/analytics/CAItem";
|
||||
var cls_CALevels = "com/cocos/analytics/CALevels";
|
||||
var cls_CAPayment = "com/cocos/analytics/CAPayment";
|
||||
var cls_CATask = "com/cocos/analytics/CATask";
|
||||
var cls_CAVirtual = "com/cocos/analytics/CAVirtual";
|
||||
|
||||
var cls_CAAgentWrapper = "org/cocos2dx/lib/CAAgentWrapper";
|
||||
|
||||
cocosAnalytics.init = function(info) {
|
||||
|
||||
if (!info.channel) {
|
||||
var anysdkChannelID = jsb.reflection.callStaticMethod(cls_CAAgentWrapper, "getChannelID", "()Ljava/lang/String;");
|
||||
console.log("Found AnySDK channel ID: " + anysdkChannelID);
|
||||
info.channel = anysdkChannelID;
|
||||
}
|
||||
|
||||
if (info && info.appID && info.appSecret && info.channel) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAgentWrapper,
|
||||
"init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.channel, info.appID, info.appSecret);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.init are wrong!");
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.enableDebug = function(enabled) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAgent,
|
||||
"enableDebug", "(Z)V",
|
||||
enabled);
|
||||
};
|
||||
|
||||
cocosAnalytics.CAAccount = {
|
||||
loginStart: function() {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginStart", "()V");
|
||||
},
|
||||
|
||||
loginSuccess: function(info) {
|
||||
if (info && info.userID) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginSuccess", "(Ljava/lang/String;)V", info.userID);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.loginSuccess are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
loginFailed: function() {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginFailed", "()V");
|
||||
},
|
||||
|
||||
logout: function(info) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "logout", "()V");
|
||||
},
|
||||
|
||||
setAccountType: function(type) {
|
||||
if (type) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setAccountType", "(Ljava/lang/String;)V", type);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.setAccountType are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setAge: function(age) {
|
||||
if (age) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setAge", "(I)V", age);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setAge is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setGender: function(gender) {
|
||||
if (gender) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setGender", "(I)V", gender);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setGender is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setLevel: function(level) {
|
||||
if (level) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setLevel", "(I)V", level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setLevel is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
createRole: function(info) {
|
||||
if (info && info.roleID && info.userName && info.race && info['class'] && info.gameServer) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount,
|
||||
"createRole", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.roleID, info.userName, info.race, info['class'], info.gameServer);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.createRole are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAEvent = {
|
||||
onEvent: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEvent", "(Ljava/lang/String;)V", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEvent is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
onEventStart: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEventStart", "(Ljava/lang/String;)V", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEventStart is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
onEventEnd: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEventEnd", "(Ljava/lang/String;)V", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEventEnd is wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAPayment = {
|
||||
payBegin: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"payBegin", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payBegin are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
paySuccess: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"paySuccess", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.paySuccess are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
payFailed: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"payFailed", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payFailed are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
payCanceled: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"payCanceled", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payCanceled are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CALevels = {
|
||||
begin: function(info) {
|
||||
if (info && info.level) {
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "begin", "(Ljava/lang/String;)V", info.level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CALevels.begin is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
if (info && info.level) {
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "complete", "(Ljava/lang/String;)V", info.level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CALevels.complete is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
if (info && info.level) {
|
||||
info.reason = info.reason || "";
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "failed", "(Ljava/lang/String;Ljava/lang/String;)V", info.level, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CALevels.failed are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CATaskType = {
|
||||
GuideLine: 1,
|
||||
MainLine: 2,
|
||||
BranchLine: 3,
|
||||
Daily: 4,
|
||||
Activity: 5,
|
||||
Other: 100
|
||||
};
|
||||
|
||||
cocosAnalytics.CATask = {
|
||||
|
||||
begin: function(info) {
|
||||
if (info && info.taskID && info.type) {
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "begin", "(Ljava/lang/String;I)V", info.taskID, info.type);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CATask.begin are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
if (info && info.taskID) {
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "complete", "(Ljava/lang/String;)V", info.taskID);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CATask.complete is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
if (info && info.taskID) {
|
||||
info.reason = info.reason || "";
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "failed", "(Ljava/lang/String;Ljava/lang/String;)V", info.taskID, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CATask.failed are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAItem = {
|
||||
buy: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.virtualCoin && info.virtualType && info.consumePoint) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "buy", "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;Ljava/lang/String;)V",
|
||||
info.itemID, info.itemType, info.itemCount, info.virtualCoin, info.virtualType, info.consumePoint);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.buy are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "get", "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V",
|
||||
info.itemID, info.itemType, info.itemCount, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.get are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "consume", "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V",
|
||||
info.itemID, info.itemType, info.itemCount, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.consume are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAVirtual = {
|
||||
setVirtualNum: function(info) {
|
||||
if (info && info.type && info.count) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "setVirtualNum", "(Ljava/lang/String;J)V",
|
||||
info.type, info.count);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.setVirtualNum are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
if (info && info.type && info.count && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "get", "(Ljava/lang/String;JLjava/lang/String;)V",
|
||||
info.type, info.count, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.get are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
if (info && info.type && info.count && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "consume", "(Ljava/lang/String;JLjava/lang/String;)V",
|
||||
info.type, info.count, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.consume are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} else if (platform === sys.IPAD || platform === sys.IPHONE) {
|
||||
cocosAnalytics = {};
|
||||
|
||||
var cls_CAAccount = "CAAccount";
|
||||
var cls_CAAgent = "CAAgent";
|
||||
var cls_CAEvent = "CAEvent";
|
||||
var cls_CAItem = "CAItem";
|
||||
var cls_CALevels = "CALevels";
|
||||
var cls_CAPayment = "CAPeiment";
|
||||
var cls_CATask = "CATask";
|
||||
var cls_CAVirtual = "CAVirtual";
|
||||
var cls_JSB_PlatformIOS = "JSB_PlatformIOS";
|
||||
|
||||
cocosAnalytics.init = function(info) {
|
||||
|
||||
if (!info.channel) {
|
||||
var anysdkChannelID = jsb.reflection.callStaticMethod(cls_JSB_PlatformIOS, "getChannelID");
|
||||
console.log("Found AnySDK channel ID: " + anysdkChannelID);
|
||||
info.channel = anysdkChannelID;
|
||||
}
|
||||
|
||||
if (info && info.appID && info.appSecret && info.channel) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAgent,
|
||||
"init:appID:appSecret:",
|
||||
info.channel, info.appID, info.appSecret);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.init are wrong!");
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.enableDebug = function(enabled) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAgent,
|
||||
"enableDebug:",
|
||||
enabled);
|
||||
};
|
||||
|
||||
cocosAnalytics.CAAccount = {
|
||||
|
||||
loginStart: function() {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginStart");
|
||||
},
|
||||
|
||||
loginSuccess: function(info) {
|
||||
if (info && info.userID) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginSuccess:", info.userID);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.loginSuccess are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
loginFailed: function() {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "loginFailed");
|
||||
},
|
||||
|
||||
logout: function(info) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "logout");
|
||||
},
|
||||
|
||||
setAccountType: function(type) {
|
||||
if (type) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setAccountType:", type);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.setAccountType are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setAge: function(age) {
|
||||
if (age) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setAge:", age);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setAge is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setGender: function(gender) {
|
||||
if (gender) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setGender:", gender);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setGender is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
setLevel: function(level) {
|
||||
if (level) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount, "setLevel:", level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAAccount.setLevel is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
createRole: function(info) {
|
||||
if (info && info.roleID && info.userName && info.race && info['class'] && info.gameServer) {
|
||||
jsb.reflection.callStaticMethod(cls_CAAccount,
|
||||
"createRole:userName:race:roleClass:gameServer:",
|
||||
info.roleID, info.userName, info.race, info['class'], info.gameServer);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAAccount.createRole are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAEvent = {
|
||||
onEvent: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEvent:", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEvent is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
onEventStart: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEventStart:", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEventStart is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
onEventEnd: function(info) {
|
||||
if (info && info.eventName) {
|
||||
jsb.reflection.callStaticMethod(cls_CAEvent, "onEventEnd:", info.eventName);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CAEvent.onEventEnd is wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAPayment = {
|
||||
payBegin: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"peiBegin:orderID:peiType:pppID:currencyType:",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payBegin are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
paySuccess: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"peiSuccess:orderID:peiType:pppID:currencyType:",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.paySuccess are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
payFailed: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"peiFailed:orderID:peiType:pppID:currencyType:",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payFailed are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
payCanceled: function(info) {
|
||||
if (info && info.amount && info.orderID && info.payType && info.iapID && info.currencyType) {
|
||||
jsb.reflection.callStaticMethod(cls_CAPayment,
|
||||
"peiCanceled:orderID:peiType:pppID:currencyType:",
|
||||
info.amount, info.orderID, info.payType, info.iapID, info.currencyType);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAPayment.payCanceled are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CALevels = {
|
||||
begin: function(info) {
|
||||
if (info && info.level) {
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "begin:", info.level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CALevels.begin is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
if (info && info.level) {
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "complete:", info.level);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CALevels.complete is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
if (info && info.level) {
|
||||
info.reason = info.reason || "";
|
||||
jsb.reflection.callStaticMethod(cls_CALevels, "failed:reason:", info.level, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CALevels.failed are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CATaskType = {
|
||||
GuideLine: 1,
|
||||
MainLine: 2,
|
||||
BranchLine: 3,
|
||||
Daily: 4,
|
||||
Activity: 5,
|
||||
Other: 100
|
||||
};
|
||||
|
||||
cocosAnalytics.CATask = {
|
||||
|
||||
begin: function(info) {
|
||||
if (info && info.taskID && info.type) {
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "begin:taskType:", info.taskID, info.type);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CATask.begin are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
if (info && info.taskID) {
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "complete:", info.taskID);
|
||||
} else {
|
||||
console.error("The argument passed to cocosAnalytics.CATask.complete is wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
if (info && info.taskID) {
|
||||
info.reason = info.reason || "";
|
||||
jsb.reflection.callStaticMethod(cls_CATask, "failed:reason:", info.taskID, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CATask.failed are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAItem = {
|
||||
buy: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.virtualCoin && info.virtualType && info.consumePoint) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "buy:type:count:virtualCoin:virtualType:consumePoint:",
|
||||
info.itemID, info.itemType, info.itemCount, info.virtualCoin, info.virtualType, info.consumePoint);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.buy are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "get:type:count:reason:",
|
||||
info.itemID, info.itemType, info.itemCount, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.get are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
if (info && info.itemID && info.itemType && info.itemCount && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAItem, "consume:type:count:reason:",
|
||||
info.itemID, info.itemType, info.itemCount, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAItem.consume are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAVirtual = {
|
||||
setVirtualNum: function(info) {
|
||||
if (info && info.type && info.count) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "setVirtualNum:count:",
|
||||
info.type, info.count);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.setVirtualNum are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
if (info && info.type && info.count && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "get:count:reason:",
|
||||
info.type, info.count, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.get are wrong!");
|
||||
}
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
if (info && info.type && info.count && info.reason) {
|
||||
jsb.reflection.callStaticMethod(cls_CAVirtual, "consume:count:reason:",
|
||||
info.type, info.count, info.reason);
|
||||
} else {
|
||||
console.error("The arguments passed to cocosAnalytics.CAVirtual.consume are wrong!");
|
||||
}
|
||||
}
|
||||
};
|
||||
} else {
|
||||
// Empty implementation for other platforms
|
||||
cocosAnalytics = {};
|
||||
|
||||
cocosAnalytics.init = function(info) {
|
||||
console.log("Cocos Analytics module isn't available on this platform!");
|
||||
};
|
||||
|
||||
cocosAnalytics.enableDebug = function(enabled) {
|
||||
};
|
||||
|
||||
cocosAnalytics.CAAccount = {
|
||||
loginStart: function() {
|
||||
},
|
||||
|
||||
loginSuccess: function(info) {
|
||||
},
|
||||
|
||||
loginFailed: function() {
|
||||
},
|
||||
|
||||
logout: function(info) {
|
||||
},
|
||||
|
||||
setAccountType: function(type) {
|
||||
},
|
||||
|
||||
setAge: function(age) {
|
||||
},
|
||||
|
||||
setGender: function(gender) {
|
||||
},
|
||||
|
||||
setLevel: function(level) {
|
||||
},
|
||||
|
||||
createRole: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAEvent = {
|
||||
onEvent: function(info) {
|
||||
},
|
||||
|
||||
onEventStart: function(info) {
|
||||
},
|
||||
|
||||
onEventEnd: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAPayment = {
|
||||
payBegin: function(info) {
|
||||
},
|
||||
|
||||
paySuccess: function(info) {
|
||||
},
|
||||
|
||||
payFailed: function(info) {
|
||||
},
|
||||
|
||||
payCanceled: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CALevels = {
|
||||
begin: function(info) {
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CATaskType = {
|
||||
GuideLine: 1,
|
||||
MainLine: 2,
|
||||
BranchLine: 3,
|
||||
Daily: 4,
|
||||
Activity: 5,
|
||||
Other: 100
|
||||
};
|
||||
|
||||
cocosAnalytics.CATask = {
|
||||
|
||||
begin: function(info) {
|
||||
},
|
||||
|
||||
complete: function(info) {
|
||||
},
|
||||
|
||||
failed: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAItem = {
|
||||
buy: function(info) {
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
}
|
||||
};
|
||||
|
||||
cocosAnalytics.CAVirtual = {
|
||||
setVirtualNum: function(info) {
|
||||
},
|
||||
|
||||
get: function(info) {
|
||||
},
|
||||
|
||||
consume: function(info) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -1,334 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
cc.KEY = {
|
||||
none:0,
|
||||
|
||||
// android
|
||||
back:6,
|
||||
menu:18,
|
||||
|
||||
// desktop
|
||||
backspace:8,
|
||||
tab:9,
|
||||
|
||||
enter:13,
|
||||
|
||||
shift:16, //should use shiftkey instead
|
||||
ctrl:17, //should use ctrlkey
|
||||
alt:18, //should use altkey
|
||||
pause:19,
|
||||
capslock:20,
|
||||
|
||||
escape:27,
|
||||
space:32,
|
||||
pageup:33,
|
||||
pagedown:34,
|
||||
end:35,
|
||||
home:36,
|
||||
left:37,
|
||||
up:38,
|
||||
right:39,
|
||||
down:40,
|
||||
select:41,
|
||||
|
||||
insert:45,
|
||||
Delete:46,
|
||||
0:48,
|
||||
1:49,
|
||||
2:50,
|
||||
3:51,
|
||||
4:52,
|
||||
5:53,
|
||||
6:54,
|
||||
7:55,
|
||||
8:56,
|
||||
9:57,
|
||||
a:65,
|
||||
b:66,
|
||||
c:67,
|
||||
d:68,
|
||||
e:69,
|
||||
f:70,
|
||||
g:71,
|
||||
h:72,
|
||||
i:73,
|
||||
j:74,
|
||||
k:75,
|
||||
l:76,
|
||||
m:77,
|
||||
n:78,
|
||||
o:79,
|
||||
p:80,
|
||||
q:81,
|
||||
r:82,
|
||||
s:83,
|
||||
t:84,
|
||||
u:85,
|
||||
v:86,
|
||||
w:87,
|
||||
x:88,
|
||||
y:89,
|
||||
z:90,
|
||||
|
||||
num0:96,
|
||||
num1:97,
|
||||
num2:98,
|
||||
num3:99,
|
||||
num4:100,
|
||||
num5:101,
|
||||
num6:102,
|
||||
num7:103,
|
||||
num8:104,
|
||||
num9:105,
|
||||
'*':106,
|
||||
'+':107,
|
||||
'-':109,
|
||||
'numdel':110,
|
||||
'/':111,
|
||||
f1:112, //f1-f12 don't work on ie
|
||||
f2:113,
|
||||
f3:114,
|
||||
f4:115,
|
||||
f5:116,
|
||||
f6:117,
|
||||
f7:118,
|
||||
f8:119,
|
||||
f9:120,
|
||||
f10:121,
|
||||
f11:122,
|
||||
f12:123,
|
||||
|
||||
numlock:144,
|
||||
scrolllock:145,
|
||||
|
||||
';':186,
|
||||
semicolon:186,
|
||||
equal:187,
|
||||
'=':187,
|
||||
',':188,
|
||||
comma:188,
|
||||
dash:189,
|
||||
'.':190,
|
||||
period:190,
|
||||
forwardslash:191,
|
||||
grave:192,
|
||||
'[':219,
|
||||
openbracket:219,
|
||||
backslash:220,
|
||||
']':221,
|
||||
closebracket:221,
|
||||
quote:222,
|
||||
|
||||
// gamepad control
|
||||
dpadLeft:1000,
|
||||
dpadRight:1001,
|
||||
dpadUp:1003,
|
||||
dpadDown:1004,
|
||||
dpadCenter:1005
|
||||
};
|
||||
|
||||
var jsbKeyArr = [
|
||||
cc.KEY["none"],//0
|
||||
cc.KEY["pause"],//1
|
||||
cc.KEY["scrolllock"],//2
|
||||
cc.KEY["none"],//3
|
||||
cc.KEY["none"],//4
|
||||
cc.KEY["none"],//5
|
||||
cc.KEY["back"],//6
|
||||
cc.KEY["backspace"],//7
|
||||
cc.KEY["tab"],//8
|
||||
cc.KEY["none"],//9
|
||||
cc.KEY["none"],//10
|
||||
cc.KEY["capslock"],//11
|
||||
cc.KEY["shift"],//12//should use shiftkey instead
|
||||
cc.KEY["shift"],//13
|
||||
cc.KEY["ctrl"],//14//should use ctrlkey
|
||||
cc.KEY["ctrl"],//15
|
||||
cc.KEY["alt"],//16//should use altkey
|
||||
cc.KEY["alt"],//17
|
||||
cc.KEY["menu"],//18
|
||||
cc.KEY["none"],//19
|
||||
cc.KEY["insert"],//20
|
||||
cc.KEY["home"],//21
|
||||
cc.KEY["pageup"],//22
|
||||
cc.KEY["Delete"],//23
|
||||
cc.KEY["end"],//24
|
||||
cc.KEY["pagedown"],//25
|
||||
cc.KEY["left"],//26
|
||||
cc.KEY["right"],//27
|
||||
cc.KEY["up"],//28
|
||||
cc.KEY["down"],//29
|
||||
cc.KEY["numlock"],//30
|
||||
cc.KEY["+"],//31
|
||||
cc.KEY["-"],//32
|
||||
cc.KEY["*"],//33
|
||||
cc.KEY["none"],//34
|
||||
cc.KEY["enter"],//35
|
||||
cc.KEY["home"],//36
|
||||
cc.KEY["up"],//37
|
||||
cc.KEY["pageup"],//38
|
||||
cc.KEY["left"],//39
|
||||
cc.KEY["num5"],//40
|
||||
cc.KEY["right"],//41
|
||||
cc.KEY["end"],//42
|
||||
cc.KEY["down"],//43
|
||||
cc.KEY["pagedown"],//44
|
||||
cc.KEY["insert"],//45
|
||||
cc.KEY["Delete"],//46
|
||||
cc.KEY["f1"],//47
|
||||
cc.KEY["f2"],//48
|
||||
cc.KEY["f3"],//49
|
||||
cc.KEY["f4"],//50
|
||||
cc.KEY["f5"],//51
|
||||
cc.KEY["f6"],//52
|
||||
cc.KEY["f7"],//53
|
||||
cc.KEY["f8"],//54
|
||||
cc.KEY["f9"],//55
|
||||
cc.KEY["f10"],//56
|
||||
cc.KEY["f11"],//57
|
||||
cc.KEY["f12"],//58
|
||||
cc.KEY["space"],//59
|
||||
cc.KEY["none"],//60
|
||||
cc.KEY["quote"],//61
|
||||
cc.KEY["none"],//62
|
||||
cc.KEY["none"],//63
|
||||
cc.KEY["none"],//64
|
||||
cc.KEY["none"],//65
|
||||
cc.KEY["none"],//66
|
||||
cc.KEY["quote"],//67
|
||||
cc.KEY["none"],//68
|
||||
cc.KEY["none"],//69
|
||||
cc.KEY["none"],//70
|
||||
cc.KEY["none"],//71
|
||||
cc.KEY["comma"],//72
|
||||
cc.KEY["-"],//73
|
||||
cc.KEY["period"],//74
|
||||
cc.KEY["forwardslash"],//75//word keyboard
|
||||
cc.KEY["num0"],//76
|
||||
cc.KEY["num1"],//77
|
||||
cc.KEY["num2"],//78
|
||||
cc.KEY["num3"],//79
|
||||
cc.KEY["num4"],//80
|
||||
cc.KEY["num5"],//81
|
||||
cc.KEY["num6"],//82
|
||||
cc.KEY["num7"],//83
|
||||
cc.KEY["num8"],//84
|
||||
cc.KEY["num9"],//85
|
||||
cc.KEY["none"],//86
|
||||
cc.KEY["semicolon"],//87
|
||||
cc.KEY["none"],//88
|
||||
cc.KEY["equal"],//89
|
||||
cc.KEY["none"],//90
|
||||
cc.KEY["none"],//91
|
||||
cc.KEY["none"],//92
|
||||
cc.KEY["a"],//93
|
||||
cc.KEY["b"],//94
|
||||
cc.KEY["c"],//95
|
||||
cc.KEY["d"],//96
|
||||
cc.KEY["e"],//97
|
||||
cc.KEY["f"],//98
|
||||
cc.KEY["g"],//99
|
||||
cc.KEY["h"],//100
|
||||
cc.KEY["i"],//101
|
||||
cc.KEY["j"],//102
|
||||
cc.KEY["k"],//103
|
||||
cc.KEY["l"],//104
|
||||
cc.KEY["m"],//105
|
||||
cc.KEY["n"],//106
|
||||
cc.KEY["o"],//107
|
||||
cc.KEY["p"],//108
|
||||
cc.KEY["q"],//109
|
||||
cc.KEY["r"],//110
|
||||
cc.KEY["s"],//111
|
||||
cc.KEY["t"],//112
|
||||
cc.KEY["u"],//113
|
||||
cc.KEY["v"],//114
|
||||
cc.KEY["w"],//115
|
||||
cc.KEY["x"],//116
|
||||
cc.KEY["y"],//117
|
||||
cc.KEY["z"],//118
|
||||
cc.KEY["openbracket"],//119
|
||||
cc.KEY["backslash"],//120
|
||||
cc.KEY["closebracket"],//121
|
||||
cc.KEY["none"],//122
|
||||
cc.KEY["grave"],//123
|
||||
cc.KEY["a"],//124
|
||||
cc.KEY["b"],//125
|
||||
cc.KEY["c"],//126
|
||||
cc.KEY["d"],//127
|
||||
cc.KEY["e"],//128
|
||||
cc.KEY["f"],//129
|
||||
cc.KEY["g"],//130
|
||||
cc.KEY["h"],//131
|
||||
cc.KEY["i"],//132
|
||||
cc.KEY["j"],//133
|
||||
cc.KEY["k"],//134
|
||||
cc.KEY["l"],//135
|
||||
cc.KEY["m"],//136
|
||||
cc.KEY["n"],//137
|
||||
cc.KEY["o"],//138
|
||||
cc.KEY["p"],//139
|
||||
cc.KEY["q"],//140
|
||||
cc.KEY["r"],//141
|
||||
cc.KEY["s"],//142
|
||||
cc.KEY["t"],//143
|
||||
cc.KEY["u"],//144
|
||||
cc.KEY["v"],//145
|
||||
cc.KEY["w"],//146
|
||||
cc.KEY["x"],//147
|
||||
cc.KEY["y"],//148
|
||||
cc.KEY["z"],//149
|
||||
cc.KEY["none"],//150
|
||||
cc.KEY["none"],//151
|
||||
cc.KEY["none"],//152
|
||||
cc.KEY["none"],//153
|
||||
cc.KEY["none"],//154
|
||||
cc.KEY["none"],//155
|
||||
cc.KEY["none"],//156
|
||||
cc.KEY["none"],//157
|
||||
cc.KEY["none"],//158
|
||||
cc.KEY["dpadLeft"],//159
|
||||
cc.KEY["dpadRight"],//160
|
||||
cc.KEY["dpadUp"],//161
|
||||
cc.KEY["dpadDown"],//162
|
||||
cc.KEY["dpadCenter"],//163
|
||||
cc.KEY["enter"],//164
|
||||
cc.KEY["none"]//165
|
||||
// html5 more key, these key can not trigge
|
||||
//'numdel'
|
||||
//select
|
||||
//dash
|
||||
];
|
||||
|
||||
if (cc.sys.os != cc.sys.OS_ANDROID)
|
||||
{
|
||||
jsbKeyArr[6] = cc.KEY["escape"];//6
|
||||
}
|
||||
|
||||
var parseKeyCode = function (keycode)
|
||||
{
|
||||
var keyIndex = jsbKeyArr.indexOf(keycode);
|
||||
var jsbKeyCode = keyIndex == -1 ? cc.KEY.none : keyIndex;
|
||||
return jsbKeyCode;
|
||||
}
|
||||
@@ -1,516 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/************************************************************
|
||||
*
|
||||
* Constructors with built in init function
|
||||
*
|
||||
************************************************************/
|
||||
|
||||
var _p;
|
||||
|
||||
/************************ Layers *************************/
|
||||
|
||||
var dummyCtor = function(){
|
||||
this.init();
|
||||
};
|
||||
|
||||
_p = cc.Layer.prototype;
|
||||
_p._ctor = function() {
|
||||
cc.Layer.prototype.init.call(this);
|
||||
};
|
||||
|
||||
|
||||
_p = cc.LayerColor.prototype;
|
||||
_p._ctor = function(color, w, h) {
|
||||
color = color || cc.color(0, 0, 0, 255);
|
||||
w = w === undefined ? cc.winSize.width : w;
|
||||
h = h === undefined ? cc.winSize.height : h;
|
||||
|
||||
cc.LayerColor.prototype.init.call(this, color, w, h);
|
||||
};
|
||||
|
||||
|
||||
_p = cc.LayerGradient.prototype;
|
||||
_p._ctor = function(start, end, v, colorStops) {
|
||||
start = start || cc.color(0,0,0,255);
|
||||
end = end || cc.color(0,0,0,255);
|
||||
v = v || cc.p(0, -1);
|
||||
|
||||
this.initWithColor(start, end, v);
|
||||
|
||||
if (colorStops instanceof Array) {
|
||||
cc.log('Warning: Color stops parameter is not supported in JSB.');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/************************ Sprite *************************/
|
||||
|
||||
_p = cc.Sprite.prototype;
|
||||
_p._ctor = function(fileName, rect) {
|
||||
if (fileName === undefined) {
|
||||
cc.Sprite.prototype.init.call(this);
|
||||
}
|
||||
else if (typeof(fileName) === 'string') {
|
||||
if (fileName[0] === '#') {
|
||||
//init with a sprite frame name
|
||||
var frameName = fileName.substr(1, fileName.length - 1);
|
||||
this.initWithSpriteFrameName(frameName);
|
||||
} else {
|
||||
// Create with filename and rect
|
||||
rect ? this.initWithFile(fileName, rect) : this.initWithFile(fileName);
|
||||
}
|
||||
}
|
||||
else if (typeof(fileName) === 'object') {
|
||||
if (fileName instanceof cc.Texture2D) {
|
||||
//init with texture and rect
|
||||
rect ? this.initWithTexture(fileName, rect) : this.initWithTexture(fileName);
|
||||
} else if (fileName instanceof cc.SpriteFrame) {
|
||||
//init with a sprite frame
|
||||
this.initWithSpriteFrame(fileName);
|
||||
} else if (fileName instanceof jsb.PolygonInfo) {
|
||||
//init with a polygon info
|
||||
this.initWithPolygon(fileName);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_p = cc.SpriteFrame.prototype;
|
||||
_p._ctor = function(filename, rect, rotated, offset, originalSize){
|
||||
if(originalSize !== undefined){
|
||||
if(filename instanceof cc.Texture2D)
|
||||
this.initWithTexture(filename, rect, rotated, offset, originalSize);
|
||||
else
|
||||
this.initWithTexture(filename, rect, rotated, offset, originalSize);
|
||||
}else if(rect !== undefined){
|
||||
if(filename instanceof cc.Texture2D)
|
||||
this.initWithTexture(filename, rect);
|
||||
else
|
||||
this.initWithTextureFilename(filename, rect);
|
||||
}
|
||||
};
|
||||
|
||||
/************************ motion-streak *************************/
|
||||
_p = cc.MotionStreak.prototype;
|
||||
_p._ctor = function(fade, minSeg, stroke, color, texture){
|
||||
if(texture !== undefined)
|
||||
this.initWithFade(fade, minSeg, stroke, color, texture);
|
||||
};
|
||||
|
||||
/************************ Particle *************************/
|
||||
_p = cc.ParticleBatchNode.prototype;
|
||||
_p._ctor = function(fileImage, capacity){
|
||||
capacity = capacity || cc.PARTICLE_DEFAULT_CAPACITY;
|
||||
if (typeof(fileImage) == 'string') {
|
||||
cc.ParticleBatchNode.prototype.init.call(this, fileImage, capacity);
|
||||
} else if (fileImage instanceof cc.Texture2D) {
|
||||
this.initWithTexture(fileImage, capacity);
|
||||
}
|
||||
};
|
||||
|
||||
_p = cc.ParticleSystem.prototype;
|
||||
_p._ctor = function(plistFile){
|
||||
if (!plistFile || typeof(plistFile) === 'number') {
|
||||
var ton = plistFile || 100;
|
||||
this.initWithTotalParticles(ton);
|
||||
} else if ( typeof plistFile === 'string') {
|
||||
this.initWithFile(plistFile);
|
||||
} else if(plistFile){
|
||||
this.initWithDictionary(plistFile);
|
||||
}
|
||||
};
|
||||
|
||||
cc.ParticleFire.prototype._ctor = dummyCtor;
|
||||
cc.ParticleFireworks.prototype._ctor = dummyCtor;
|
||||
cc.ParticleSun.prototype._ctor = dummyCtor;
|
||||
cc.ParticleGalaxy.prototype._ctor = dummyCtor;
|
||||
cc.ParticleMeteor.prototype._ctor = dummyCtor;
|
||||
cc.ParticleFlower.prototype._ctor = dummyCtor;
|
||||
cc.ParticleSpiral.prototype._ctor = dummyCtor;
|
||||
cc.ParticleExplosion.prototype._ctor = dummyCtor;
|
||||
cc.ParticleSmoke.prototype._ctor = dummyCtor;
|
||||
cc.ParticleRain.prototype._ctor = dummyCtor;
|
||||
cc.ParticleSnow.prototype._ctor = dummyCtor;
|
||||
|
||||
/************************ RenderTexture *************************/
|
||||
_p = cc.RenderTexture.prototype;
|
||||
_p._ctor = function(width, height, format, depthStencilFormat){
|
||||
if(width !== undefined && height !== undefined){
|
||||
format = format || cc.Texture2D.PIXEL_FORMAT_RGBA8888;
|
||||
depthStencilFormat = depthStencilFormat || 0;
|
||||
this.initWithWidthAndHeight(width, height, format, depthStencilFormat);
|
||||
}
|
||||
};
|
||||
|
||||
/************************ Tile Map *************************/
|
||||
_p = cc.TileMapAtlas.prototype;
|
||||
_p._ctor = function(tile, mapFile, tileWidth, tileHeight){
|
||||
if(tileHeight !== undefined)
|
||||
this.initWithTileFile(tile, mapFile, tileWidth, tileHeight);
|
||||
};
|
||||
|
||||
_p = cc.TMXLayer.prototype;
|
||||
_p._ctor = function(tilesetInfo, layerInfo, mapInfo){
|
||||
if(mapInfo !== undefined)
|
||||
this.initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo);
|
||||
};
|
||||
|
||||
_p = cc.TMXTiledMap.prototype;
|
||||
_p._ctor = function(tmxFile, resourcePath){
|
||||
if(resourcePath !== undefined){
|
||||
this.initWithXML(tmxFile,resourcePath);
|
||||
}else if(tmxFile !== undefined){
|
||||
this.initWithTMXFile(tmxFile);
|
||||
}
|
||||
};
|
||||
|
||||
_p = cc.TMXMapInfo.prototype;
|
||||
_p._ctor = function(tmxFile, resourcePath){
|
||||
if (resourcePath !== undefined) {
|
||||
this.initWithXML(tmxFile,resourcePath);
|
||||
}else if(tmxFile !== undefined){
|
||||
this.initWithTMXFile(tmxFile);
|
||||
}
|
||||
};
|
||||
|
||||
/************************ Actions *************************/
|
||||
|
||||
cc.Speed.prototype._ctor = function (action, speed) {
|
||||
speed !== undefined && this.initWithAction(action, speed);
|
||||
};
|
||||
cc.speed = cc.Speed.create = function (action, speed) {
|
||||
return new cc.Speed(action, speed);
|
||||
};
|
||||
|
||||
cc.CardinalSplineTo.prototype._ctor = cc.CardinalSplineBy.prototype._ctor = function(duration, points, tension) {
|
||||
tension !== undefined && this.initWithDuration(duration, points, tension);
|
||||
};
|
||||
|
||||
cc.CatmullRomTo.prototype._ctor = cc.CatmullRomBy.prototype._ctor = function(dt, points) {
|
||||
points !== undefined && this.initWithDuration(dt, points);
|
||||
};
|
||||
|
||||
var easeCtor = function(action) {
|
||||
action !== undefined && this.initWithAction(action);
|
||||
};
|
||||
|
||||
cc.ActionEase.prototype._ctor = easeCtor;
|
||||
cc.EaseExponentialIn.prototype._ctor = easeCtor;
|
||||
cc.EaseExponentialOut.prototype._ctor = easeCtor;
|
||||
cc.EaseExponentialInOut.prototype._ctor = easeCtor;
|
||||
cc.EaseSineIn.prototype._ctor = easeCtor;
|
||||
cc.EaseSineOut.prototype._ctor = easeCtor;
|
||||
cc.EaseSineInOut.prototype._ctor = easeCtor;
|
||||
cc.EaseBounce.prototype._ctor = easeCtor;
|
||||
cc.EaseBounceIn.prototype._ctor = easeCtor;
|
||||
cc.EaseBounceOut.prototype._ctor = easeCtor;
|
||||
cc.EaseBounceInOut.prototype._ctor = easeCtor;
|
||||
cc.EaseBackIn.prototype._ctor = easeCtor;
|
||||
cc.EaseBackOut.prototype._ctor = easeCtor;
|
||||
cc.EaseBackInOut.prototype._ctor = easeCtor;
|
||||
|
||||
var easeRateCtor = function(action, rate) {
|
||||
rate !== undefined && this.initWithAction(action, rate);
|
||||
};
|
||||
cc.EaseRateAction.prototype._ctor = easeRateCtor;
|
||||
cc.EaseIn.prototype._ctor = easeRateCtor;
|
||||
cc.EaseOut.prototype._ctor = easeRateCtor;
|
||||
cc.EaseInOut.prototype._ctor = easeRateCtor;
|
||||
|
||||
var easeElasticCtor = function(action, period) {
|
||||
if( action ) {
|
||||
period !== undefined ? this.initWithAction(action, period)
|
||||
: this.initWithAction(action);
|
||||
}
|
||||
};
|
||||
cc.EaseElastic.prototype._ctor = easeElasticCtor;
|
||||
cc.EaseElasticIn.prototype._ctor = easeElasticCtor;
|
||||
cc.EaseElasticOut.prototype._ctor = easeElasticCtor;
|
||||
cc.EaseElasticInOut.prototype._ctor = easeElasticCtor;
|
||||
|
||||
cc.RemoveSelf.prototype._ctor = function(isNeedCleanUp) {
|
||||
isNeedCleanUp !== undefined && cc.RemoveSelf.prototype.init.call(this, isNeedCleanUp);
|
||||
};
|
||||
|
||||
cc.FlipX.prototype._ctor = function(flip) {
|
||||
flip !== undefined && this.initWithFlipX(flip);
|
||||
};
|
||||
|
||||
cc.FlipY.prototype._ctor = function(flip) {
|
||||
flip !== undefined && this.initWithFlipY(flip);
|
||||
};
|
||||
|
||||
cc.Place.prototype._ctor = function(pos, y) {
|
||||
if (pos !== undefined) {
|
||||
if (pos.x !== undefined) {
|
||||
y = pos.y;
|
||||
pos = pos.x;
|
||||
}
|
||||
this.initWithPosition(cc.p(pos, y));
|
||||
}
|
||||
};
|
||||
|
||||
cc.CallFunc.prototype._ctor = function(selector, selectorTarget, data) {
|
||||
if (selector !== undefined) {
|
||||
if (selectorTarget === undefined) {
|
||||
this.initWithFunction(selector);
|
||||
}
|
||||
else {
|
||||
var callback = selector;
|
||||
if (data !== undefined) {
|
||||
callback = function (sender) {
|
||||
selector.call(this, sender, data);
|
||||
}
|
||||
}
|
||||
this.initWithFunction(callback, selectorTarget);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cc.ActionInterval.prototype._ctor = function(d) {
|
||||
d !== undefined && this.initWithDuration(d);
|
||||
};
|
||||
|
||||
cc.Sequence.prototype._ctor = function(tempArray) {
|
||||
var actions = (tempArray instanceof Array) ? tempArray : arguments;
|
||||
var last = actions.length - 1;
|
||||
if ((last >= 0) && (actions[last] == null))
|
||||
cc.log('parameters should not be ending with null in Javascript');
|
||||
|
||||
if (last >= 1) {
|
||||
var prev = actions[0];
|
||||
for (var i = 1; i < last; i++) {
|
||||
if (actions[i]) {
|
||||
prev = new cc.Sequence(prev, actions[i]);
|
||||
}
|
||||
}
|
||||
this.initWithTwoActions(prev, actions[last]);
|
||||
}
|
||||
};
|
||||
cc.sequence = cc.Sequence.create = function (tempArray) {
|
||||
var actions = (tempArray instanceof Array) ? tempArray : arguments;
|
||||
var last = actions.length - 1;
|
||||
if ((last >= 0) && (actions[last] == null))
|
||||
cc.log('parameters should not be ending with null in Javascript');
|
||||
|
||||
if (last >= 1) {
|
||||
var prev = actions[0];
|
||||
for (var i = 1; i < last; i++) {
|
||||
if (actions[i]) {
|
||||
prev = new cc.Sequence(prev, actions[i]);
|
||||
}
|
||||
}
|
||||
return new cc.Sequence(prev, actions[last]);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
cc.Repeat.prototype._ctor = function (action, times) {
|
||||
times !== undefined && this.initWithAction(action, times);
|
||||
};
|
||||
cc.repeat = cc.Repeat.create = function (action, times) {
|
||||
return new cc.Repeat(action, times);
|
||||
};
|
||||
|
||||
cc.RepeatForever.prototype._ctor = function (action) {
|
||||
action !== undefined && this.initWithAction(action);
|
||||
};
|
||||
cc.repeatForever = cc.RepeatForever.create = function (action) {
|
||||
return new cc.RepeatForever(action);
|
||||
};
|
||||
|
||||
cc.Spawn.prototype._ctor = function (tempArray) {
|
||||
var actions = (tempArray instanceof Array) ? tempArray : arguments;
|
||||
var last = actions.length - 1;
|
||||
if ((last >= 0) && (actions[last] == null))
|
||||
cc.log('parameters should not be ending with null in Javascript');
|
||||
|
||||
if (last >= 1) {
|
||||
var prev = actions[0];
|
||||
for (var i = 1; i < last; i++) {
|
||||
if (actions[i]) {
|
||||
prev = new cc.Spawn(prev, actions[i]);
|
||||
}
|
||||
}
|
||||
this.initWithTwoActions(prev, actions[last]);
|
||||
}
|
||||
};
|
||||
cc.spawn = cc.Spawn.create = function (tempArray) {
|
||||
var actions = (tempArray instanceof Array) ? tempArray : arguments;
|
||||
var last = actions.length - 1;
|
||||
if ((last >= 0) && (actions[last] == null))
|
||||
cc.log('parameters should not be ending with null in Javascript');
|
||||
|
||||
if (last >= 1) {
|
||||
var prev = actions[0];
|
||||
for (var i = 1; i < last; i++) {
|
||||
if (actions[i]) {
|
||||
prev = new cc.Spawn(prev, actions[i]);
|
||||
}
|
||||
}
|
||||
return new cc.Spawn(prev, actions[last]);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
cc.RotateTo.prototype._ctor = cc.RotateBy.prototype._ctor = function(duration, deltaAngleX, deltaAngleY) {
|
||||
if (deltaAngleX !== undefined) {
|
||||
if (deltaAngleY !== undefined)
|
||||
this.initWithDuration(duration, deltaAngleX, deltaAngleY);
|
||||
else
|
||||
this.initWithDuration(duration, deltaAngleX, deltaAngleX);
|
||||
}
|
||||
};
|
||||
|
||||
cc.MoveBy.prototype._ctor = cc.MoveTo.prototype._ctor = function(duration, pos, y) {
|
||||
if (pos !== undefined) {
|
||||
if(pos.x === undefined) {
|
||||
pos = cc.p(pos, y);
|
||||
}
|
||||
|
||||
this.initWithDuration(duration, pos);
|
||||
}
|
||||
};
|
||||
|
||||
cc.SkewTo.prototype._ctor = cc.SkewBy.prototype._ctor = function(t, sx, sy) {
|
||||
sy !== undefined && this.initWithDuration(t, sx, sy);
|
||||
};
|
||||
|
||||
cc.JumpBy.prototype._ctor = cc.JumpTo.prototype._ctor = function(duration, position, y, height, jumps) {
|
||||
if (height !== undefined) {
|
||||
if (jumps !== undefined) {
|
||||
position = cc.p(position, y);
|
||||
}
|
||||
else {
|
||||
jumps = height;
|
||||
height = y;
|
||||
}
|
||||
this.initWithDuration(duration, position, height, jumps);
|
||||
}
|
||||
};
|
||||
|
||||
cc.BezierBy.prototype._ctor = cc.BezierTo.prototype._ctor = function(t, c) {
|
||||
c !== undefined && this.initWithDuration(t, c);
|
||||
};
|
||||
|
||||
cc.ScaleTo.prototype._ctor = cc.ScaleBy.prototype._ctor = function(duration, sx, sy) {
|
||||
if (sx !== undefined) {
|
||||
if (sy !== undefined)
|
||||
this.initWithDuration(duration, sx, sy);
|
||||
else this.initWithDuration(duration, sx);
|
||||
}
|
||||
};
|
||||
|
||||
cc.Blink.prototype._ctor = function(duration, blinks) {
|
||||
blinks !== undefined && this.initWithDuration(duration, blinks);
|
||||
};
|
||||
|
||||
cc.FadeTo.prototype._ctor = function(duration, opacity) {
|
||||
opacity !== undefined && this.initWithDuration(duration, opacity);
|
||||
};
|
||||
|
||||
cc.FadeIn.prototype._ctor = function(duration) {
|
||||
duration !== undefined && this.initWithDuration(duration, 255);
|
||||
};
|
||||
|
||||
cc.FadeOut.prototype._ctor = function(duration) {
|
||||
duration !== undefined && this.initWithDuration(duration, 0);
|
||||
};
|
||||
|
||||
cc.TintTo.prototype._ctor = cc.TintBy.prototype._ctor = function(duration, red, green, blue) {
|
||||
blue !== undefined && this.initWithDuration(duration, red, green, blue);
|
||||
};
|
||||
|
||||
cc.DelayTime.prototype._ctor = function(duration) {
|
||||
duration !== undefined && this.initWithDuration(duration);
|
||||
};
|
||||
/*
|
||||
cc.ReverseTime.prototype._ctor = function(action) {
|
||||
action && this.initWithAction(action);
|
||||
};*/
|
||||
|
||||
cc.TargetedAction.prototype._ctor = function (target, action) {
|
||||
action && this.initWithTarget(target, action);
|
||||
};
|
||||
cc.targetedAction = cc.TargetedAction.create = function (target, action) {
|
||||
return new cc.TargetedAction(target, action);
|
||||
};
|
||||
|
||||
/************************ Nodes *************************/
|
||||
|
||||
cc.ClippingNode.prototype._ctor = function(stencil) {
|
||||
if(stencil != undefined)
|
||||
cc.ClippingNode.prototype.init.call(this, stencil);
|
||||
else
|
||||
cc.ClippingNode.prototype.init.call(this);
|
||||
};
|
||||
|
||||
cc.DrawNode.prototype._ctor = function() {
|
||||
cc.DrawNode.prototype.init.call(this);
|
||||
};
|
||||
|
||||
cc.LabelTTF.prototype._ctor = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
|
||||
this._flippedX = false;
|
||||
this._flippedY = false;
|
||||
this._renderLabel = this.getRenderLabel();
|
||||
if (text === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
text = text || '';
|
||||
if (fontName && fontName instanceof cc.FontDefinition) {
|
||||
this.initWithStringAndTextDefinition(text, fontName);
|
||||
}
|
||||
else {
|
||||
fontName = fontName || '';
|
||||
fontSize = fontSize || 16;
|
||||
dimensions = dimensions || cc.size(0,0);
|
||||
hAlignment = hAlignment === undefined ? cc.TEXT_ALIGNMENT_LEFT : hAlignment;
|
||||
vAlignment = vAlignment === undefined ? cc.VERTICAL_TEXT_ALIGNMENT_TOP : vAlignment;
|
||||
this.initWithString(text, fontName, fontSize, dimensions, hAlignment, vAlignment);
|
||||
}
|
||||
};
|
||||
|
||||
/************************ Other classes *************************/
|
||||
|
||||
cc.EventTouch.prototype._ctor = function(touches) {
|
||||
touches !== undefined && cc.EventTouch.prototype.setTouches.call(this, touches);
|
||||
};
|
||||
cc.Touch.prototype._ctor = function(x, y, id) {
|
||||
id !== undefined && cc.Touch.prototype.setTouchInfo.call(this, x, y, id);
|
||||
};
|
||||
|
||||
cc.GLProgram.prototype._ctor = function(vShaderFileName, fShaderFileName) {
|
||||
if(vShaderFileName !== undefined && fShaderFileName !== undefined){
|
||||
cc.GLProgram.prototype.init.call(this, vShaderFileName, fShaderFileName);
|
||||
cc.GLProgram.prototype.link.call(this);
|
||||
cc.GLProgram.prototype.updateUniforms.call(this);
|
||||
}
|
||||
};
|
||||
@@ -1,294 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
|
||||
// const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common");
|
||||
// const { RootActor } = require("devtools/server/actors/root");
|
||||
// const { ThreadActor } = require("devtools/server/actors/script");
|
||||
// const { DebuggerServer } = require("devtools/server/main");
|
||||
// const { TabSources } = require("devtools/server/actors/utils/TabSources");
|
||||
// const promise = require("promise");
|
||||
// const makeDebugger = require("devtools/server/actors/utils/make-debugger");
|
||||
|
||||
|
||||
let gTestGlobals = [];
|
||||
let needToSendNavigation = false;
|
||||
let testTab = null;
|
||||
|
||||
// A mock tab list, for use by tests. This simply presents each global in
|
||||
// gTestGlobals as a tab, and the list is fixed: it never calls its
|
||||
// onListChanged handler.
|
||||
//
|
||||
// As implemented now, we consult gTestGlobals when we're constructed, not
|
||||
// when we're iterated over, so tests have to add their globals before the
|
||||
// root actor is created.
|
||||
function TestTabList(aConnection) {
|
||||
this.conn = aConnection;
|
||||
|
||||
// An array of actors for each global added with
|
||||
// DebuggerServer.addTestGlobal.
|
||||
this._tabActors = [];
|
||||
|
||||
// A pool mapping those actors' names to the actors.
|
||||
this._tabActorPool = new ActorPool(aConnection);
|
||||
|
||||
for (let global of gTestGlobals) {
|
||||
let actor = new TestTabActor(aConnection, global);
|
||||
testTab = actor;
|
||||
actor.selected = false;
|
||||
this._tabActors.push(actor);
|
||||
this._tabActorPool.addActor(actor);
|
||||
}
|
||||
if (this._tabActors.length > 0) {
|
||||
this._tabActors[0].selected = true;
|
||||
}
|
||||
|
||||
aConnection.addActorPool(this._tabActorPool);
|
||||
}
|
||||
|
||||
TestTabList.prototype = {
|
||||
constructor: TestTabList,
|
||||
getList: function () {
|
||||
return Promise.resolve([...this._tabActors]);
|
||||
}
|
||||
};
|
||||
|
||||
function createRootActor(aConnection)
|
||||
{
|
||||
let root = new RootActor(aConnection, {
|
||||
tabList: new TestTabList(aConnection),
|
||||
globalActorFactories: DebuggerServer.globalActorFactories,
|
||||
});
|
||||
|
||||
// root.applicationType = "xpcshell-tests";
|
||||
return root;
|
||||
}
|
||||
|
||||
function TestTabActor(aConnection, aGlobal)
|
||||
{
|
||||
this.makeDebugger = function() {
|
||||
let dbg = new Debugger();
|
||||
dbg.addDebuggee(this._global);
|
||||
return dbg;
|
||||
};
|
||||
|
||||
this.conn = aConnection;
|
||||
this._global = aGlobal;
|
||||
this._global.wrappedJSObject = aGlobal;
|
||||
this.threadActor = new ThreadActor(this, this._global);
|
||||
this.conn.addActor(this.threadActor);
|
||||
this.consoleActor = new WebConsoleActor(this.conn, this);
|
||||
this.conn.addActor(this.consoleActor);
|
||||
this._attached = false;
|
||||
this._extraActors = {};
|
||||
// this.makeDebugger = makeDebugger.bind(null, {
|
||||
// findDebuggees: () => [this._global],
|
||||
// shouldAddNewGlobalAsDebuggee: g => g.hostAnnotations &&
|
||||
// g.hostAnnotations.type == "document" &&
|
||||
// g.hostAnnotations.element === this._global
|
||||
|
||||
// });
|
||||
}
|
||||
|
||||
TestTabActor.prototype = {
|
||||
constructor: TestTabActor,
|
||||
actorPrefix: "TestTabActor",
|
||||
|
||||
get window() {
|
||||
return this._global;
|
||||
},
|
||||
|
||||
get url() {
|
||||
// return "http://cocos2d-x.org";
|
||||
return "about:cehome";
|
||||
},
|
||||
|
||||
get sources() {
|
||||
if (!this._sources) {
|
||||
this._sources = new TabSources(this.threadActor);
|
||||
}
|
||||
return this._sources;
|
||||
},
|
||||
|
||||
form: function() {
|
||||
let response = { actor: this.actorID, title: "cocos project", 'consoleActor': this.consoleActor.actorID };
|
||||
|
||||
// Walk over tab actors added by extensions and add them to a new ActorPool.
|
||||
let actorPool = new ActorPool(this.conn);
|
||||
// this._createExtraActors(DebuggerServer.tabActorFactories, actorPool);
|
||||
if (!actorPool.isEmpty()) {
|
||||
this._tabActorPool = actorPool;
|
||||
this.conn.addActorPool(this._tabActorPool);
|
||||
}
|
||||
|
||||
// this._appendExtraActors(response);
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
onAttach: function(aRequest) {
|
||||
this._attached = true;
|
||||
|
||||
let response = { type: "tabAttached", threadActor: this.threadActor.actorID};
|
||||
// this._appendExtraActors(response);
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
onDetach: function(aRequest) {
|
||||
if (!this._attached) {
|
||||
return { "error":"wrongState" };
|
||||
}
|
||||
return { type: "detached" };
|
||||
},
|
||||
|
||||
onReload: function(aRequest) {
|
||||
this.sources.reset({ sourceMaps: true });
|
||||
this.threadActor.clearDebuggees();
|
||||
this.threadActor.dbg.addDebuggees();
|
||||
return {};
|
||||
},
|
||||
|
||||
removeActorByName: function(aName) {
|
||||
const actor = this._extraActors[aName];
|
||||
if (this._tabActorPool) {
|
||||
this._tabActorPool.removeActor(actor);
|
||||
}
|
||||
delete this._extraActors[aName];
|
||||
},
|
||||
|
||||
/* Support for DebuggerServer.addTabActor. */
|
||||
// _createExtraActors: createExtraActors,
|
||||
// _appendExtraActors: appendExtraActors
|
||||
};
|
||||
|
||||
TestTabActor.prototype.requestTypes = {
|
||||
"attach": TestTabActor.prototype.onAttach,
|
||||
"detach": TestTabActor.prototype.onDetach,
|
||||
"reload": TestTabActor.prototype.onReload
|
||||
};
|
||||
|
||||
let conn = null;
|
||||
let transport = null;
|
||||
|
||||
let incomingData = '';
|
||||
|
||||
this.processInput = function (inputstr) {
|
||||
if (!inputstr) {
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (inputstr === "connected")
|
||||
{
|
||||
DebuggerServer.init();
|
||||
DebuggerServer.setRootActor(createRootActor);
|
||||
conn = DebuggerServer._onConnection(transport);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
function extractPacket(inputString) {
|
||||
// Well this is ugly.
|
||||
let sep = inputString.indexOf(':');
|
||||
if (sep < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let count = inputString.substring(0, sep);
|
||||
// Check for a positive number with no garbage afterwards.
|
||||
if (!/^[0-9]+$/.exec(count)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
count = +count;
|
||||
if (inputString.length - (sep + 1) < count) {
|
||||
// Don't have a complete request yet.
|
||||
return null;
|
||||
}
|
||||
|
||||
// We have a complete request, pluck it out of the data and parse it.
|
||||
inputString = inputString.substring(sep + 1);
|
||||
let packet = inputString.substring(0, count);
|
||||
incomingData = inputString.substring(count);
|
||||
|
||||
// log(">>>>>>>>>> " + packet);
|
||||
return packet;
|
||||
}
|
||||
|
||||
function handlePacket(packet) {
|
||||
try {
|
||||
// packet = this._converter.ConvertToUnicode(packet);
|
||||
packet = DevToolsUtils.utf8to16(packet);
|
||||
var parsed = JSON.parse(packet);
|
||||
conn.onPacket(parsed);
|
||||
} catch(e) {
|
||||
let msg = "Error parsing incoming packet: " + packet + " (" + e + " - " + e.stack + ")";
|
||||
}
|
||||
}
|
||||
|
||||
incomingData += inputstr;
|
||||
var packet;
|
||||
while (packet = extractPacket(incomingData)) {
|
||||
handlePacket(packet);
|
||||
}
|
||||
};
|
||||
|
||||
this._prepareDebugger = function (global) {
|
||||
|
||||
this.globalDebuggee = global;
|
||||
cc = global.cc;
|
||||
// load all functions exported in DevToolsUtils to global(exports)
|
||||
// exports = global;
|
||||
|
||||
// SDK cods from https://hg.mozilla.org/mozilla-central/file/d1c70c20e7b5/addon-sdk/source/lib/sdk/
|
||||
require('script/debugger/sdk/heritage.js', 'debug');
|
||||
require('script/debugger/sdk/object.js', 'debug');
|
||||
require('script/debugger/sdk/event-core.js', 'debug');
|
||||
require('script/debugger/sdk/target.js', 'debug');
|
||||
|
||||
require('script/debugger/DevToolsUtils.js', 'debug');
|
||||
require('script/debugger/event-emitter.js', 'debug');
|
||||
require('script/debugger/actors/utils/ScriptStore.js', 'debug');
|
||||
require('script/debugger/actors/common.js', 'debug');
|
||||
require('script/debugger/transport.js', 'debug');
|
||||
require('script/debugger/main.js', 'debug');
|
||||
require('script/debugger/protocol.js', 'debug');
|
||||
require('script/debugger/actors/object.js', 'debug');
|
||||
require('script/debugger/actors/root.js', 'debug');
|
||||
require('script/debugger/actors/source.js', 'debug');
|
||||
require('script/debugger/actors/breakpoint.js', 'debug');
|
||||
require('script/debugger/actors/environment.js', 'debug');
|
||||
require('script/debugger/actors/frame.js', 'debug');
|
||||
require('script/debugger/actors/script.js', 'debug');
|
||||
require('script/debugger/actors/webconsole.js', 'debug')
|
||||
require('script/debugger/actors/utils/TabSources.js', 'debug');
|
||||
|
||||
//DebuggerServer.addTestGlobal = function(aGlobal) {
|
||||
gTestGlobals.push(global);
|
||||
//};
|
||||
|
||||
transport = new DebuggerTransport();
|
||||
};
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
var _proto = dragonBones.CCArmatureDisplay.prototype;
|
||||
_proto.animation = _proto.getAnimation;
|
||||
|
||||
var slotProto = dragonBones.Slot.prototype;
|
||||
cc.defineGetterSetter(slotProto, 'childArmature', slotProto.getChildArmature, slotProto.setChildArmature);
|
||||
|
||||
var armatureProto = dragonBones.Armature.prototype;
|
||||
cc.defineGetterSetter(armatureProto, 'animation', armatureProto.getAnimation, null);
|
||||
cc.defineGetterSetter(armatureProto, 'display', armatureProto.getDisplay, null);
|
||||
cc.defineGetterSetter(armatureProto, 'name', armatureProto.getName, null);
|
||||
|
||||
var animationStateProto = dragonBones.AnimationState.prototype;
|
||||
cc.defineGetterSetter(animationStateProto, 'name', animationStateProto.getName);
|
||||
|
||||
var slotProto = dragonBones.Slot.prototype;
|
||||
cc.defineGetterSetter(slotProto, 'display', slotProto.getDisplay);
|
||||
|
||||
var transformProto = dragonBones.Transform.prototype;
|
||||
cc.defineGetterSetter(transformProto, 'rotation', transformProto.getRotation, transformProto.setRotation);
|
||||
|
||||
dragonBones.EventObject.START = "start";
|
||||
dragonBones.EventObject.LOOP_COMPLETE = "loopComplete";
|
||||
dragonBones.EventObject.COMPLETE = "complete";
|
||||
dragonBones.EventObject.FADE_IN = "fadeIn";
|
||||
dragonBones.EventObject.FADE_IN_COMPLETE = "fadeInComplete";
|
||||
dragonBones.EventObject.FADE_OUT = "fadeOut";
|
||||
dragonBones.EventObject.FADE_OUT_COMPLETE = "fadeOutComplete";
|
||||
dragonBones.EventObject.FRAME_EVENT = "frameEvent";
|
||||
dragonBones.EventObject.SOUND_EVENT = "soundEvent";
|
||||
|
||||
dragonBones.DragonBones = {
|
||||
ANGLE_TO_RADIAN : Math.PI / 180,
|
||||
RADIAN_TO_ANGLE : 180 / Math.PI
|
||||
};
|
||||
@@ -1,389 +0,0 @@
|
||||
/*
|
||||
* OpenGL ES 2.0 / WebGL helper functions
|
||||
*
|
||||
* According to the WebGL specification ( For further info see:s http://www.khronos.org/registry/webgl/specs/latest/webgl.idl ),
|
||||
* the API should work with objects like WebGLTexture, WebGLBuffer, WebGLRenderBuffer, WebGLFramebuffer, WebGLProgram, WebGLShader.
|
||||
* OpenGL ES 2.0 doesn't have "objects" concepts: Instead it uses ids (GLints). So, these objects are emulated in this thin wrapper.
|
||||
*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
require('./jsb_opengl_constants');
|
||||
window.gl = window.gl || {};
|
||||
|
||||
gl.canvas = {
|
||||
clientWidth: window.innerWidth,
|
||||
clientHeight: window.innerHeight
|
||||
};
|
||||
|
||||
//
|
||||
// Create functions
|
||||
//
|
||||
gl.createTexture = function() {
|
||||
// Returns a "WebGLTexture" object
|
||||
var ret = gl._createTexture();
|
||||
return { texture_id:ret };
|
||||
};
|
||||
|
||||
gl.createBuffer = function() {
|
||||
// Returns a "WebGLBuffer" object
|
||||
var ret = gl._createBuffer();
|
||||
return { buffer_id:ret };
|
||||
};
|
||||
|
||||
gl.createRenderbuffer = function() {
|
||||
// Returns a "WebGLRenderBuffer" object
|
||||
var ret = gl._createRenderuffer();
|
||||
return { renderbuffer_id:ret};
|
||||
};
|
||||
|
||||
gl.createFramebuffer = function() {
|
||||
// Returns a "WebGLFramebuffer" object
|
||||
var ret = gl._createFramebuffer();
|
||||
return {framebuffer_id:ret};
|
||||
};
|
||||
|
||||
gl.createProgram = function() {
|
||||
// Returns a "WebGLProgram" object
|
||||
var ret = gl._createProgram();
|
||||
return {program_id:ret};
|
||||
};
|
||||
|
||||
gl.createShader = function(shaderType) {
|
||||
// Returns a "WebGLShader" object
|
||||
var ret = gl._createShader(shaderType);
|
||||
return {shader_id:ret};
|
||||
};
|
||||
|
||||
//
|
||||
// Delete Functions
|
||||
//
|
||||
gl.deleteTexture = function(texture) {
|
||||
var texture_id = texture.texture_id;
|
||||
// Accept numbers too. eg: gl.deleteTexture(0)
|
||||
if( typeof texture === 'number' )
|
||||
texture_id = texture;
|
||||
|
||||
gl._deleteTexture(texture_id);
|
||||
};
|
||||
|
||||
gl.deleteBuffer = function(buffer) {
|
||||
var buffer_id = buffer.buffer_id;
|
||||
// Accept numbers too. eg: gl.deleteBuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
|
||||
gl._deleteBuffer(buffer_id);
|
||||
};
|
||||
|
||||
gl.deleteRenderbuffer = function(buffer) {
|
||||
var buffer_id = buffer.renderbuffer_id;
|
||||
// Accept numbers too. eg: gl.deleteRenderbuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
|
||||
gl._deleteRenderbuffer(renderbuffer_id);
|
||||
};
|
||||
|
||||
gl.deleteFramebuffer = function(buffer) {
|
||||
var buffer_id = buffer.framebuffer_id;
|
||||
// Accept numbers too. eg: gl.deleteFramebuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
|
||||
gl._deleteFramebuffer(buffer_id);
|
||||
};
|
||||
|
||||
gl.deleteProgram = function(program) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.deleteShader(0)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
gl._deleteProgram(program_id);
|
||||
};
|
||||
|
||||
gl.deleteShader = function(shader) {
|
||||
var shader_id = shader.shader_id;
|
||||
// Accept numbers too. eg: gl.deleteShader(0)
|
||||
if( typeof shader === 'number' )
|
||||
shader_id = shader;
|
||||
|
||||
gl._deleteShader(shader_id);
|
||||
};
|
||||
|
||||
//
|
||||
// Bind Related
|
||||
//
|
||||
// void bindTexture(GLenum target, WebGLTexture? texture);
|
||||
gl.bindTexture = function(target, texture) {
|
||||
|
||||
var texture_id;
|
||||
// Accept numbers too. eg: gl.bindTexture(0)
|
||||
if( typeof texture === 'number' )
|
||||
texture_id = texture;
|
||||
else if( texture === null )
|
||||
texture_id = 0;
|
||||
else
|
||||
texture_id = texture.texture_id;
|
||||
|
||||
gl._bindTexture( target, texture_id );
|
||||
};
|
||||
|
||||
// void bindBuffer(GLenum target, WebGLBuffer? buffer);
|
||||
gl.bindBuffer = function(target, buffer) {
|
||||
var buffer_id;
|
||||
// Accept numbers too. eg: gl.bindBuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
else if( buffer === null )
|
||||
buffer_id = 0;
|
||||
else
|
||||
buffer_id = buffer.buffer_id;
|
||||
|
||||
gl._bindBuffer(target, buffer_id);
|
||||
};
|
||||
|
||||
// void bindRenderbuffer(GLenum target, WebGLRenderbuffer? renderbuffer);
|
||||
gl.bindRenderBuffer = function(target, buffer) {
|
||||
var buffer_id;
|
||||
|
||||
// Accept numbers too. eg: gl.bindRenderbuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
else if( buffer === null )
|
||||
buffer_id = 0;
|
||||
else
|
||||
buffer_id = buffer.buffer_id;
|
||||
|
||||
gl._bindRenderbuffer(target, buffer_id);
|
||||
};
|
||||
|
||||
// void bindFramebuffer(GLenum target, WebGLFramebuffer? framebuffer);
|
||||
gl.bindFramebuffer = function(target, buffer) {
|
||||
var buffer_id;
|
||||
|
||||
// Accept numbers too. eg: gl.bindFramebuffer(0)
|
||||
if( typeof buffer === 'number' )
|
||||
buffer_id = buffer;
|
||||
else if( buffer === null )
|
||||
buffer_id = 0;
|
||||
else
|
||||
buffer_id = buffer.buffer_id;
|
||||
|
||||
gl._bindFramebuffer(target, buffer_id);
|
||||
};
|
||||
|
||||
//
|
||||
// Uniform related
|
||||
//
|
||||
// any getUniform(WebGLProgram? program, WebGLUniformLocation? location);
|
||||
gl.getUniform = function(program, location) {
|
||||
var program_id;
|
||||
var location_id;
|
||||
|
||||
// Accept numbers too. eg: gl.bindFramebuffer(0)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
else
|
||||
program_id = program.program_id;
|
||||
|
||||
if( typeof location === 'number' )
|
||||
location_id = location;
|
||||
else
|
||||
location_id = location.location_id;
|
||||
|
||||
return gl._getUniform(program_id, location_id);
|
||||
};
|
||||
|
||||
// gl.uniformMatrix2fv = function(location, bool, matrix) {
|
||||
// gl._uniformMatrix2fv(program.program_id, bool, matrix);
|
||||
// };
|
||||
|
||||
// gl.uniformMatrix3fv = function(program, bool, matrix) {
|
||||
// gl._uniformMatrix3fv(program.program_id, bool, matrix);
|
||||
// };
|
||||
|
||||
// gl.uniformMatrix4fv = function(program, bool, matrix) {
|
||||
// gl._uniformMatrix4fv(program.program_id, bool, matrix);
|
||||
// };
|
||||
|
||||
|
||||
//
|
||||
// Shader related
|
||||
//
|
||||
// void compileShader(WebGLShader? shader);
|
||||
gl.compileShader = function(shader) {
|
||||
gl._compileShader( shader.shader_id);
|
||||
};
|
||||
|
||||
// void shaderSource(WebGLShader? shader, DOMString source);
|
||||
gl.shaderSource = function(shader, source) {
|
||||
gl._shaderSource(shader.shader_id, source);
|
||||
};
|
||||
|
||||
// any getShaderParameter(WebGLShader? shader, GLenum pname);
|
||||
gl.getShaderParameter = function(shader, e) {
|
||||
return gl._getShaderParameter(shader.shader_id,e);
|
||||
};
|
||||
|
||||
// DOMString? getShaderInfoLog(WebGLShader? shader);
|
||||
gl.getShaderInfoLog = function(shader) {
|
||||
return gl._getShaderInfoLog(shader.shader_id);
|
||||
};
|
||||
|
||||
// DOMString gl.getShaderSource(shader);
|
||||
gl.getShaderSource = function(shader) {
|
||||
return gl._getShaderSource(shader.shader_id);
|
||||
};
|
||||
|
||||
//
|
||||
// program related
|
||||
//
|
||||
// void attachShader(WebGLProgram? program, WebGLShader? shader);
|
||||
gl.attachShader = function(program, shader) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.attachShader(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
gl._attachShader(program_id, shader.shader_id);
|
||||
};
|
||||
|
||||
// void linkProgram(WebGLProgram? program);
|
||||
gl.linkProgram = function(program) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.linkProgram(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
gl._linkProgram(program_id);
|
||||
};
|
||||
|
||||
gl.bindAttribLocation = function(program, index, name) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.linkProgram(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
gl._bindAttribLocation(program_id, index, name);
|
||||
};
|
||||
|
||||
// any getProgramParameter(WebGLProgram? program, GLenum pname);
|
||||
gl.getProgramParameter = function(program, e) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getProgramParameter(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getProgramParameter(program_id, e);
|
||||
};
|
||||
|
||||
gl.getProgramInfoLog = function(program) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getProgramParameter(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getProgramInfoLog(program_id);
|
||||
};
|
||||
|
||||
// void useProgram(WebGLProgram? program);
|
||||
gl.useProgram = function(program) {
|
||||
var program_id;
|
||||
// Accept numbers too. eg: gl.useProgram(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
else
|
||||
program_id = program.program_id;
|
||||
|
||||
gl._useProgram (program_id);
|
||||
};
|
||||
|
||||
|
||||
// [WebGLHandlesContextLoss] GLint getAttribLocation(WebGLProgram? program, DOMString name);
|
||||
gl.getAttribLocation = function(program, name) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getAttribLocation(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getAttribLocation(program_id, name);
|
||||
};
|
||||
|
||||
// WebGLUniformLocation? getUniformLocation(WebGLProgram? program, DOMString name);
|
||||
gl.getUniformLocation = function(program, name) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getUniformLocation(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
// XXX: it should return an object, not an integer
|
||||
return gl._getUniformLocation(program_id,name);
|
||||
};
|
||||
|
||||
|
||||
// WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index);
|
||||
gl.getActiveAttrib = function(program, index) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getActiveAttrib(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getActiveAttrib(program_id, index);
|
||||
};
|
||||
|
||||
// WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index);
|
||||
gl.getActiveUniform = function(program, index) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getActiveUniform(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getActiveUniform(program_id, index);
|
||||
};
|
||||
|
||||
// sequence<WebGLShader>? getAttachedShaders(WebGLProgram? program);
|
||||
gl.getAttachedShaders = function(program) {
|
||||
var program_id = program.program_id;
|
||||
// Accept numbers too. eg: gl.getAttachedShaders(17)
|
||||
if( typeof program === 'number' )
|
||||
program_id = program;
|
||||
|
||||
return gl._getAttachedShaders(program_id);
|
||||
};
|
||||
|
||||
//
|
||||
// Extensions
|
||||
//
|
||||
// From the WebGL spec:
|
||||
// Returns an object if, and only if, name is an ASCII case-insensitive match [HTML] for one of the names returned from getSupportedExtensions;
|
||||
// otherwise, returns null. The object returned from getExtension contains any constants or functions provided by the extension.
|
||||
// A returned object may have no constants or functions if the extension does not define any, but a unique object must still be returned.
|
||||
// That object is used to indicate that the extension has been enabled.
|
||||
// XXX: The returned object must return the functions and constants.
|
||||
gl.getExtension = function(extension) {
|
||||
var extensions = gl.getSupportedExtensions();
|
||||
if( extensions.indexOf(extension) > -1 )
|
||||
return {};
|
||||
return null;
|
||||
};
|
||||
@@ -1,863 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
/*
|
||||
* AUTOGENERATED FILE. DO NOT EDIT IT
|
||||
* Generated by "generate_jsb.py -c opengl_jsb.ini" on 2013-03-18
|
||||
* Script version: v0.6
|
||||
*/
|
||||
|
||||
window.gl = window.gl || {};
|
||||
|
||||
gl.GCCSO_SHADER_BINARY_FJ = 0x9260;
|
||||
gl._3DC_XY_AMD = 0x87fa;
|
||||
gl._3DC_X_AMD = 0x87f9;
|
||||
gl.ACTIVE_ATTRIBUTES = 0x8b89;
|
||||
gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a;
|
||||
gl.ACTIVE_PROGRAM_EXT = 0x8259;
|
||||
gl.ACTIVE_TEXTURE = 0x84e0;
|
||||
gl.ACTIVE_UNIFORMS = 0x8b86;
|
||||
gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87;
|
||||
gl.ALIASED_LINE_WIDTH_RANGE = 0x846e;
|
||||
gl.ALIASED_POINT_SIZE_RANGE = 0x846d;
|
||||
gl.ALL_COMPLETED_NV = 0x84f2;
|
||||
gl.ALL_SHADER_BITS_EXT = 0xffffffff;
|
||||
gl.ALPHA = 0x1906;
|
||||
gl.ALPHA16F_EXT = 0x881c;
|
||||
gl.ALPHA32F_EXT = 0x8816;
|
||||
gl.ALPHA8_EXT = 0x803c;
|
||||
gl.ALPHA8_OES = 0x803c;
|
||||
gl.ALPHA_BITS = 0xd55;
|
||||
gl.ALPHA_TEST_FUNC_QCOM = 0xbc1;
|
||||
gl.ALPHA_TEST_QCOM = 0xbc0;
|
||||
gl.ALPHA_TEST_REF_QCOM = 0xbc2;
|
||||
gl.ALREADY_SIGNALED_APPLE = 0x911a;
|
||||
gl.ALWAYS = 0x207;
|
||||
gl.AMD_compressed_3DC_texture = 0x1;
|
||||
gl.AMD_compressed_ATC_texture = 0x1;
|
||||
gl.AMD_performance_monitor = 0x1;
|
||||
gl.AMD_program_binary_Z400 = 0x1;
|
||||
gl.ANGLE_depth_texture = 0x1;
|
||||
gl.ANGLE_framebuffer_blit = 0x1;
|
||||
gl.ANGLE_framebuffer_multisample = 0x1;
|
||||
gl.ANGLE_instanced_arrays = 0x1;
|
||||
gl.ANGLE_pack_reverse_row_order = 0x1;
|
||||
gl.ANGLE_program_binary = 0x1;
|
||||
gl.ANGLE_texture_compression_dxt3 = 0x1;
|
||||
gl.ANGLE_texture_compression_dxt5 = 0x1;
|
||||
gl.ANGLE_texture_usage = 0x1;
|
||||
gl.ANGLE_translated_shader_source = 0x1;
|
||||
gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a;
|
||||
gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f;
|
||||
gl.APPLE_copy_texture_levels = 0x1;
|
||||
gl.APPLE_framebuffer_multisample = 0x1;
|
||||
gl.APPLE_rgb_422 = 0x1;
|
||||
gl.APPLE_sync = 0x1;
|
||||
gl.APPLE_texture_format_BGRA8888 = 0x1;
|
||||
gl.APPLE_texture_max_level = 0x1;
|
||||
gl.ARM_mali_program_binary = 0x1;
|
||||
gl.ARM_mali_shader_binary = 0x1;
|
||||
gl.ARM_rgba8 = 0x1;
|
||||
gl.ARRAY_BUFFER = 0x8892;
|
||||
gl.ARRAY_BUFFER_BINDING = 0x8894;
|
||||
gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93;
|
||||
gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee;
|
||||
gl.ATC_RGB_AMD = 0x8c92;
|
||||
gl.ATTACHED_SHADERS = 0x8b85;
|
||||
gl.BACK = 0x405;
|
||||
gl.BGRA8_EXT = 0x93a1;
|
||||
gl.BGRA_EXT = 0x80e1;
|
||||
gl.BGRA_IMG = 0x80e1;
|
||||
gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0;
|
||||
gl.BLEND = 0xbe2;
|
||||
gl.BLEND_COLOR = 0x8005;
|
||||
gl.BLEND_DST_ALPHA = 0x80ca;
|
||||
gl.BLEND_DST_RGB = 0x80c8;
|
||||
gl.BLEND_EQUATION = 0x8009;
|
||||
gl.BLEND_EQUATION_ALPHA = 0x883d;
|
||||
gl.BLEND_EQUATION_RGB = 0x8009;
|
||||
gl.BLEND_SRC_ALPHA = 0x80cb;
|
||||
gl.BLEND_SRC_RGB = 0x80c9;
|
||||
gl.BLUE_BITS = 0xd54;
|
||||
gl.BOOL = 0x8b56;
|
||||
gl.BOOL_VEC2 = 0x8b57;
|
||||
gl.BOOL_VEC3 = 0x8b58;
|
||||
gl.BOOL_VEC4 = 0x8b59;
|
||||
gl.BUFFER = 0x82e0;
|
||||
gl.BUFFER_ACCESS_OES = 0x88bb;
|
||||
gl.BUFFER_MAPPED_OES = 0x88bc;
|
||||
gl.BUFFER_MAP_POINTER_OES = 0x88bd;
|
||||
gl.BUFFER_OBJECT_EXT = 0x9151;
|
||||
gl.BUFFER_SIZE = 0x8764;
|
||||
gl.BUFFER_USAGE = 0x8765;
|
||||
gl.BYTE = 0x1400;
|
||||
gl.CCW = 0x901;
|
||||
gl.CLAMP_TO_BORDER_NV = 0x812d;
|
||||
gl.CLAMP_TO_EDGE = 0x812f;
|
||||
gl.COLOR_ATTACHMENT0 = 0x8ce0;
|
||||
gl.COLOR_ATTACHMENT0_NV = 0x8ce0;
|
||||
gl.COLOR_ATTACHMENT10_NV = 0x8cea;
|
||||
gl.COLOR_ATTACHMENT11_NV = 0x8ceb;
|
||||
gl.COLOR_ATTACHMENT12_NV = 0x8cec;
|
||||
gl.COLOR_ATTACHMENT13_NV = 0x8ced;
|
||||
gl.COLOR_ATTACHMENT14_NV = 0x8cee;
|
||||
gl.COLOR_ATTACHMENT15_NV = 0x8cef;
|
||||
gl.COLOR_ATTACHMENT1_NV = 0x8ce1;
|
||||
gl.COLOR_ATTACHMENT2_NV = 0x8ce2;
|
||||
gl.COLOR_ATTACHMENT3_NV = 0x8ce3;
|
||||
gl.COLOR_ATTACHMENT4_NV = 0x8ce4;
|
||||
gl.COLOR_ATTACHMENT5_NV = 0x8ce5;
|
||||
gl.COLOR_ATTACHMENT6_NV = 0x8ce6;
|
||||
gl.COLOR_ATTACHMENT7_NV = 0x8ce7;
|
||||
gl.COLOR_ATTACHMENT8_NV = 0x8ce8;
|
||||
gl.COLOR_ATTACHMENT9_NV = 0x8ce9;
|
||||
gl.COLOR_ATTACHMENT_EXT = 0x90f0;
|
||||
gl.COLOR_BUFFER_BIT = 0x4000;
|
||||
gl.COLOR_BUFFER_BIT0_QCOM = 0x1;
|
||||
gl.COLOR_BUFFER_BIT1_QCOM = 0x2;
|
||||
gl.COLOR_BUFFER_BIT2_QCOM = 0x4;
|
||||
gl.COLOR_BUFFER_BIT3_QCOM = 0x8;
|
||||
gl.COLOR_BUFFER_BIT4_QCOM = 0x10;
|
||||
gl.COLOR_BUFFER_BIT5_QCOM = 0x20;
|
||||
gl.COLOR_BUFFER_BIT6_QCOM = 0x40;
|
||||
gl.COLOR_BUFFER_BIT7_QCOM = 0x80;
|
||||
gl.COLOR_CLEAR_VALUE = 0xc22;
|
||||
gl.COLOR_EXT = 0x1800;
|
||||
gl.COLOR_WRITEMASK = 0xc23;
|
||||
gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e;
|
||||
gl.COMPILE_STATUS = 0x8b81;
|
||||
gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb;
|
||||
gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8;
|
||||
gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9;
|
||||
gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba;
|
||||
gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc;
|
||||
gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd;
|
||||
gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0;
|
||||
gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1;
|
||||
gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2;
|
||||
gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3;
|
||||
gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4;
|
||||
gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5;
|
||||
gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6;
|
||||
gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7;
|
||||
gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03;
|
||||
gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137;
|
||||
gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02;
|
||||
gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138;
|
||||
gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1;
|
||||
gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2;
|
||||
gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3;
|
||||
gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01;
|
||||
gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00;
|
||||
gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6;
|
||||
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7;
|
||||
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d;
|
||||
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e;
|
||||
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f;
|
||||
gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c;
|
||||
gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3;
|
||||
gl.CONDITION_SATISFIED_APPLE = 0x911c;
|
||||
gl.CONSTANT_ALPHA = 0x8003;
|
||||
gl.CONSTANT_COLOR = 0x8001;
|
||||
gl.CONTEXT_FLAG_DEBUG_BIT = 0x2;
|
||||
gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3;
|
||||
gl.COUNTER_RANGE_AMD = 0x8bc1;
|
||||
gl.COUNTER_TYPE_AMD = 0x8bc0;
|
||||
gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5;
|
||||
gl.COVERAGE_ATTACHMENT_NV = 0x8ed2;
|
||||
gl.COVERAGE_AUTOMATIC_NV = 0x8ed7;
|
||||
gl.COVERAGE_BUFFERS_NV = 0x8ed3;
|
||||
gl.COVERAGE_BUFFER_BIT_NV = 0x8000;
|
||||
gl.COVERAGE_COMPONENT4_NV = 0x8ed1;
|
||||
gl.COVERAGE_COMPONENT_NV = 0x8ed0;
|
||||
gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6;
|
||||
gl.COVERAGE_SAMPLES_NV = 0x8ed4;
|
||||
gl.CPU_OPTIMIZED_QCOM = 0x8fb1;
|
||||
gl.CULL_FACE = 0xb44;
|
||||
gl.CULL_FACE_MODE = 0xb45;
|
||||
gl.CURRENT_PROGRAM = 0x8b8d;
|
||||
gl.CURRENT_QUERY_EXT = 0x8865;
|
||||
gl.CURRENT_VERTEX_ATTRIB = 0x8626;
|
||||
gl.CW = 0x900;
|
||||
gl.DEBUG_CALLBACK_FUNCTION = 0x8244;
|
||||
gl.DEBUG_CALLBACK_USER_PARAM = 0x8245;
|
||||
gl.DEBUG_GROUP_STACK_DEPTH = 0x826d;
|
||||
gl.DEBUG_LOGGED_MESSAGES = 0x9145;
|
||||
gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243;
|
||||
gl.DEBUG_OUTPUT = 0x92e0;
|
||||
gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242;
|
||||
gl.DEBUG_SEVERITY_HIGH = 0x9146;
|
||||
gl.DEBUG_SEVERITY_LOW = 0x9148;
|
||||
gl.DEBUG_SEVERITY_MEDIUM = 0x9147;
|
||||
gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b;
|
||||
gl.DEBUG_SOURCE_API = 0x8246;
|
||||
gl.DEBUG_SOURCE_APPLICATION = 0x824a;
|
||||
gl.DEBUG_SOURCE_OTHER = 0x824b;
|
||||
gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248;
|
||||
gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249;
|
||||
gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247;
|
||||
gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d;
|
||||
gl.DEBUG_TYPE_ERROR = 0x824c;
|
||||
gl.DEBUG_TYPE_MARKER = 0x8268;
|
||||
gl.DEBUG_TYPE_OTHER = 0x8251;
|
||||
gl.DEBUG_TYPE_PERFORMANCE = 0x8250;
|
||||
gl.DEBUG_TYPE_POP_GROUP = 0x826a;
|
||||
gl.DEBUG_TYPE_PORTABILITY = 0x824f;
|
||||
gl.DEBUG_TYPE_PUSH_GROUP = 0x8269;
|
||||
gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e;
|
||||
gl.DECR = 0x1e03;
|
||||
gl.DECR_WRAP = 0x8508;
|
||||
gl.DELETE_STATUS = 0x8b80;
|
||||
gl.DEPTH24_STENCIL8_OES = 0x88f0;
|
||||
gl.DEPTH_ATTACHMENT = 0x8d00;
|
||||
gl.DEPTH_BITS = 0xd56;
|
||||
gl.DEPTH_BUFFER_BIT = 0x100;
|
||||
gl.DEPTH_BUFFER_BIT0_QCOM = 0x100;
|
||||
gl.DEPTH_BUFFER_BIT1_QCOM = 0x200;
|
||||
gl.DEPTH_BUFFER_BIT2_QCOM = 0x400;
|
||||
gl.DEPTH_BUFFER_BIT3_QCOM = 0x800;
|
||||
gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000;
|
||||
gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000;
|
||||
gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000;
|
||||
gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000;
|
||||
gl.DEPTH_CLEAR_VALUE = 0xb73;
|
||||
gl.DEPTH_COMPONENT = 0x1902;
|
||||
gl.DEPTH_COMPONENT16 = 0x81a5;
|
||||
gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c;
|
||||
gl.DEPTH_COMPONENT16_OES = 0x81a5;
|
||||
gl.DEPTH_COMPONENT24_OES = 0x81a6;
|
||||
gl.DEPTH_COMPONENT32_OES = 0x81a7;
|
||||
gl.DEPTH_EXT = 0x1801;
|
||||
gl.DEPTH_FUNC = 0xb74;
|
||||
gl.DEPTH_RANGE = 0xb70;
|
||||
gl.DEPTH_STENCIL = 0x84f9;
|
||||
gl.DEPTH_STENCIL_OES = 0x84f9;
|
||||
gl.DEPTH_TEST = 0xb71;
|
||||
gl.DEPTH_WRITEMASK = 0xb72;
|
||||
gl.DITHER = 0xbd0;
|
||||
gl.DMP_shader_binary = 0x1;
|
||||
gl.DONT_CARE = 0x1100;
|
||||
gl.DRAW_BUFFER0_NV = 0x8825;
|
||||
gl.DRAW_BUFFER10_NV = 0x882f;
|
||||
gl.DRAW_BUFFER11_NV = 0x8830;
|
||||
gl.DRAW_BUFFER12_NV = 0x8831;
|
||||
gl.DRAW_BUFFER13_NV = 0x8832;
|
||||
gl.DRAW_BUFFER14_NV = 0x8833;
|
||||
gl.DRAW_BUFFER15_NV = 0x8834;
|
||||
gl.DRAW_BUFFER1_NV = 0x8826;
|
||||
gl.DRAW_BUFFER2_NV = 0x8827;
|
||||
gl.DRAW_BUFFER3_NV = 0x8828;
|
||||
gl.DRAW_BUFFER4_NV = 0x8829;
|
||||
gl.DRAW_BUFFER5_NV = 0x882a;
|
||||
gl.DRAW_BUFFER6_NV = 0x882b;
|
||||
gl.DRAW_BUFFER7_NV = 0x882c;
|
||||
gl.DRAW_BUFFER8_NV = 0x882d;
|
||||
gl.DRAW_BUFFER9_NV = 0x882e;
|
||||
gl.DRAW_BUFFER_EXT = 0xc01;
|
||||
gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9;
|
||||
gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9;
|
||||
gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6;
|
||||
gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6;
|
||||
gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6;
|
||||
gl.DRAW_FRAMEBUFFER_NV = 0x8ca9;
|
||||
gl.DST_ALPHA = 0x304;
|
||||
gl.DST_COLOR = 0x306;
|
||||
gl.DYNAMIC_DRAW = 0x88e8;
|
||||
gl.ELEMENT_ARRAY_BUFFER = 0x8893;
|
||||
gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
|
||||
gl.EQUAL = 0x202;
|
||||
gl.ES_VERSION_2_0 = 0x1;
|
||||
gl.ETC1_RGB8_OES = 0x8d64;
|
||||
gl.ETC1_SRGB8_NV = 0x88ee;
|
||||
gl.EXTENSIONS = 0x1f03;
|
||||
gl.EXT_blend_minmax = 0x1;
|
||||
gl.EXT_color_buffer_half_float = 0x1;
|
||||
gl.EXT_debug_label = 0x1;
|
||||
gl.EXT_debug_marker = 0x1;
|
||||
gl.EXT_discard_framebuffer = 0x1;
|
||||
gl.EXT_map_buffer_range = 0x1;
|
||||
gl.EXT_multi_draw_arrays = 0x1;
|
||||
gl.EXT_multisampled_render_to_texture = 0x1;
|
||||
gl.EXT_multiview_draw_buffers = 0x1;
|
||||
gl.EXT_occlusion_query_boolean = 0x1;
|
||||
gl.EXT_read_format_bgra = 0x1;
|
||||
gl.EXT_robustness = 0x1;
|
||||
gl.EXT_sRGB = 0x1;
|
||||
gl.EXT_separate_shader_objects = 0x1;
|
||||
gl.EXT_shader_framebuffer_fetch = 0x1;
|
||||
gl.EXT_shader_texture_lod = 0x1;
|
||||
gl.EXT_shadow_samplers = 0x1;
|
||||
gl.EXT_texture_compression_dxt1 = 0x1;
|
||||
gl.EXT_texture_filter_anisotropic = 0x1;
|
||||
gl.EXT_texture_format_BGRA8888 = 0x1;
|
||||
gl.EXT_texture_rg = 0x1;
|
||||
gl.EXT_texture_storage = 0x1;
|
||||
gl.EXT_texture_type_2_10_10_10_REV = 0x1;
|
||||
gl.EXT_unpack_subimage = 0x1;
|
||||
gl.FALSE = 0x0;
|
||||
gl.FASTEST = 0x1101;
|
||||
gl.FENCE_CONDITION_NV = 0x84f4;
|
||||
gl.FENCE_STATUS_NV = 0x84f3;
|
||||
gl.FIXED = 0x140c;
|
||||
gl.FJ_shader_binary_GCCSO = 0x1;
|
||||
gl.FLOAT = 0x1406;
|
||||
gl.FLOAT_MAT2 = 0x8b5a;
|
||||
gl.FLOAT_MAT3 = 0x8b5b;
|
||||
gl.FLOAT_MAT4 = 0x8b5c;
|
||||
gl.FLOAT_VEC2 = 0x8b50;
|
||||
gl.FLOAT_VEC3 = 0x8b51;
|
||||
gl.FLOAT_VEC4 = 0x8b52;
|
||||
gl.FRAGMENT_SHADER = 0x8b30;
|
||||
gl.FRAGMENT_SHADER_BIT_EXT = 0x2;
|
||||
gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b;
|
||||
gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52;
|
||||
gl.FRAMEBUFFER = 0x8d40;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2;
|
||||
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c;
|
||||
gl.FRAMEBUFFER_BINDING = 0x8ca6;
|
||||
gl.FRAMEBUFFER_COMPLETE = 0x8cd5;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134;
|
||||
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56;
|
||||
gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219;
|
||||
gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd;
|
||||
gl.FRONT = 0x404;
|
||||
gl.FRONT_AND_BACK = 0x408;
|
||||
gl.FRONT_FACE = 0xb46;
|
||||
gl.FUNC_ADD = 0x8006;
|
||||
gl.FUNC_REVERSE_SUBTRACT = 0x800b;
|
||||
gl.FUNC_SUBTRACT = 0x800a;
|
||||
gl.GENERATE_MIPMAP_HINT = 0x8192;
|
||||
gl.GEQUAL = 0x206;
|
||||
gl.GPU_OPTIMIZED_QCOM = 0x8fb2;
|
||||
gl.GREATER = 0x204;
|
||||
gl.GREEN_BITS = 0xd53;
|
||||
gl.GUILTY_CONTEXT_RESET_EXT = 0x8253;
|
||||
gl.HALF_FLOAT_OES = 0x8d61;
|
||||
gl.HIGH_FLOAT = 0x8df2;
|
||||
gl.HIGH_INT = 0x8df5;
|
||||
gl.IMG_multisampled_render_to_texture = 0x1;
|
||||
gl.IMG_program_binary = 0x1;
|
||||
gl.IMG_read_format = 0x1;
|
||||
gl.IMG_shader_binary = 0x1;
|
||||
gl.IMG_texture_compression_pvrtc = 0x1;
|
||||
gl.IMG_texture_compression_pvrtc2 = 0x1;
|
||||
gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b;
|
||||
gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a;
|
||||
gl.INCR = 0x1e02;
|
||||
gl.INCR_WRAP = 0x8507;
|
||||
gl.INFO_LOG_LENGTH = 0x8b84;
|
||||
gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254;
|
||||
gl.INT = 0x1404;
|
||||
gl.INT_10_10_10_2_OES = 0x8df7;
|
||||
gl.INT_VEC2 = 0x8b53;
|
||||
gl.INT_VEC3 = 0x8b54;
|
||||
gl.INT_VEC4 = 0x8b55;
|
||||
gl.INVALID_ENUM = 0x500;
|
||||
gl.INVALID_FRAMEBUFFER_OPERATION = 0x506;
|
||||
gl.INVALID_OPERATION = 0x502;
|
||||
gl.INVALID_VALUE = 0x501;
|
||||
gl.INVERT = 0x150a;
|
||||
gl.KEEP = 0x1e00;
|
||||
gl.KHR_debug = 0x1;
|
||||
gl.KHR_texture_compression_astc_ldr = 0x1;
|
||||
gl.LEFT = 0x0406;
|
||||
gl.LEQUAL = 0x203;
|
||||
gl.LESS = 0x201;
|
||||
gl.LINEAR = 0x2601;
|
||||
gl.LINEAR_MIPMAP_LINEAR = 0x2703;
|
||||
gl.LINEAR_MIPMAP_NEAREST = 0x2701;
|
||||
gl.LINES = 0x1;
|
||||
gl.LINE_LOOP = 0x2;
|
||||
gl.LINE_STRIP = 0x3;
|
||||
gl.LINE_WIDTH = 0xb21;
|
||||
gl.LINK_STATUS = 0x8b82;
|
||||
gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252;
|
||||
gl.LOW_FLOAT = 0x8df0;
|
||||
gl.LOW_INT = 0x8df3;
|
||||
gl.LUMINANCE = 0x1909;
|
||||
gl.LUMINANCE16F_EXT = 0x881e;
|
||||
gl.LUMINANCE32F_EXT = 0x8818;
|
||||
gl.LUMINANCE4_ALPHA4_OES = 0x8043;
|
||||
gl.LUMINANCE8_ALPHA8_EXT = 0x8045;
|
||||
gl.LUMINANCE8_ALPHA8_OES = 0x8045;
|
||||
gl.LUMINANCE8_EXT = 0x8040;
|
||||
gl.LUMINANCE8_OES = 0x8040;
|
||||
gl.LUMINANCE_ALPHA = 0x190a;
|
||||
gl.LUMINANCE_ALPHA16F_EXT = 0x881f;
|
||||
gl.LUMINANCE_ALPHA32F_EXT = 0x8819;
|
||||
gl.MALI_PROGRAM_BINARY_ARM = 0x8f61;
|
||||
gl.MALI_SHADER_BINARY_ARM = 0x8f60;
|
||||
gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10;
|
||||
gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8;
|
||||
gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4;
|
||||
gl.MAP_READ_BIT_EXT = 0x1;
|
||||
gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20;
|
||||
gl.MAP_WRITE_BIT_EXT = 0x2;
|
||||
gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073;
|
||||
gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf;
|
||||
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d;
|
||||
gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c;
|
||||
gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c;
|
||||
gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144;
|
||||
gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143;
|
||||
gl.MAX_DRAW_BUFFERS_NV = 0x8824;
|
||||
gl.MAX_EXT = 0x8008;
|
||||
gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd;
|
||||
gl.MAX_LABEL_LENGTH = 0x82e8;
|
||||
gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2;
|
||||
gl.MAX_RENDERBUFFER_SIZE = 0x84e8;
|
||||
gl.MAX_SAMPLES_ANGLE = 0x8d57;
|
||||
gl.MAX_SAMPLES_APPLE = 0x8d57;
|
||||
gl.MAX_SAMPLES_EXT = 0x8d57;
|
||||
gl.MAX_SAMPLES_IMG = 0x9135;
|
||||
gl.MAX_SAMPLES_NV = 0x8d57;
|
||||
gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111;
|
||||
gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872;
|
||||
gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff;
|
||||
gl.MAX_TEXTURE_SIZE = 0xd33;
|
||||
gl.MAX_VARYING_VECTORS = 0x8dfc;
|
||||
gl.MAX_VERTEX_ATTRIBS = 0x8869;
|
||||
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c;
|
||||
gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb;
|
||||
gl.MAX_VIEWPORT_DIMS = 0xd3a;
|
||||
gl.MEDIUM_FLOAT = 0x8df1;
|
||||
gl.MEDIUM_INT = 0x8df4;
|
||||
gl.MIN_EXT = 0x8007;
|
||||
gl.MIRRORED_REPEAT = 0x8370;
|
||||
gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000;
|
||||
gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000;
|
||||
gl.MULTIVIEW_EXT = 0x90f1;
|
||||
gl.NEAREST = 0x2600;
|
||||
gl.NEAREST_MIPMAP_LINEAR = 0x2702;
|
||||
gl.NEAREST_MIPMAP_NEAREST = 0x2700;
|
||||
gl.NEVER = 0x200;
|
||||
gl.NICEST = 0x1102;
|
||||
gl.NONE = 0x0;
|
||||
gl.NOTEQUAL = 0x205;
|
||||
gl.NO_ERROR = 0x0;
|
||||
gl.NO_RESET_NOTIFICATION_EXT = 0x8261;
|
||||
gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2;
|
||||
gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe;
|
||||
gl.NUM_SHADER_BINARY_FORMATS = 0x8df9;
|
||||
gl.NV_coverage_sample = 0x1;
|
||||
gl.NV_depth_nonlinear = 0x1;
|
||||
gl.NV_draw_buffers = 0x1;
|
||||
gl.NV_draw_instanced = 0x1;
|
||||
gl.NV_fbo_color_attachments = 0x1;
|
||||
gl.NV_fence = 0x1;
|
||||
gl.NV_framebuffer_blit = 0x1;
|
||||
gl.NV_framebuffer_multisample = 0x1;
|
||||
gl.NV_generate_mipmap_sRGB = 0x1;
|
||||
gl.NV_instanced_arrays = 0x1;
|
||||
gl.NV_read_buffer = 0x1;
|
||||
gl.NV_read_buffer_front = 0x1;
|
||||
gl.NV_read_depth = 0x1;
|
||||
gl.NV_read_depth_stencil = 0x1;
|
||||
gl.NV_read_stencil = 0x1;
|
||||
gl.NV_sRGB_formats = 0x1;
|
||||
gl.NV_shadow_samplers_array = 0x1;
|
||||
gl.NV_shadow_samplers_cube = 0x1;
|
||||
gl.NV_texture_border_clamp = 0x1;
|
||||
gl.NV_texture_compression_s3tc_update = 0x1;
|
||||
gl.NV_texture_npot_2D_mipmap = 0x1;
|
||||
gl.OBJECT_TYPE_APPLE = 0x9112;
|
||||
gl.OES_EGL_image = 0x1;
|
||||
gl.OES_EGL_image_external = 0x1;
|
||||
gl.OES_compressed_ETC1_RGB8_texture = 0x1;
|
||||
gl.OES_compressed_paletted_texture = 0x1;
|
||||
gl.OES_depth24 = 0x1;
|
||||
gl.OES_depth32 = 0x1;
|
||||
gl.OES_depth_texture = 0x1;
|
||||
gl.OES_element_index_uint = 0x1;
|
||||
gl.OES_fbo_render_mipmap = 0x1;
|
||||
gl.OES_fragment_precision_high = 0x1;
|
||||
gl.OES_get_program_binary = 0x1;
|
||||
gl.OES_mapbuffer = 0x1;
|
||||
gl.OES_packed_depth_stencil = 0x1;
|
||||
gl.OES_required_internalformat = 0x1;
|
||||
gl.OES_rgb8_rgba8 = 0x1;
|
||||
gl.OES_standard_derivatives = 0x1;
|
||||
gl.OES_stencil1 = 0x1;
|
||||
gl.OES_stencil4 = 0x1;
|
||||
gl.OES_surfaceless_context = 0x1;
|
||||
gl.OES_texture_3D = 0x1;
|
||||
gl.OES_texture_float = 0x1;
|
||||
gl.OES_texture_float_linear = 0x1;
|
||||
gl.OES_texture_half_float = 0x1;
|
||||
gl.OES_texture_half_float_linear = 0x1;
|
||||
gl.OES_texture_npot = 0x1;
|
||||
gl.OES_vertex_array_object = 0x1;
|
||||
gl.OES_vertex_half_float = 0x1;
|
||||
gl.OES_vertex_type_10_10_10_2 = 0x1;
|
||||
gl.ONE = 0x1;
|
||||
gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004;
|
||||
gl.ONE_MINUS_CONSTANT_COLOR = 0x8002;
|
||||
gl.ONE_MINUS_DST_ALPHA = 0x305;
|
||||
gl.ONE_MINUS_DST_COLOR = 0x307;
|
||||
gl.ONE_MINUS_SRC_ALPHA = 0x303;
|
||||
gl.ONE_MINUS_SRC_COLOR = 0x301;
|
||||
gl.OUT_OF_MEMORY = 0x505;
|
||||
gl.PACK_ALIGNMENT = 0xd05;
|
||||
gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4;
|
||||
gl.PALETTE4_R5_G6_B5_OES = 0x8b92;
|
||||
gl.PALETTE4_RGB5_A1_OES = 0x8b94;
|
||||
gl.PALETTE4_RGB8_OES = 0x8b90;
|
||||
gl.PALETTE4_RGBA4_OES = 0x8b93;
|
||||
gl.PALETTE4_RGBA8_OES = 0x8b91;
|
||||
gl.PALETTE8_R5_G6_B5_OES = 0x8b97;
|
||||
gl.PALETTE8_RGB5_A1_OES = 0x8b99;
|
||||
gl.PALETTE8_RGB8_OES = 0x8b95;
|
||||
gl.PALETTE8_RGBA4_OES = 0x8b98;
|
||||
gl.PALETTE8_RGBA8_OES = 0x8b96;
|
||||
gl.PERCENTAGE_AMD = 0x8bc3;
|
||||
gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0;
|
||||
gl.PERFMON_RESULT_AMD = 0x8bc6;
|
||||
gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4;
|
||||
gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5;
|
||||
gl.POINTS = 0x0;
|
||||
gl.POLYGON_OFFSET_FACTOR = 0x8038;
|
||||
gl.POLYGON_OFFSET_FILL = 0x8037;
|
||||
gl.POLYGON_OFFSET_UNITS = 0x2a00;
|
||||
gl.PROGRAM = 0x82e2;
|
||||
gl.PROGRAM_BINARY_ANGLE = 0x93a6;
|
||||
gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff;
|
||||
gl.PROGRAM_BINARY_LENGTH_OES = 0x8741;
|
||||
gl.PROGRAM_OBJECT_EXT = 0x8b40;
|
||||
gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a;
|
||||
gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f;
|
||||
gl.PROGRAM_SEPARABLE_EXT = 0x8258;
|
||||
gl.QCOM_alpha_test = 0x1;
|
||||
gl.QCOM_binning_control = 0x1;
|
||||
gl.QCOM_driver_control = 0x1;
|
||||
gl.QCOM_extended_get = 0x1;
|
||||
gl.QCOM_extended_get2 = 0x1;
|
||||
gl.QCOM_perfmon_global_mode = 0x1;
|
||||
gl.QCOM_tiled_rendering = 0x1;
|
||||
gl.QCOM_writeonly_rendering = 0x1;
|
||||
gl.QUERY = 0x82e3;
|
||||
gl.QUERY_OBJECT_EXT = 0x9153;
|
||||
gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867;
|
||||
gl.QUERY_RESULT_EXT = 0x8866;
|
||||
gl.R16F_EXT = 0x822d;
|
||||
gl.R32F_EXT = 0x822e;
|
||||
gl.R8_EXT = 0x8229;
|
||||
gl.READ_BUFFER_EXT = 0xc02;
|
||||
gl.READ_BUFFER_NV = 0xc02;
|
||||
gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8;
|
||||
gl.READ_FRAMEBUFFER_APPLE = 0x8ca8;
|
||||
gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa;
|
||||
gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa;
|
||||
gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa;
|
||||
gl.READ_FRAMEBUFFER_NV = 0x8ca8;
|
||||
gl.RED_BITS = 0xd52;
|
||||
gl.RED_EXT = 0x1903;
|
||||
gl.RENDERBUFFER = 0x8d41;
|
||||
gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53;
|
||||
gl.RENDERBUFFER_BINDING = 0x8ca7;
|
||||
gl.RENDERBUFFER_BLUE_SIZE = 0x8d52;
|
||||
gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54;
|
||||
gl.RENDERBUFFER_GREEN_SIZE = 0x8d51;
|
||||
gl.RENDERBUFFER_HEIGHT = 0x8d43;
|
||||
gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44;
|
||||
gl.RENDERBUFFER_RED_SIZE = 0x8d50;
|
||||
gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab;
|
||||
gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab;
|
||||
gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab;
|
||||
gl.RENDERBUFFER_SAMPLES_IMG = 0x9133;
|
||||
gl.RENDERBUFFER_SAMPLES_NV = 0x8cab;
|
||||
gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55;
|
||||
gl.RENDERBUFFER_WIDTH = 0x8d42;
|
||||
gl.RENDERER = 0x1f01;
|
||||
gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3;
|
||||
gl.REPEAT = 0x2901;
|
||||
gl.REPLACE = 0x1e01;
|
||||
gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68;
|
||||
gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256;
|
||||
gl.RG16F_EXT = 0x822f;
|
||||
gl.RG32F_EXT = 0x8230;
|
||||
gl.RG8_EXT = 0x822b;
|
||||
gl.RGB = 0x1907;
|
||||
gl.RGB10_A2_EXT = 0x8059;
|
||||
gl.RGB10_EXT = 0x8052;
|
||||
gl.RGB16F_EXT = 0x881b;
|
||||
gl.RGB32F_EXT = 0x8815;
|
||||
gl.RGB565 = 0x8d62;
|
||||
gl.RGB565_OES = 0x8d62;
|
||||
gl.RGB5_A1 = 0x8057;
|
||||
gl.RGB5_A1_OES = 0x8057;
|
||||
gl.RGB8_OES = 0x8051;
|
||||
gl.RGBA = 0x1908;
|
||||
gl.RGBA16F_EXT = 0x881a;
|
||||
gl.RGBA32F_EXT = 0x8814;
|
||||
gl.RGBA4 = 0x8056;
|
||||
gl.RGBA4_OES = 0x8056;
|
||||
gl.RGBA8_OES = 0x8058;
|
||||
gl.RGB_422_APPLE = 0x8a1f;
|
||||
gl.RG_EXT = 0x8227;
|
||||
gl.RIGHT = 0x0407;
|
||||
gl.SAMPLER = 0x82e6;
|
||||
gl.SAMPLER_2D = 0x8b5e;
|
||||
gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4;
|
||||
gl.SAMPLER_2D_SHADOW_EXT = 0x8b62;
|
||||
gl.SAMPLER_3D_OES = 0x8b5f;
|
||||
gl.SAMPLER_CUBE = 0x8b60;
|
||||
gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5;
|
||||
gl.SAMPLER_EXTERNAL_OES = 0x8d66;
|
||||
gl.SAMPLES = 0x80a9;
|
||||
gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e;
|
||||
gl.SAMPLE_BUFFERS = 0x80a8;
|
||||
gl.SAMPLE_COVERAGE = 0x80a0;
|
||||
gl.SAMPLE_COVERAGE_INVERT = 0x80ab;
|
||||
gl.SAMPLE_COVERAGE_VALUE = 0x80aa;
|
||||
gl.SCISSOR_BOX = 0xc10;
|
||||
gl.SCISSOR_TEST = 0xc11;
|
||||
gl.SGX_BINARY_IMG = 0x8c0a;
|
||||
gl.SGX_PROGRAM_BINARY_IMG = 0x9130;
|
||||
gl.SHADER = 0x82e1;
|
||||
gl.SHADER_BINARY_DMP = 0x9250;
|
||||
gl.SHADER_BINARY_FORMATS = 0x8df8;
|
||||
gl.SHADER_BINARY_VIV = 0x8fc4;
|
||||
gl.SHADER_COMPILER = 0x8dfa;
|
||||
gl.SHADER_OBJECT_EXT = 0x8b48;
|
||||
gl.SHADER_SOURCE_LENGTH = 0x8b88;
|
||||
gl.SHADER_TYPE = 0x8b4f;
|
||||
gl.SHADING_LANGUAGE_VERSION = 0x8b8c;
|
||||
gl.SHORT = 0x1402;
|
||||
gl.SIGNALED_APPLE = 0x9119;
|
||||
gl.SLUMINANCE8_ALPHA8_NV = 0x8c45;
|
||||
gl.SLUMINANCE8_NV = 0x8c47;
|
||||
gl.SLUMINANCE_ALPHA_NV = 0x8c44;
|
||||
gl.SLUMINANCE_NV = 0x8c46;
|
||||
gl.SRC_ALPHA = 0x302;
|
||||
gl.SRC_ALPHA_SATURATE = 0x308;
|
||||
gl.SRC_COLOR = 0x300;
|
||||
gl.SRGB8_ALPHA8_EXT = 0x8c43;
|
||||
gl.SRGB8_NV = 0x8c41;
|
||||
gl.SRGB_ALPHA_EXT = 0x8c42;
|
||||
gl.SRGB_EXT = 0x8c40;
|
||||
gl.STACK_OVERFLOW = 0x503;
|
||||
gl.STACK_UNDERFLOW = 0x504;
|
||||
gl.STATE_RESTORE = 0x8bdc;
|
||||
gl.STATIC_DRAW = 0x88e4;
|
||||
gl.STENCIL_ATTACHMENT = 0x8d20;
|
||||
gl.STENCIL_BACK_FAIL = 0x8801;
|
||||
gl.STENCIL_BACK_FUNC = 0x8800;
|
||||
gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
|
||||
gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
|
||||
gl.STENCIL_BACK_REF = 0x8ca3;
|
||||
gl.STENCIL_BACK_VALUE_MASK = 0x8ca4;
|
||||
gl.STENCIL_BACK_WRITEMASK = 0x8ca5;
|
||||
gl.STENCIL_BITS = 0xd57;
|
||||
gl.STENCIL_BUFFER_BIT = 0x400;
|
||||
gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000;
|
||||
gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000;
|
||||
gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000;
|
||||
gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000;
|
||||
gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000;
|
||||
gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000;
|
||||
gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000;
|
||||
gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000;
|
||||
gl.STENCIL_CLEAR_VALUE = 0xb91;
|
||||
gl.STENCIL_EXT = 0x1802;
|
||||
gl.STENCIL_FAIL = 0xb94;
|
||||
gl.STENCIL_FUNC = 0xb92;
|
||||
gl.STENCIL_INDEX1_OES = 0x8d46;
|
||||
gl.STENCIL_INDEX4_OES = 0x8d47;
|
||||
gl.STENCIL_INDEX8 = 0x8d48;
|
||||
gl.STENCIL_PASS_DEPTH_FAIL = 0xb95;
|
||||
gl.STENCIL_PASS_DEPTH_PASS = 0xb96;
|
||||
gl.STENCIL_REF = 0xb97;
|
||||
gl.STENCIL_TEST = 0xb90;
|
||||
gl.STENCIL_VALUE_MASK = 0xb93;
|
||||
gl.STENCIL_WRITEMASK = 0xb98;
|
||||
gl.STREAM_DRAW = 0x88e0;
|
||||
gl.SUBPIXEL_BITS = 0xd50;
|
||||
gl.SYNC_CONDITION_APPLE = 0x9113;
|
||||
gl.SYNC_FENCE_APPLE = 0x9116;
|
||||
gl.SYNC_FLAGS_APPLE = 0x9115;
|
||||
gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1;
|
||||
gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117;
|
||||
gl.SYNC_OBJECT_APPLE = 0x8a53;
|
||||
gl.SYNC_STATUS_APPLE = 0x9114;
|
||||
gl.TEXTURE = 0x1702;
|
||||
gl.TEXTURE0 = 0x84c0;
|
||||
gl.TEXTURE1 = 0x84c1;
|
||||
gl.TEXTURE10 = 0x84ca;
|
||||
gl.TEXTURE11 = 0x84cb;
|
||||
gl.TEXTURE12 = 0x84cc;
|
||||
gl.TEXTURE13 = 0x84cd;
|
||||
gl.TEXTURE14 = 0x84ce;
|
||||
gl.TEXTURE15 = 0x84cf;
|
||||
gl.TEXTURE16 = 0x84d0;
|
||||
gl.TEXTURE17 = 0x84d1;
|
||||
gl.TEXTURE18 = 0x84d2;
|
||||
gl.TEXTURE19 = 0x84d3;
|
||||
gl.TEXTURE2 = 0x84c2;
|
||||
gl.TEXTURE20 = 0x84d4;
|
||||
gl.TEXTURE21 = 0x84d5;
|
||||
gl.TEXTURE22 = 0x84d6;
|
||||
gl.TEXTURE23 = 0x84d7;
|
||||
gl.TEXTURE24 = 0x84d8;
|
||||
gl.TEXTURE25 = 0x84d9;
|
||||
gl.TEXTURE26 = 0x84da;
|
||||
gl.TEXTURE27 = 0x84db;
|
||||
gl.TEXTURE28 = 0x84dc;
|
||||
gl.TEXTURE29 = 0x84dd;
|
||||
gl.TEXTURE3 = 0x84c3;
|
||||
gl.TEXTURE30 = 0x84de;
|
||||
gl.TEXTURE31 = 0x84df;
|
||||
gl.TEXTURE4 = 0x84c4;
|
||||
gl.TEXTURE5 = 0x84c5;
|
||||
gl.TEXTURE6 = 0x84c6;
|
||||
gl.TEXTURE7 = 0x84c7;
|
||||
gl.TEXTURE8 = 0x84c8;
|
||||
gl.TEXTURE9 = 0x84c9;
|
||||
gl.TEXTURE_2D = 0xde1;
|
||||
gl.TEXTURE_3D_OES = 0x806f;
|
||||
gl.TEXTURE_BINDING_2D = 0x8069;
|
||||
gl.TEXTURE_BINDING_3D_OES = 0x806a;
|
||||
gl.TEXTURE_BINDING_CUBE_MAP = 0x8514;
|
||||
gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67;
|
||||
gl.TEXTURE_BORDER_COLOR_NV = 0x1004;
|
||||
gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d;
|
||||
gl.TEXTURE_COMPARE_MODE_EXT = 0x884c;
|
||||
gl.TEXTURE_CUBE_MAP = 0x8513;
|
||||
gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;
|
||||
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;
|
||||
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a;
|
||||
gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;
|
||||
gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;
|
||||
gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;
|
||||
gl.TEXTURE_DEPTH_QCOM = 0x8bd4;
|
||||
gl.TEXTURE_EXTERNAL_OES = 0x8d65;
|
||||
gl.TEXTURE_FORMAT_QCOM = 0x8bd6;
|
||||
gl.TEXTURE_HEIGHT_QCOM = 0x8bd3;
|
||||
gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8;
|
||||
gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f;
|
||||
gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5;
|
||||
gl.TEXTURE_MAG_FILTER = 0x2800;
|
||||
gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe;
|
||||
gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d;
|
||||
gl.TEXTURE_MIN_FILTER = 0x2801;
|
||||
gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9;
|
||||
gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb;
|
||||
gl.TEXTURE_SAMPLES_IMG = 0x9136;
|
||||
gl.TEXTURE_TARGET_QCOM = 0x8bda;
|
||||
gl.TEXTURE_TYPE_QCOM = 0x8bd7;
|
||||
gl.TEXTURE_USAGE_ANGLE = 0x93a2;
|
||||
gl.TEXTURE_WIDTH_QCOM = 0x8bd2;
|
||||
gl.TEXTURE_WRAP_R_OES = 0x8072;
|
||||
gl.TEXTURE_WRAP_S = 0x2802;
|
||||
gl.TEXTURE_WRAP_T = 0x2803;
|
||||
gl.TIMEOUT_EXPIRED_APPLE = 0x911b;
|
||||
gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff;
|
||||
gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0;
|
||||
gl.TRIANGLES = 0x4;
|
||||
gl.TRIANGLE_FAN = 0x6;
|
||||
gl.TRIANGLE_STRIP = 0x5;
|
||||
gl.TRUE = 0x1;
|
||||
gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255;
|
||||
gl.UNPACK_ALIGNMENT = 0xcf5;
|
||||
gl.UNPACK_ROW_LENGTH = 0xcf2;
|
||||
gl.UNPACK_SKIP_PIXELS = 0xcf4;
|
||||
gl.UNPACK_SKIP_ROWS = 0xcf3;
|
||||
gl.UNSIGNALED_APPLE = 0x9118;
|
||||
gl.UNSIGNED_BYTE = 0x1401;
|
||||
gl.UNSIGNED_INT = 0x1405;
|
||||
gl.UNSIGNED_INT64_AMD = 0x8bc2;
|
||||
gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6;
|
||||
gl.UNSIGNED_INT_24_8_OES = 0x84fa;
|
||||
gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368;
|
||||
gl.UNSIGNED_NORMALIZED_EXT = 0x8c17;
|
||||
gl.UNSIGNED_SHORT = 0x1403;
|
||||
gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366;
|
||||
gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033;
|
||||
gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365;
|
||||
gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365;
|
||||
gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034;
|
||||
gl.UNSIGNED_SHORT_5_6_5 = 0x8363;
|
||||
gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba;
|
||||
gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb;
|
||||
gl.VALIDATE_STATUS = 0x8b83;
|
||||
gl.VENDOR = 0x1f00;
|
||||
gl.VERSION = 0x1f02;
|
||||
gl.VERTEX_ARRAY_BINDING_OES = 0x85b5;
|
||||
gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154;
|
||||
gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f;
|
||||
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe;
|
||||
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe;
|
||||
gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
|
||||
gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a;
|
||||
gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
|
||||
gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
|
||||
gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
|
||||
gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
|
||||
gl.VERTEX_SHADER = 0x8b31;
|
||||
gl.VERTEX_SHADER_BIT_EXT = 0x1;
|
||||
gl.VIEWPORT = 0xba2;
|
||||
gl.VIV_shader_binary = 0x1;
|
||||
gl.WAIT_FAILED_APPLE = 0x911d;
|
||||
gl.WRITEONLY_RENDERING_QCOM = 0x8823;
|
||||
gl.WRITE_ONLY_OES = 0x88b9;
|
||||
gl.Z400_BINARY_AMD = 0x8740;
|
||||
gl.ZERO = 0x0;
|
||||
|
||||
gl.UNPACK_FLIP_Y_WEBGL = 0x9240;
|
||||
gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;
|
||||
gl.CONTEXT_LOST_WEBGL = 0x9242;
|
||||
gl.UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;
|
||||
gl.BROWSER_DEFAULT_WEBGL = 0x9244;
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// Prepare JSB environment
|
||||
|
||||
// Hack JavaScriptCore begin
|
||||
|
||||
|
||||
if (window.scriptEngineType == "JavaScriptCore") {
|
||||
window.__jsc_createArrayBufferObject = function(arr) {
|
||||
var len = arr.length;
|
||||
var buffer = new ArrayBuffer(len);
|
||||
var typedArr = new Uint8Array(buffer);
|
||||
for (var i = 0; i < len; ++i) {
|
||||
typedArr[i] = arr[i];
|
||||
}
|
||||
return buffer;
|
||||
};
|
||||
|
||||
window.__jsc_getArrayBufferData = function(arrBuf) {
|
||||
var typedArr = new Uint8Array(arrBuf);
|
||||
var len = typedArr.length;
|
||||
var arr = new Array(len);
|
||||
for (var i = 0; i < len; ++i) {
|
||||
arr[i] = typedArr[i];
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
|
||||
window.__jsc_getTypedArrayData = function(typedArr) {
|
||||
var length = typedArr.byteLength;
|
||||
var offset = typedArr.byteOffset;
|
||||
var buf = typedArr.buffer;
|
||||
var uint8Arr = new Uint8Array(buf);
|
||||
var retArr = new Array(length);
|
||||
var arrIndex = 0;
|
||||
var bufIndex = offset;
|
||||
var bufEnd = offset + length;
|
||||
for (; bufIndex < bufEnd; ++bufIndex, ++arrIndex) {
|
||||
retArr[arrIndex] = uint8Arr[bufIndex];
|
||||
}
|
||||
return retArr;
|
||||
};
|
||||
|
||||
window.__jscTypedArrayConstructor = Object.getPrototypeOf(Uint16Array.prototype).constructor;
|
||||
}
|
||||
|
||||
|
||||
// Hack JavaScriptCore end
|
||||
|
||||
window.cc = window.cc || {};
|
||||
/**
|
||||
* @namespace jsb
|
||||
* @name jsb
|
||||
*/
|
||||
window.jsb = window.jsb || {};
|
||||
|
||||
/**
|
||||
* Common getter setter configuration function
|
||||
* @function
|
||||
* @param {Object} proto A class prototype or an object to config
|
||||
* @param {String} prop Property name
|
||||
* @param {function} getter Getter function for the property
|
||||
* @param {function} setter Setter function for the property
|
||||
*/
|
||||
cc.defineGetterSetter = function (proto, prop, getter, setter){
|
||||
var desc = { enumerable: false, configurable: true };
|
||||
getter && (desc.get = getter);
|
||||
setter && (desc.set = setter);
|
||||
Object.defineProperty(proto, prop, desc);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new object and copy all properties in an exist object to the new object
|
||||
* @method clone
|
||||
* @param {Object|Array} obj - The source object
|
||||
* @return {Array|Object} The created object
|
||||
*/
|
||||
cc.clone = function (obj) {
|
||||
// Cloning is better if the new object is having the same prototype chain
|
||||
// as the copied obj (or otherwise, the cloned object is certainly going to
|
||||
// have a different hidden class). Play with C1/C2 of the
|
||||
// PerformanceVirtualMachineTests suite to see how this makes an impact
|
||||
// under extreme conditions.
|
||||
//
|
||||
// Object.create(Object.getPrototypeOf(obj)) doesn't work well because the
|
||||
// prototype lacks a link to the constructor (Carakan, V8) so the new
|
||||
// object wouldn't have the hidden class that's associated with the
|
||||
// constructor (also, for whatever reasons, utilizing
|
||||
// Object.create(Object.getPrototypeOf(obj)) + Object.defineProperty is even
|
||||
// slower than the original in V8). Therefore, we call the constructor, but
|
||||
// there is a big caveat - it is possible that the this.init() in the
|
||||
// constructor would throw with no argument. It is also possible that a
|
||||
// derived class forgets to set "constructor" on the prototype. We ignore
|
||||
// these possibities for and the ultimate solution is a standardized
|
||||
// Object.clone(<object>).
|
||||
var newObj = (obj.constructor) ? new obj.constructor : {};
|
||||
|
||||
// Assuming that the constuctor above initialized all properies on obj, the
|
||||
// following keyed assignments won't turn newObj into dictionary mode
|
||||
// becasue they're not *appending new properties* but *assigning existing
|
||||
// ones* (note that appending indexed properties is another story). See
|
||||
// CCClass.js for a link to the devils when the assumption fails.
|
||||
for (var key in obj) {
|
||||
var copy = obj[key];
|
||||
// Beware that typeof null == "object" !
|
||||
if (typeof copy === "object" &&
|
||||
copy &&
|
||||
!(copy instanceof _ccsg.Node) &&
|
||||
(CC_JSB || !(copy instanceof HTMLElement))) {
|
||||
newObj[key] = cc.clone(copy);
|
||||
} else {
|
||||
newObj[key] = copy;
|
||||
}
|
||||
}
|
||||
return newObj;
|
||||
};
|
||||
|
||||
|
||||
var ClassManager = {
|
||||
id : (0|(Math.random()*998)),
|
||||
|
||||
instanceId : (0|(Math.random()*998)),
|
||||
|
||||
getNewID : function(){
|
||||
return this.id++;
|
||||
},
|
||||
|
||||
getNewInstanceId : function(){
|
||||
return this.instanceId++;
|
||||
}
|
||||
};
|
||||
//
|
||||
// 2) Using "extend" subclassing
|
||||
// Simple JavaScript Inheritance By John Resig http://ejohn.org/
|
||||
//
|
||||
cc.Class = function(){};
|
||||
cc.Class.extend = function (prop) {
|
||||
var _super = this.prototype,
|
||||
prototype, Class, classId,
|
||||
className = prop._className || "",
|
||||
name, desc;
|
||||
|
||||
// Instantiate a base class (but only create the instance,
|
||||
// don't run the init constructor)
|
||||
initializing = true;
|
||||
prototype = Object.create(_super);
|
||||
initializing = false;
|
||||
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
|
||||
|
||||
// Copy the properties over onto the new prototype
|
||||
for (name in prop) {
|
||||
// Check if we're overwriting an existing function
|
||||
prototype[name] = typeof prop[name] == "function" &&
|
||||
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
|
||||
(function (name, fn) {
|
||||
return function () {
|
||||
var tmp = this._super;
|
||||
|
||||
// Add a new ._super() method that is the same method
|
||||
// but on the super-class
|
||||
this._super = _super[name];
|
||||
|
||||
// The method only need to be bound temporarily, so we
|
||||
// remove it when we're done executing
|
||||
var ret = fn.apply(this, arguments);
|
||||
this._super = tmp;
|
||||
|
||||
return ret;
|
||||
};
|
||||
})(name, prop[name]) :
|
||||
prop[name];
|
||||
}
|
||||
|
||||
Class = function () {
|
||||
if (!initializing) {
|
||||
this.__instanceId = ClassManager.getNewInstanceId();
|
||||
if (this.ctor) {
|
||||
switch (arguments.length) {
|
||||
case 0: this.ctor(); break;
|
||||
case 1: this.ctor(arguments[0]); break;
|
||||
case 2: this.ctor(arguments[0], arguments[1]); break;
|
||||
case 3: this.ctor(arguments[0], arguments[1], arguments[2]); break;
|
||||
case 4: this.ctor(arguments[0], arguments[1], arguments[2], arguments[3]); break;
|
||||
case 5: this.ctor(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); break;
|
||||
default: this.ctor.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Populate our constructed prototype object
|
||||
Class.prototype = prototype;
|
||||
|
||||
// Enforce the constructor to be what we expect
|
||||
Class.prototype.constructor = Class;
|
||||
|
||||
// And make this class extendable
|
||||
Class.extend = cc.Class.extend;
|
||||
|
||||
classId = ClassManager.getNewID();
|
||||
ClassManager[classId] = _super;
|
||||
desc = { writable: true, enumerable: false, configurable: true };
|
||||
Class.id = classId;
|
||||
desc.value = classId;
|
||||
Object.defineProperty(prototype, '__pid', desc);
|
||||
|
||||
return Class;
|
||||
};
|
||||
|
||||
jsb.__obj_ref_id = 0;
|
||||
|
||||
jsb.registerNativeRef = function (owner, target) {
|
||||
if (owner && target && owner !== target) {
|
||||
var targetID = target.__jsb_ref_id;
|
||||
if (targetID === undefined)
|
||||
targetID = target.__jsb_ref_id = jsb.__obj_ref_id++;
|
||||
|
||||
var refs = owner.__nativeRefs;
|
||||
if (!refs) {
|
||||
refs = owner.__nativeRefs = {};
|
||||
}
|
||||
|
||||
refs[targetID] = target;
|
||||
}
|
||||
};
|
||||
|
||||
jsb.unregisterNativeRef = function (owner, target) {
|
||||
if (owner && target && owner !== target) {
|
||||
var targetID = target.__jsb_ref_id;
|
||||
if (targetID === undefined)
|
||||
return;
|
||||
|
||||
var refs = owner.__nativeRefs;
|
||||
if (!refs) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete refs[targetID];
|
||||
}
|
||||
};
|
||||
|
||||
jsb.unregisterAllNativeRefs = function (owner) {
|
||||
if (!owner) return;
|
||||
delete owner.__nativeRefs;
|
||||
};
|
||||
|
||||
jsb.unregisterChildRefsForNode = function (node, recursive) {
|
||||
if (!(node instanceof cc.Node)) return;
|
||||
recursive = !!recursive;
|
||||
var children = node.getChildren(), i, l, child;
|
||||
for (i = 0, l = children.length; i < l; ++i) {
|
||||
child = children[i];
|
||||
jsb.unregisterNativeRef(node, child);
|
||||
if (recursive) {
|
||||
jsb.unregisterChildRefsForNode(child, recursive);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* <p>Properties configuration function </br>
|
||||
* All properties in attrs will be set to the node, </br>
|
||||
* when the setter of the node is available, </br>
|
||||
* the property will be set via setter function.</br>
|
||||
* </p>
|
||||
* @param {Object} attrs Properties to be set to node
|
||||
*/
|
||||
cc.Node.prototype.attr = function(attrs) {
|
||||
for(var key in attrs) {
|
||||
this[key] = attrs[key];
|
||||
}
|
||||
};
|
||||
|
||||
var _proto = cc.Action.prototype;
|
||||
cc.defineGetterSetter(_proto, "tag", _proto.getTag, _proto.setTag);
|
||||
|
||||
// Overrides
|
||||
_proto = cc.Label.prototype;
|
||||
cc.defineGetterSetter(_proto, "size", _proto.getContentSize, _proto.setContentSize);
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
cc.defineGetterSetter(_proto, "boundingWidth", _proto.getWidth, _proto.setWidth);
|
||||
cc.defineGetterSetter(_proto, "boundingHeight", _proto.getHeight, _proto.setHeight);
|
||||
|
||||
_proto = cc.LabelTTF.prototype;
|
||||
cc.defineGetterSetter(_proto, "size", _proto.getContentSize, _proto.setContentSize);
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
|
||||
_proto = cc.LayerColor.prototype;
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
|
||||
_proto = cc.LayerGradient.prototype;
|
||||
cc.defineGetterSetter(_proto, "size", _proto.getContentSize, _proto.setContentSize);
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
|
||||
_proto = cc.Sprite.prototype;
|
||||
cc.defineGetterSetter(_proto, "ignoreAnchor", _proto.isIgnoreAnchorPointForPosition, _proto.ignoreAnchorPointForPosition);
|
||||
|
||||
_proto = cc.MotionStreak.prototype;
|
||||
cc.defineGetterSetter(_proto, "x", _proto.getPositionX, _proto.setPositionX);
|
||||
cc.defineGetterSetter(_proto, "y", _proto.getPositionY, _proto.setPositionY);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.ParticleSystem.prototype;
|
||||
cc.defineGetterSetter(_proto, "rotation", _proto.getRotation, _proto.setRotation);
|
||||
cc.defineGetterSetter(_proto, "scale", _proto.getScale, _proto.setScale);
|
||||
cc.defineGetterSetter(_proto, "scaleX", _proto.getScaleX, _proto.setScaleX);
|
||||
cc.defineGetterSetter(_proto, "scaleY", _proto.getScaleY, _proto.setScaleY);
|
||||
|
||||
// Extends
|
||||
var _proto = cc.ClippingNode.prototype;
|
||||
cc.defineGetterSetter(_proto, "alphaThreshold", _proto.getAlphaThreshold, _proto.setAlphaThreshold);
|
||||
cc.defineGetterSetter(_proto, "inverted", _proto.getInverted, _proto.setInverted);
|
||||
cc.defineGetterSetter(_proto, "stencil", _proto.getStencil, _proto.setStencil);
|
||||
|
||||
_proto = cc.Node.prototype;
|
||||
cc.defineGetterSetter(_proto, "x", _proto.getPositionX, _proto.setPositionX);
|
||||
cc.defineGetterSetter(_proto, "y", _proto.getPositionY, _proto.setPositionY);
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
cc.defineGetterSetter(_proto, "anchorX", _proto._getAnchorX, _proto._setAnchorX);
|
||||
cc.defineGetterSetter(_proto, "anchorY", _proto._getAnchorY, _proto._setAnchorY);
|
||||
cc.defineGetterSetter(_proto, "skewX", _proto.getSkewX, _proto.setSkewX);
|
||||
cc.defineGetterSetter(_proto, "skewY", _proto.getSkewY, _proto.setSkewY);
|
||||
cc.defineGetterSetter(_proto, "zIndex", _proto.getLocalZOrder, _proto.setLocalZOrder);
|
||||
cc.defineGetterSetter(_proto, "vertexZ", _proto.getVertexZ, _proto.setVertexZ);
|
||||
cc.defineGetterSetter(_proto, "rotation", _proto.getRotation, _proto.setRotation);
|
||||
cc.defineGetterSetter(_proto, "rotationX", _proto.getRotationX, _proto.setRotationX);
|
||||
cc.defineGetterSetter(_proto, "rotationY", _proto.getRotationY, _proto.setRotationY);
|
||||
cc.defineGetterSetter(_proto, "scale", _proto.getScale, _proto.setScale);
|
||||
cc.defineGetterSetter(_proto, "scaleX", _proto.getScaleX, _proto.setScaleX);
|
||||
cc.defineGetterSetter(_proto, "scaleY", _proto.getScaleY, _proto.setScaleY);
|
||||
cc.defineGetterSetter(_proto, "children", _proto.getChildren);
|
||||
cc.defineGetterSetter(_proto, "childrenCount", _proto.getChildrenCount);
|
||||
cc.defineGetterSetter(_proto, "parent", _proto.getParent, _proto.setParent);
|
||||
cc.defineGetterSetter(_proto, "visible", _proto.isVisible, _proto.setVisible);
|
||||
cc.defineGetterSetter(_proto, "running", _proto.isRunning);
|
||||
cc.defineGetterSetter(_proto, "ignoreAnchor", _proto.isIgnoreAnchorPointForPosition, _proto.ignoreAnchorPointForPosition);
|
||||
cc.defineGetterSetter(_proto, "actionManager", _proto.getActionManager, _proto.setActionManager);
|
||||
cc.defineGetterSetter(_proto, "scheduler", _proto.getScheduler, _proto.setScheduler);
|
||||
cc.defineGetterSetter(_proto, "shaderProgram", _proto.getShaderProgram, _proto.setShaderProgram);
|
||||
cc.defineGetterSetter(_proto, "glServerState", _proto.getGLServerState, _proto.setGLServerState);
|
||||
cc.defineGetterSetter(_proto, "tag", _proto.getTag, _proto.setTag);
|
||||
cc.defineGetterSetter(_proto, "userObject", _proto.getUserObject, _proto.setUserObject);
|
||||
cc.defineGetterSetter(_proto, "arrivalOrder", _proto.getOrderOfArrival, _proto.setOrderOfArrival);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.LabelTTF.prototype;
|
||||
cc.defineGetterSetter(_proto, "string", _proto.getString, _proto.setString);
|
||||
cc.defineGetterSetter(_proto, "textAlign", _proto.getHorizontalAlignment, _proto.setHorizontalAlignment);
|
||||
cc.defineGetterSetter(_proto, "verticalAlign", _proto.getVerticalAlignment, _proto.setVerticalAlignment);
|
||||
cc.defineGetterSetter(_proto, "fontSize", _proto.getFontSize, _proto.setFontSize);
|
||||
cc.defineGetterSetter(_proto, "fontName", _proto.getFontName, _proto.setFontName);
|
||||
cc.defineGetterSetter(_proto, "font", _proto._getFont, _proto._setFont);
|
||||
cc.defineGetterSetter(_proto, "boundingWidth", _proto._getBoundingWidth, _proto._setBoundingWidth);
|
||||
cc.defineGetterSetter(_proto, "boundingHeight", _proto._getBoundingHeight, _proto._setBoundingHeight);
|
||||
cc.defineGetterSetter(_proto, "fillStyle", _proto._getFillStyle, _proto.setFontFillColor);
|
||||
cc.defineGetterSetter(_proto, "strokeStyle", _proto._getStrokeStyle, _proto._setStrokeStyle);
|
||||
cc.defineGetterSetter(_proto, "lineWidth", _proto._getLineWidth, _proto._setLineWidth);
|
||||
cc.defineGetterSetter(_proto, "shadowOffsetX", _proto._getShadowOffsetX, _proto._setShadowOffsetX);
|
||||
cc.defineGetterSetter(_proto, "shadowOffsetY", _proto._getShadowOffsetY, _proto._setShadowOffsetY);
|
||||
cc.defineGetterSetter(_proto, "shadowOpacity", _proto._getShadowOpacity, _proto._setShadowOpacity);
|
||||
cc.defineGetterSetter(_proto, "shadowBlur", _proto._getShadowBlur, _proto._setShadowBlur);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.LayerColor.prototype;
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth, _proto._setWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight, _proto._setHeight);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.LayerGradient.prototype;
|
||||
cc.defineGetterSetter(_proto, "startColor", _proto.getStartColor, _proto.setStartColor);
|
||||
cc.defineGetterSetter(_proto, "endColor", _proto.getEndColor, _proto.setEndColor);
|
||||
cc.defineGetterSetter(_proto, "startOpacity", _proto.getStartOpacity, _proto.setStartOpacity);
|
||||
cc.defineGetterSetter(_proto, "endOpacity", _proto.getEndOpacity, _proto.setEndOpacity);
|
||||
cc.defineGetterSetter(_proto, "vector", _proto.getVector, _proto.setVector);
|
||||
cc.defineGetterSetter(_proto, "compresseInterpolation", _proto.isCompressedInterpolation, _proto.setCompressedInterpolation);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.Sprite.prototype;
|
||||
cc.defineGetterSetter(_proto, "dirty", _proto.getDirty, _proto.setDirty);
|
||||
cc.defineGetterSetter(_proto, "flippedX", _proto.isFlippedX, _proto.setFlippedX);
|
||||
cc.defineGetterSetter(_proto, "flippedY", _proto.isFlippedY, _proto.setFlippedY);
|
||||
cc.defineGetterSetter(_proto, "offsetX", _proto._getOffsetX);
|
||||
cc.defineGetterSetter(_proto, "offsetY", _proto._getOffsetY);
|
||||
cc.defineGetterSetter(_proto, "atlasIndex", _proto.getAtlasIndex, _proto.setAtlasIndex);
|
||||
cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture);
|
||||
cc.defineGetterSetter(_proto, "textureRectRotated", _proto.isTextureRectRotated);
|
||||
cc.defineGetterSetter(_proto, "textureAtlas", _proto.getTextureAtlas, _proto.setTextureAtlas);
|
||||
cc.defineGetterSetter(_proto, "batchNode", _proto.getBatchNode, _proto.setBatchNode);
|
||||
cc.defineGetterSetter(_proto, "quad", _proto.getQuad);
|
||||
cc.defineGetterSetter(_proto, "opacity", _proto.getOpacity, _proto.setOpacity);
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "cascadeOpacity", _proto.isCascadeOpacityEnabled, _proto.setCascadeOpacityEnabled);
|
||||
cc.defineGetterSetter(_proto, "color", _proto.getColor, _proto.setColor);
|
||||
cc.defineGetterSetter(_proto, "cascadeColor", _proto.isCascadeColorEnabled, _proto.setCascadeColorEnabled);
|
||||
|
||||
_proto = cc.Texture2D.prototype;
|
||||
cc.defineGetterSetter(_proto, "name", _proto.getName);
|
||||
cc.defineGetterSetter(_proto, "pixelFormat", _proto.getPixelFormat);
|
||||
cc.defineGetterSetter(_proto, "pixelsWidth", _proto.getPixelsWide);
|
||||
cc.defineGetterSetter(_proto, "pixelsHeight", _proto.getPixelsHigh);
|
||||
cc.defineGetterSetter(_proto, "width", _proto._getWidth);
|
||||
cc.defineGetterSetter(_proto, "height", _proto._getHeight);
|
||||
cc.defineGetterSetter(_proto, "shaderProgram", _proto.getShaderProgram, _proto.setShaderProgram);
|
||||
cc.defineGetterSetter(_proto, "maxS", _proto.getMaxS, _proto.setMaxS);
|
||||
cc.defineGetterSetter(_proto, "maxT", _proto.getMaxT, _proto.setMaxT);
|
||||
cc.defineGetterSetter(cc.Texture2D, "defaultPixelFormat", cc.Texture2D.getDefaultAlphaPixelFormat, cc.Texture2D.setDefaultAlphaPixelFormat);
|
||||
|
||||
_proto = cc.ParticleBatchNode.prototype;
|
||||
cc.defineGetterSetter(_proto, "textureAtlas", _proto.getTextureAtlas, _proto.setTextureAtlas);
|
||||
cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture);
|
||||
|
||||
_proto = cc.ParticleSystem.prototype;
|
||||
cc.defineGetterSetter(_proto, "opacityModifyRGB", _proto.isOpacityModifyRGB, _proto.setOpacityModifyRGB);
|
||||
cc.defineGetterSetter(_proto, "batchNode", _proto.getBatchNode, _proto.setBatchNode);
|
||||
cc.defineGetterSetter(_proto, "active", _proto.isActive);
|
||||
cc.defineGetterSetter(_proto, "shapeType", _proto.getShapeType, _proto.setShapeType);
|
||||
cc.defineGetterSetter(_proto, "atlasIndex", _proto.getAtlasIndex, _proto.setAtlasIndex);
|
||||
cc.defineGetterSetter(_proto, "particleCount", _proto.getParticleCount, _proto.setParticleCount);
|
||||
cc.defineGetterSetter(_proto, "duration", _proto.getDuration, _proto.setDuration);
|
||||
cc.defineGetterSetter(_proto, "sourcePos", _proto.getSourcePosition, _proto.setSourcePosition);
|
||||
cc.defineGetterSetter(_proto, "posVar", _proto.getPosVar, _proto.setPosVar);
|
||||
cc.defineGetterSetter(_proto, "life", _proto.getLife, _proto.setLife);
|
||||
cc.defineGetterSetter(_proto, "lifeVar", _proto.getLifeVar, _proto.setLifeVar);
|
||||
cc.defineGetterSetter(_proto, "angle", _proto.getAngle, _proto.setAngle);
|
||||
cc.defineGetterSetter(_proto, "angleVar", _proto.getAngleVar, _proto.setAngleVar);
|
||||
cc.defineGetterSetter(_proto, "startSize", _proto.getStartSize, _proto.setStartSize);
|
||||
cc.defineGetterSetter(_proto, "startSizeVar", _proto.getStartSizeVar, _proto.setStartSizeVar);
|
||||
cc.defineGetterSetter(_proto, "endSize", _proto.getEndSize, _proto.setEndSize);
|
||||
cc.defineGetterSetter(_proto, "endSizeVar", _proto.getEndSizeVar, _proto.setEndSizeVar);
|
||||
cc.defineGetterSetter(_proto, "startSpin", _proto.getStartSpin, _proto.setStartSpin);
|
||||
cc.defineGetterSetter(_proto, "startSpinVar", _proto.getStartSpinVar, _proto.setStartSpinVar);
|
||||
cc.defineGetterSetter(_proto, "endSpin", _proto.getEndSpin, _proto.setEndSpin);
|
||||
cc.defineGetterSetter(_proto, "endSpinVar", _proto.getEndSpinVar, _proto.setEndSpinVar);
|
||||
cc.defineGetterSetter(_proto, "gravity", _proto.getGravity, _proto.setGravity);
|
||||
cc.defineGetterSetter(_proto, "speed", _proto.getSpeed, _proto.setSpeed);
|
||||
cc.defineGetterSetter(_proto, "speedVar", _proto.getSpeedVar, _proto.setSpeedVar);
|
||||
cc.defineGetterSetter(_proto, "tangentialAccel", _proto.getTangentialAccel, _proto.setTangentialAccel);
|
||||
cc.defineGetterSetter(_proto, "tangentialAccelVar", _proto.getTangentialAccelVar, _proto.setTangentialAccelVar);
|
||||
cc.defineGetterSetter(_proto, "tangentialAccel", _proto.getTangentialAccel, _proto.setTangentialAccel);
|
||||
cc.defineGetterSetter(_proto, "tangentialAccelVar", _proto.getTangentialAccelVar, _proto.setTangentialAccelVar);
|
||||
cc.defineGetterSetter(_proto, "rotationIsDir", _proto.getRotationIsDir, _proto.setRotationIsDir);
|
||||
cc.defineGetterSetter(_proto, "startRadius", _proto.getStartRadius, _proto.setStartRadius);
|
||||
cc.defineGetterSetter(_proto, "startRadiusVar", _proto.getStartRadiusVar, _proto.setStartRadiusVar);
|
||||
cc.defineGetterSetter(_proto, "endRadius", _proto.getEndRadius, _proto.setEndRadius);
|
||||
cc.defineGetterSetter(_proto, "endRadiusVar", _proto.getEndRadiusVar, _proto.setEndRadiusVar);
|
||||
cc.defineGetterSetter(_proto, "rotatePerS", _proto.getRotatePerSecond, _proto.setRotatePerSecond);
|
||||
cc.defineGetterSetter(_proto, "rotatePerSVar", _proto.getRotatePerSecondVar, _proto.setRotatePerSecondVar);
|
||||
cc.defineGetterSetter(_proto, "startColor", _proto.getStartColor, _proto.setStartColor);
|
||||
cc.defineGetterSetter(_proto, "startColorVar", _proto.getStartColorVar, _proto.setStartColorVar);
|
||||
cc.defineGetterSetter(_proto, "endColor", _proto.getEndColor, _proto.setEndColor);
|
||||
cc.defineGetterSetter(_proto, "endColorVar", _proto.getEndColorVar, _proto.setEndColorVar);
|
||||
cc.defineGetterSetter(_proto, "emissionRate", _proto.getEmissionRate, _proto.setEmissionRate);
|
||||
cc.defineGetterSetter(_proto, "emitterMode", _proto.getEmitterMode, _proto.setEmitterMode);
|
||||
cc.defineGetterSetter(_proto, "positionType", _proto.getPositionType, _proto.setPositionType);
|
||||
cc.defineGetterSetter(_proto, "totalParticles", _proto.getTotalParticles, _proto.setTotalParticles);
|
||||
cc.defineGetterSetter(_proto, "autoRemoveOnFinish", _proto.getAutoRemoveOnFinish, _proto.setAutoRemoveOnFinish);
|
||||
cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture);
|
||||
|
||||
_proto = cc.RenderTexture.prototype;
|
||||
cc.defineGetterSetter(_proto, "sprite", _proto.getSprite, _proto.setSprite);
|
||||
cc.defineGetterSetter(_proto, "clearFlags", _proto.getClearFlags, _proto.setClearFlags);
|
||||
cc.defineGetterSetter(_proto, "clearDepthVal", _proto.getClearDepthVal, _proto.setClearDepthVal);
|
||||
cc.defineGetterSetter(_proto, "clearStencilVal", _proto.getClearStencilVal, _proto.setClearStencilVal);
|
||||
cc.defineGetterSetter(_proto, "clearColorVal", _proto.getClearColor, _proto.setClearColor);
|
||||
cc.defineGetterSetter(_proto, "autoDraw", _proto.getAutoDraw, _proto.setAutoDraw);
|
||||
|
||||
_proto = cc.TMXLayer.prototype;
|
||||
cc.defineGetterSetter(_proto, "tiles", _proto.getTiles, _proto.setTiles);
|
||||
cc.defineGetterSetter(_proto, "tileset", _proto.getTileset, _proto.setTileset);
|
||||
cc.defineGetterSetter(_proto, "layerOrientation", _proto.getLayerOrientation, _proto.setLayerOrientation);
|
||||
cc.defineGetterSetter(_proto, "properties", _proto.getProperties, _proto.setProperties);
|
||||
cc.defineGetterSetter(_proto, "layerName", _proto.getLayerName, _proto.setLayerName);
|
||||
cc.defineGetterSetter(_proto, "layerWidth", _proto._getLayerWidth, _proto._setLayerWidth);
|
||||
cc.defineGetterSetter(_proto, "layerHeight", _proto._getLayerHeight, _proto._setLayerHeight);
|
||||
cc.defineGetterSetter(_proto, "tileWidth", _proto._getTileWidth, _proto._setTileWidth);
|
||||
cc.defineGetterSetter(_proto, "tileHeight", _proto._getTileHeight, _proto._setTileHeight);
|
||||
cc.defineGetterSetter(_proto, "texture", _proto.getTexture, _proto.setTexture);
|
||||
|
||||
_proto = cc.TMXTiledMap.prototype;
|
||||
cc.defineGetterSetter(_proto, "properties", _proto.getProperties, _proto.setProperties);
|
||||
cc.defineGetterSetter(_proto, "mapOrientation", _proto.getMapOrientation, _proto.setMapOrientation);
|
||||
cc.defineGetterSetter(_proto, "objectGroups", _proto.getObjectGroups, _proto.setObjectGroups);
|
||||
cc.defineGetterSetter(_proto, "mapWidth", _proto._getMapWidth, _proto._setMapWidth);
|
||||
cc.defineGetterSetter(_proto, "mapHeight", _proto._getMapHeight, _proto._setMapHeight);
|
||||
cc.defineGetterSetter(_proto, "tileWidth", _proto._getTileWidth, _proto._setTileWidth);
|
||||
cc.defineGetterSetter(_proto, "tileHeight", _proto._getTileHeight, _proto._setTileHeight);
|
||||
@@ -1,215 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
function _safeExtend(obj, list) {
|
||||
for (var key in list)
|
||||
if(!obj[key])
|
||||
obj[key] = list[key];
|
||||
}
|
||||
function _forceExtend(obj, list) {
|
||||
for (var key in list)
|
||||
obj[key] = list[key];
|
||||
}
|
||||
|
||||
function _customUndefined(message) {
|
||||
return function() {
|
||||
cc.log("Not implemented yet in JSB");
|
||||
message && cc.log(message);
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
|
||||
var _undefined = {
|
||||
_jsbUndefined: function(message) {
|
||||
cc.log("Not implemented yet in JSB");
|
||||
return undefined;
|
||||
},
|
||||
_shadowUndefined: _customUndefined("Please use enableShadow function"),
|
||||
_strokeUndefined: _customUndefined("Please use enableStroke function")
|
||||
};
|
||||
|
||||
_safeExtend(cc.Node.prototype, {
|
||||
_getWidth: function() {
|
||||
return this.getContentSize().width;
|
||||
},
|
||||
_getHeight: function() {
|
||||
return this.getContentSize().height;
|
||||
},
|
||||
|
||||
_setWidth: function(width) {
|
||||
this.setContentSize(width, this.getContentSize().height);
|
||||
},
|
||||
_setHeight: function(height) {
|
||||
this.setContentSize(this.getContentSize().width, height);
|
||||
},
|
||||
|
||||
_getAnchorX: function() {
|
||||
return this.getAnchorPoint().x;
|
||||
},
|
||||
_getAnchorY: function() {
|
||||
return this.getAnchorPoint().y;
|
||||
},
|
||||
|
||||
_setAnchorX: function(x) {
|
||||
this.setAnchorPoint(cc.p(x, this.getAnchorPoint().y));
|
||||
},
|
||||
_setAnchorY: function(y) {
|
||||
this.setAnchorPoint(cc.p(this.getAnchorPoint().x, y));
|
||||
}
|
||||
});
|
||||
|
||||
_safeExtend(cc.LabelTTF.prototype, {
|
||||
_fontStyleRE: /^(\d+)px\s+['"]?([\w\s\d]+)['"]?$/,
|
||||
|
||||
_getFont: function() {
|
||||
var size = this.getFontSize();
|
||||
var name = this.getFontName();
|
||||
return size + "px '" + name + "'";
|
||||
},
|
||||
|
||||
_setFont: function(fontStyle) {
|
||||
var res = this._fontStyleRE.exec(fontStyle);
|
||||
if(res) {
|
||||
this.setFontSize(parseInt(res[1]));
|
||||
this.setFontName(res[2]);
|
||||
}
|
||||
},
|
||||
|
||||
_getBoundingWidth: function() {
|
||||
return this.getDimensions().width;
|
||||
},
|
||||
_getBoundingHeight: function() {
|
||||
return this.getDimensions().height;
|
||||
},
|
||||
|
||||
_setBoundingWidth: function(w) {
|
||||
var size = cc.size(w, this.getDimensions().height);
|
||||
this.setDimensions(size);
|
||||
},
|
||||
_setBoundingHeight: function(h) {
|
||||
var size = cc.size(this.getDimensions().width, h);
|
||||
this.setDimensions(size);
|
||||
},
|
||||
|
||||
_getFillStyle: _undefined._jsbUndefined,
|
||||
_getStrokeStyle: _undefined._strokeUndefined,
|
||||
_setStrokeStyle: _undefined._strokeUndefined,
|
||||
_getLineWidth: _undefined._strokeUndefined,
|
||||
_setLineWidth: _undefined._strokeUndefined,
|
||||
_getShadowOffsetX: _undefined._shadowUndefined,
|
||||
_setShadowOffsetX: _undefined._shadowUndefined,
|
||||
_getShadowOffsetY: _undefined._shadowUndefined,
|
||||
_setShadowOffsetY: _undefined._shadowUndefined,
|
||||
_getShadowOpacity: _undefined._shadowUndefined,
|
||||
_setShadowOpacity: _undefined._shadowUndefined,
|
||||
_getShadowBlur: _undefined._shadowUndefined,
|
||||
_setShadowBlur: _undefined._shadowUndefined
|
||||
});
|
||||
|
||||
_safeExtend(cc.Sprite.prototype, {
|
||||
_getOffsetX: function() {
|
||||
return this.getOffsetPosition().x;
|
||||
},
|
||||
_getOffsetY: function() {
|
||||
return this.getOffsetPosition().y;
|
||||
}
|
||||
});
|
||||
|
||||
_safeExtend(cc.TMXLayer.prototype, {
|
||||
_getLayerWidth: function() {
|
||||
return this.getLayerSize().width;
|
||||
},
|
||||
_getLayerHeight: function() {
|
||||
return this.getLayerSize().height;
|
||||
},
|
||||
|
||||
_setLayerWidth: function(w) {
|
||||
var size = cc.size(w, this.getLayerSize().height);
|
||||
this.setLayerSize(size);
|
||||
},
|
||||
_setLayerHeight: function(h) {
|
||||
var size = cc.size(this.getLayerSize().width, h);
|
||||
this.setLayerSize(size);
|
||||
},
|
||||
|
||||
_getTileWidth: function() {
|
||||
return this.getMapTileSize().width;
|
||||
},
|
||||
_getTileHeight: function() {
|
||||
return this.getMapTileSize().height;
|
||||
},
|
||||
|
||||
_setTileWidth: function(w) {
|
||||
var size = cc.size(w, this.getMapTileSize().height);
|
||||
this.setMapTileSize(size);
|
||||
},
|
||||
_setTileHeight: function(h) {
|
||||
var size = cc.size(this.getMapTileSize().width, h);
|
||||
this.setMapTileSize(size);
|
||||
}
|
||||
});
|
||||
|
||||
_safeExtend(cc.TMXTiledMap.prototype, {
|
||||
_getMapWidth: function() {
|
||||
return this.getMapSize().width;
|
||||
},
|
||||
_getMapHeight: function() {
|
||||
return this.getMapSize().height;
|
||||
},
|
||||
|
||||
_setMapWidth: function(w) {
|
||||
var size = cc.size(w, this.getMapSize().height);
|
||||
this.setMapSize(size);
|
||||
},
|
||||
_setMapHeight: function(h) {
|
||||
var size = cc.size(this.getMapSize().width, h);
|
||||
this.setMapSize(size);
|
||||
},
|
||||
|
||||
_getTileWidth: function() {
|
||||
return this.getTileSize().width;
|
||||
},
|
||||
_getTileHeight: function() {
|
||||
return this.getTileSize().height;
|
||||
},
|
||||
|
||||
_setTileWidth: function(w) {
|
||||
var size = cc.size(w, this.getTileSize().height);
|
||||
this.setTileSize(size);
|
||||
},
|
||||
_setTileHeight: function(h) {
|
||||
var size = cc.size(this.getTileSize().width, h);
|
||||
this.setTileSize(size);
|
||||
}
|
||||
});
|
||||
|
||||
_safeExtend(cc.Texture2D.prototype, {
|
||||
_getWidth : function(){
|
||||
return this.getContentSize().width;
|
||||
},
|
||||
_getHeight : function(){
|
||||
return this.getContentSize().height;
|
||||
}
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
sp.ANIMATION_EVENT_TYPE = {
|
||||
START: 0,
|
||||
INTERRUPT: 1,
|
||||
END: 2,
|
||||
DISPOSE: 3,
|
||||
COMPLETE: 4,
|
||||
EVENT: 5
|
||||
};
|
||||
|
||||
// The methods are added to be compatibility with old versions.
|
||||
sp.SkeletonAnimation.prototype.setCompleteListener = function (listener) {
|
||||
this._compeleteListener = listener;
|
||||
this.setCompleteListenerNative(function (trackEntry) {
|
||||
var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
|
||||
this._compeleteListener(trackEntry, loopCount);
|
||||
});
|
||||
};
|
||||
|
||||
// Temporary solution before upgrade the Spine API
|
||||
sp.SkeletonAnimation.prototype.setAnimationListener = function (target, callback) {
|
||||
this._target = target;
|
||||
this._callback = callback;
|
||||
|
||||
this.setStartListener(function (trackEntry) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.START, null, 0);
|
||||
}
|
||||
});
|
||||
|
||||
this.setInterruptListener(function (trackEntry) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.INTERRUPT, null, 0);
|
||||
}
|
||||
});
|
||||
|
||||
this.setEndListener(function (trackEntry) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.END, null, 0);
|
||||
}
|
||||
});
|
||||
|
||||
this.setDisposeListener(function (trackEntry) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.DISPOSE, null, 0);
|
||||
}
|
||||
});
|
||||
|
||||
this.setCompleteListener(function (trackEntry, loopCount) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, loopCount);
|
||||
}
|
||||
});
|
||||
|
||||
this.setEventListener(function (trackEntry, event) {
|
||||
if (this._target && this._callback) {
|
||||
this._callback.call(this._target, this, trackEntry, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0);
|
||||
}
|
||||
});
|
||||
};
|
||||
Submodule native/tools/bindings-generator updated: 44a66e34a0...95536521cf
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user